Вы находитесь на странице: 1из 207

Introduction

Last week I attended an interview with Infosys, Chennai. When I entered the compound,
there were very many candidates. The atmosphere and culture in Infosys was very nice.
Please find the original article here : http://sibeeshpassion.com/Infosys-InterviewQuestions-For-DotNet-Professionals.html
You can read another series of interview questions here : http://www.csharpcorner.com/UploadFile/65794e/dot-net-interview-questions-for-experienced-andfresher/
Background
I have attended many interviews in my life. But the interview with Infosys was something
different. I thought to share that experience with you all.
Points to be remember
(There are some mistakes I made in the interview. I don't want you to do the same :) )
1. Please ensure that you are maintaining eye contact with the interviewer.
2. Be confident of what you say. Don't change your answer if the interviewer tries to
make you do so.
3. Please avoid the unwanted examples.
4. Please never use any other technical terms that may provoke the interviewer into
asking questions about.
5. If you don't know the answer, please say "I don't know". It is always better to say
so instead of going with the wrong answer.
You can find more tips here: How to Prepare for a Job Interview
Questions asked and answers
(Here I am giving the answers that I answered .)
1. Tell me about yourself?
A. You can find many answers to this question in the internet. Please see the following
link:
Tell me about yourself
2. What is your role in your project? What is the team size?
A. I said "My main role is coding, unit testing, big fixing and maintenance. My team size is
7".
3. What is the hierarchy of your team?
A. First I was confused by this question. Then I answered "Project Manager, Team Leader,
Software Engineers, Trainees".
4. Describe the projects that you have worked on?

A. I described them. Please include the technologies you used in your projects and what
kind of architecture (for example: 3-tire, n- tier) you used.
5. What is the employee size in your company? You don't need to be accurate. You can
provide the approximate value.
A. I said "150 to 200".
Then he moved to the programming section.
6. Write an algorithm and program to determine whether or not a word is a palindrome.
We can do it in either of the following two ways:
a) Using a built-in function as in the following:
1.

string strRev,strReal = null;

2.

Console.WriteLine("Enter the string..");

3.

strReal = Console.ReadLine();

4.

char[] tmpChar = strReal.ToCharArray();

5.

Array.Reverse(tmpChar);

6.

strRev=new string(tmpChar);

7.

if(strReal.Equals(strRev, StringComparison.OrdinalIgnoreCase))

8.

9.

Console.WriteLine("The string is pallindrome");

10. }
11. else
12. {
13.

Console.WriteLine("The string is not pallindrome");

14. }
15.

Console.ReadLine();

Ref: To check string is palindrome or not in .NET (C#)


b) Without using a built-in function.
When I wrote the first program, the interviewer asked me to write the same without using
a built-in function.
1.

private static bool chkPallindrome(string strVal)

2.

3.

try

4.

5.

int min = 0;

6.

int max = strVal.Length - 1;

7.

while (true)

8.

9.

if (min > max)

10.

return true;

11.

char minChar = strVal[min];

12.

char maxChar = strVal[max];

13.

if (char.ToLower(minChar) != char.ToLower(maxChar))

14.

15.

return false;

16.

17.

min++;

18.

max--;

19.

20.

21.

catch (Exception)

22.

23.
24.

throw;

25.
26.

}
}

Ref: You can find more here: C# Palindrome


7. Write a program to determine the count of a specific character in a string.
A.

1.

using System;

2.

using System.Collections.Generic;

3.

using System.Linq;

4.

using System.Text;

5.
6.

namespace FindCountCharOccurance

7.

8.

class Program

9.

10.

static void Main(string[] args)

11.

12.
13.

string strOccur,strChar = null;


Console.WriteLine("Enter the string in which you need to find the count of a char oc
curance");

14.

strOccur = Console.ReadLine();

15.
16.

Console.WriteLine("Enter the char to be searched..");

17.

strChar = Console.ReadLine();

18.

int intCnt =strOccur.Length- strOccur.Replace(strChar, string.Empty).Length;

19.

Console.WriteLine("Count of occurance is "+intCnt);

20.

Console.ReadLine();

21.

22.

23. }

Please see this for more suggestions: count the number of characters in a string.
8. Next he gave me a program like the following and asked me what the output of this
will be.
1.
2.

public class A
{

3.

public int A()

4.

5.

Console.WriteLine("Hi you are in class A");

6.

7.

A. I said "Here we have a constructor A; a constructor should not have a return type. So
the code above will throw a compilation error."
9. What may be the output of the following program?
1.

using System;

2.

using System.Collections.Generic;

3.

using System.Linq;

4.

using System.Text;

5.
6.

namespace RefClass

7.

8.

class Program

9.

10.

static void Main(string[] args)

11.

12.

B bObj= new B();

13.

Console.ReadLine();

14.
15.

16.

17.

public class A

18.

19.

public A()

20.

21.

Console.WriteLine("Hi you are in class A");

22.

23.

24.
25.

public class B:A

26.

27.

public B()

28.

29.

Console.WriteLine("Hi you are in class B");

30.

31.

32. }

A. I said the output will be:


Hi you are in class A
Hi you are in class B
Even though you are creating an object of the derived class, it will invoke the base class
first.
10. Write the output of the following program.
1.
2.

class Program
{

3.

static void Main(string[] args)

4.

5.

B bObj= new B(2);

6.

Console.ReadLine();

7.
8.

9.

10.

public class A

11.

12.

public A()

13.

14.

Console.WriteLine("Hi you are in class A");

15.

16.
17.

public A(int x)

18.

19.
20.
21.

}
}

22.
23.

public class B:A

24.

25.

public B()

26.

27.

Console.WriteLine("Hi you are in class B");

28.
29.

}
}

A. It will throw a compilation error.


B does not contain a constructor that takes 1 argument. If you want to make this
program run, you must create a parameterized constructor for class B also.
11. Abstract and interface real time examples
B.Please read it here: Real time example of interface
12. Describe authentication, types, differences?
A. Forms, Windows, Passport. Please read more here: ASP.NET authentication and
authorization
13. Why DBMS? Why don't we save data in separate files?
A. I didn't know what exactly he meant, I got stuck there for a while. Finally I came up
with the answer that "Normalization" is the main advantage of a DBMS.
Read more here: Why use a DBMS?
14. What is the differences between a Primary key and a Unique key?

A. Primary key doesn't allow NULL, a unique key does.


15. What exactly is happening when we make a field a primary key?
A. A clustered index will be created for that specific field.
16. How may clustered index we can create in table?
A. Basically we can create only one clustered index, but there is a way to have more.
Please read here: Only one clustered index can be created on table <Tablename>.
(Visual Database Tools)
17. What is the difference between a clustered and a non-clustered index?
A. I explained, please read here: Clustered and Non-Clustered Index in SQL 2005
18. What is a Distributed System?
A. A collection of autonomous computers.
http://www.csc.villanova.edu/~schragge/CSC8530/Intro.html

Image Courtesy : http://msdn.microsoft.com/en-us/library/cc239737.aspx


19. What will be the output for the below mentioned lines in JQuery?

1.

alert('5' + 5 + 5);

2.

alert(5 + 5 + '5');

3.

alert(5 + '5' + '5');

4.

alert(5 + '5' );

That was little tricky at that time. For a while I thought, and I just wrote the question to a
paper, and replied.
1.

alert('5' + 5 + 5);

Output= 555

2.

alert(5 + 5 + '5');

Output=105

3.

alert(5 + '5' + '5'); Output=555

4.

alert(5 + '5' );

Output=55

Hmmm finally he said "You are selected for the next round" :)
Next was the direct HR round. That was a simple round. He just asked me to fill in some
forms.
Finally they sent me an Offer Letter :)
Wish you good luck.

Lets Face my .NET Interview


The title of this article is likely to make you curious and cause you to look at it. OK, let me
explain the purpose of this article. Today I attended a .NET technical interview (and got
clear in the first round though I am not at all interested to join there) in a company (I am
not disclosing the company name). And while travelling by bus, I was thinking about what
to write for another article in c-sharpcorner.com.
Then I decided that ok, let's write all my interview questions with my experiences and
answers. Now it's the evening and I am providing my interview experiences from a few
hours before.
Let's clarify some thing first. I have 9 months of experience and the interview questions
have been that basic. So, if you are very much experienced or .NET savvy then it may
seem that I am kidding with you.
OK, no more talking. Sit next to me and hear our conversation. It's only a 1:1 interview.
He offer me a chair when I enter in the room. I saw that he was reading my CV and
highlighting a few portions with pencil (Hmm, loading ammunition for him to use). I took
a seat and was waiting for his response.

He started with an ice-breaking question.


Tell me about yourself.
I told him a little of my background, my academics and a little bit about current and
previous projects.
Have you used Infragestic and Telerik controls?
I said yes, as I said in my CV.
Which kind of control and version?
Q2 version, many controls like drop down list, combo box, list box, grid and so on and so
on.
Then he starts to ask questions about SQL Server.
How many categories are there in SQL command?
Three, DDL, DML ,TCL and a few examples about them.
Structure of join query
I had drawn a tree structure to show various types of joins with Venn diagram.
What is self join and their uses?
A self join is needed when we want to make a join of one table with itself. Then I gave a
small example.
Difference between left and left outer join
Left and left outer join are the same, there is no difference between them.
Is the outer keyword mandatory?
No.
Implement a try catch block in PL/SQL
I gave a small structure of a try catch block.
How to define transactions?

10

I gave an exmple of beginning a transaction and ending a transaction within a try catch
block, if the try raises an error then a rollback will occur within the catch.
Find the third highest salary from a table.
It's a very popular one. I provided an answer with a nested query. First fetch the top 3
highest salaries from the table then filter and pick the minimum one from them. He
asked me to find another method, but at that moment I could not think of an alternative.
Give an example of a nested query.
I have referred to the previous example (of the third highest salary) since I wrote it using
a nested query.
Temporary table and table variable syntax
I provided an example with # and @ symbols.
Difference between local temp table and global temp table
Local temp table (starts with #) has the current user's session scope wherea a global
temp table (starts with ##) has all user's scope.
Save point of transaction
A Save point is needed to rollback up to a certain point.
One insert statement to enter multiple rows.
Written using the following insert command.
Insert into <table> values(1,'a')(2,'b')
I had forgotten to provide a comma between each value pair. He point it out and
corrected me.
What are ldf and mdf files
They are two files of SQL Server and I explained a little about them.
Syntax of function and trigger
I wrote the basic syntax of them. I made the mistake of not writing returns in the
functions. He pointed it out and told me.
Types of trigger
I explained two types of triggers (instead of and after) and a little explanation about
them, when they fire and so on and group by and and having clauses.
I gave an answer with one example to calculate the sum of a salary group by
department. Where we can add a having clause to filter it again.
Find duplicate records
After a little struggle, I wrote one but it was not perfect. (Hmm,. my grip had slipped a
little.)

11

What is a view?
I answered with a small example and also added how to make an index on a view.
Difference between primary key and unique key
It's a very common and popular question. I provided two differences. That is what he was
expecting.
What is a candidate key?
I answered with a small example of a student table. Where roll is the primary key and
registration number is the candidate key.
Then he began to ask about .NET and C# (though it was very basic).
Draw architecture of .NET framework
I had drawn a complete architecture. He told me to point out the location of Entity
Framework and how LINQ provides abstraction on ADO.NET classes.
Latest version of C#
I directly came to the point that he wanted. Yes, asynchronous programming.
What is CLS and CTS?
Discuss them with a little technical knowledge.
How to see IL code?
Answered about ILDASM.
How to collect garbage?
Started to talk about GC.Collect() (it's an overloaded function) and about generation, how
objects are promoted from one generation to another generation and so on.
Is there any other method?
I was taking time to find an alternate to GC.Collect(). After a few moments I suddenly
discovered, hey the finalize dispose pattern is there to collect garbage (although it's not
collection , it's nothing but disposing after use). And he was waiting for that.
How can multiple inheritance problems be overcome?
I provided a small structure and implementation of a class of multiple interfaces.
What is polymorphism and its Types?
I gave a definition of polymorphism with a classic example. The following is the example.
"Let's think about me. Now I am giving an interview, so you are my interviewer and I am
the interviewee. Now when I go to my room, with respect to my roommate, I am his
friend. And I talk to my mother after dinner on the phone (it's my daily routine for the
past 7 years).
I am her son. So, I am not changing but my identity is changing with respect to people
and places. It's nothing but polymorphism. The technical definition is "Ability to take

12

more than one form". At first I was wondering what is its type but then it came to me,
okay runtime and compile time. Actually I had forgotten the terminology. Then I showed
an example of function overloading and overriding.
Then a few more was there but I have forgotten them, uh oh; no it is not coming to mind.
Then we started to talk about ASP.NET but not much.
What is MVC pattern?
Though, I am new to it and currently learning. I have drawn a picture with three bubble
shapes ( yes, a classic MVC model picture, green, yellow and red colors, do you
remember?) and began to discuss them little. Then I was trying to bring him into my safe
zone. (Ha Ha, in ASP.Net web forms.)
How does viwestate work? Internally how does it store data?
I answered with the basic mechanism and how it stores data in key and value pairs and
it's disadvantages when the page is heavy.
How to bind DataTable in grid and how to allow pagin
I answered the dataSource property but forgot about the paging properly. I answered,
most probably it's Allow Paging.
Difference between DataView and DataGrid?
I was thinking and wondering for the answer of how they are related with each other.
What is Dataview? I asked, sir, what is the Dataview? Is it a control? He replied, yes it's a
control in the data section. Again I started to think and fnally I said sir, there is no control
like this. (Or at least I have not used it). Then we discovered that he was a little incorrect
and instead of DataView it is a Data Pager.
What is 3-tier architecture?
I showed a diagram with data flow from layer to layer and the forms of data.
Which namespace is used to make platform independent data access
mechanisms?
I answered System.data.commn. Yes, it contains the DBFactory class.
How to solve the jQuery conflict problem?
I am hearing this question for the very first time, so obviously I was unable to provide an
answer. He said something about a noconflict method. (I need to check that.)
A few more were there but at this moment they are not coming to mind.
So, it ended peacefully and I got confirmation for the next round within a few minutes.
So dear reader, here I have tried to show one motion picture of an interview session from
my experience and knowledge.
The answer I have written here is not a complete and full answer. I have just tried to
touch each and every question with important keywords. If you find any wrong question
or answer then please correct me.

13

C# and ASP.Net Question and Answers


Introduction
This article provides a collection of numerous .Net, C#, ADO.NET, Web Services, .Net
Framework questions and answers for which a reader must normally look around the
entire internet in various community web sites. Most of the questions and answers you
likely have already read. The purpose of this article is to consolidate most of the study
material related to .Net in one single place.
ASP.NET
What is view state and the use of it?
The current property settings of an ASP.NET page and those of any ASP.NET server
controls contained within the page. ASP.NET can detect when a form is requested for the
first time versus when the form is posted (sent to the server), that allows you to program
accordingly.
What are user controls and custom controls?
Custom controls
A control authored by a user or a third-party software vendor that does not belong to
the .NET Framework class library. This is a generic term that includes user controls. A
custom server control is used in Web Forms (ASP.NET pages). A custom client control is
used in Windows Forms applications.
User Controls
In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as
a server control. An ASP.NET user control is authored declaratively and persisted as a text
file with an .ascx extension. The ASP.NET page framework compiles a user control on the
fly to a class that derives from the System.Web.UI.UserControl class.
What are the validation controls?
A set of server controls included with ASP.NET that tests user input in HTML and Web
server controls for programmer-defined requirements. Validation controls perform input
checking in server code. If the user is working with a browser that supports DHTML then
the validation controls can also perform validation using a client script.
What's the difference between Response.Write() andResponse.Output.Write()?
The latter one allows you to write formatted output.
What methods are fired during the page load? Init ()
When the page is instantiated, Load() when the page is loaded into server memory;
PreRender() for the brief moment before the page is displayed to the user as HTML and
Unload() when the page finishes loading.
Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
Where do you store the information about the user's locale?

14

System.Web.UI.Page.Culture
What's the difference between Codebehind="MyCode.aspx.cs" and
src="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.
What's a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for
each object (cell, button, row and so on) is quite tedious. The controls can bubble up their
event handlers, allowing the main DataGrid event handler to take care of its constituents.
Suppose you want a certain ASP.NET function executed on MouseOver over a certain
button.
Where do you add an event handler?
It's the Attributes property, the Add function of that property. For example:
btnSubmit.Attributes.Add("onMouseOver","someClientCode();")
What data type does the RangeValidator control support?
Integer, String and Date.
What are the various types of caching?
Caching is a technique widely used in computing to increase performance by keeping
frequently accessed or expensive data in memory. In the context of a web application,
caching retains the pages or data across HTTP requests and reuses them without the
expense of recreating them. ASP.NET has 3 kinds of caching, strategiesOutput,
CachingFragment and CachingData.
CachingOutput Caching: Caches the dynamic output generated by a request. Some
times it is useful to cache the output of a website even for a minute, which will result in a
better performance. For caching the entire page the page should have OutputCache
directive.<%@ OutputCache Duration="60" VaryByParam="state" %>
Fragment Caching: Caches the portion of the page generated by the request. Some
times it is not practical to cache the entire page, in such cases we can cache a portion of
page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
Data Caching: Caches the objects programmatically. For data caching ASP.Net provides
a cache object for eg: cache["States"] = dsStates;
What do you mean by authentication and authorization?
Authentication is the process of validating a user on the credentials (username and
password) and authorization performs after authentication. After Authentication a user
will be verified for performing the various tasks, It access is limited it is known as
authorization.
What are various types of directives in .NET?
@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler.
Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>
@Control: Defines control-specific attributes used by the ASP.NET page parser and
compiler. Can be included only in .ascx files. <%@ Control Language="VB"

15

EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import
directive cannot have more than one namespace attribute. To import multiple
namespaces, use multiple @Import directives. <% @ Import Namespace="System.web"
%>
@Implements: Indicates that the current page or user control implements the
specified .NET framework interface.<%@ Implements
Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in
custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator"
src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the
assembly's classes and interfaces available for use on the page. <%@ Assembly
Name="MyAssembly" %><%@ Assembly src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page
or a user control contained in a page<%@ OutputCache Duration="#ofseconds"
Location="Any | Client | Downstream | Server | None" Shared="True | False"
VaryByControl="controlname" VaryByCustom="browser | customstring"
VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should
be dynamically compiled and linked against the page in which this directive is declared.
Note: A few of the references are were taken from other sites/sources.
How do I debug an ASP.NET application that wasn't written with Visual
Studio.NET and that doesn't use code-behind?
Start the DbgClr debugger that comes with the .NET Framework SDK, open the file
containing the code you want to debug, and set your breakpoints. Start the ASP.NET
application. Go back to DbgClr, choose "Debug Processes" from the Tools menu, and
select "aspnet_wp.exe" from the list of processes. (If "aspnet_wp.exe" doesn't appear in
the list then check the "Show system processes" box.) Click the "Attach" button to attach
to "aspnet_wp.exe" and begin debugging.
Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can
enable ASP.NET to build debug executables by placing a:
<%@ Page Debug="true" %>
statement at the top of an ASPX file or a:
<COMPILATION debug="true" />
statement in a Web.config file.
Can a user browsing my Web site read my Web.config or Global.asax files?
No. The <HTTPHANDLERS> section of Machine.config, which holds the master
configuration settings for ASP.NET, contains entries that map ASAX files, CONFIG files,
and selected other file types to an HTTP handler named HttpForbiddenHandler, which
fails attempts to retrieve the associated file. You can modify it by editing Machine.config
or including a section in a local Web.config file.
What's the difference between Page.RegisterClientScriptBlock and
Page.RegisterStartupScript?
RegisterClientScriptBlock is for returning blocks of client-side script containing functions.
RegisterStartupScript is for returning blocks of client scripts, not packaged in functions. In
other words, code that's to execute when the page is loaded. The latter positions script

16

blocks near the end of the document so elements on the page that the script interacts
with are loaded before the script runs. <%@ Reference Control="MyControl.ascx" %>
Is it necessary to lock application state before accessing it?
Only if you're performing a multi-step update and want the update to be treated as an
atomic operation. Here's an example:
Application.Lock ();
Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;
Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;
Application.UnLock ();
By locking application state before updating it and unlocking it afterwards, you ensure
that another request being processed on another thread doesn't read application state at
exactly the wrong time and see an inconsistent view of it. If I update session state then
should I lock it, too?
Are concurrent accesses by multiple requests executing on multiple threads a concern
with session state?
Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely
that two requests from the same user will overlap. Two, if they do overlap then ASP.NET
locks down session state during request processing so that two threads can't touch it at
once. Session state is locked down when the HttpApplication instance that's processing
the request fires an AcquireRequestState event and unlocked when it fires a
ReleaseRequestState event.
Do ASP.NET forms authentication cookies provide any protection against replay attacks?
Do they, for example, include the client's IP address or anything else that would
distinguish the real client from an attacker?
No. If an authentication cookie is stolen then it can be used by an attacker. It's up to you
to prevent this from happening by using an encrypted communications channel (HTTPS).
Authentication cookies issued as session cookies, do, however, include a time-out valid
that limits their lifetime. So a stolen session cookie can only be used in replay attacks as
long as the ticket inside the cookie is valid. The default time-out interval is 30 minutes.
You can change that by modifying the timeout attribute accompanying the <forms>
element in the Machine.config or a local Web.config file. Persistent authentication cookies
do not time-out and therefore are a more serious security threat if stolen.
How do I send e-mail from an ASP.NET application?
MailMessage message = new MailMessage ();
message.From = <email>;
message.To = <email>;
message.Subject = "Scheduled Power Outage";
message.Body = "Our servers will be down tonight.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (message);
MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's
System.Web.Mail namespace. Due to a security change made to ASP.NET just before it
shipped, you need to set SmtpMail's SmtpServer property to "localhost" even though
"localhost" is the default. In addition, you must use the IIS configuration applet to enable
localhost (127.0.0.1) to relay messages through the local SMTP service.
What are VSDISCO files?
VSDISCO files are DISCO files that support dynamic discovery of Web services. If you

17

place the following VSDISCO file in a directory on your Web server, for example then it
returns references to all ASMX and DISCO files in the host directory and any
subdirectories not noted in <exclude> elements:
<?xml version="1.0" ?>
<dynamicDiscovery
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<exclude path="_vti_cnf" />
<exclude path="_vti_pvt" />
<exclude path="_vti_log" />
<exclude path="_vti_script" />
<exclude path="_vti_txt" />
</dynamicDiscovery>
How does dynamic discovery work?
ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host
directory and subdirectories for ASMX and DISCO files and returns a dynamically
generated DISCO document. A client who requests a VSDISCO file gets back what
appears to be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable
them by uncommenting the line in the <httpHandlers> section of Machine.config that
maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting
the ASPNET user account permission to read the IIS metabase. However, Microsoft is
actively discouraging the use of VSDISCO files because they could represent a threat to
Web server security.
Is it possible to prevent a browser from caching an ASPX page?
Just call SetNoStore on the HttpCachePolicy object exposed through the Response
object's Cache property, as demonstrated here:
<%@ Page Language="C#" %>
<html>
<body>
<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
</body>
</html>
SetNoStore works by returning a Cache-Controll; a private, no-store header in the HTTP
response. In this example, it prevents caching of a Web page that shows the current
time.
What does AspCompat="true" mean and when should I use it?
AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but
should be set to true in any ASPX file that creates apartment-threaded COM objects; that
is, COM objects registered with ThreadingModel=Apartment. That includes all COM
objects written with Visual Basic 6.0. AspCompat should also be set to true (regardless of
threading model) if the page creates COM objects that access intrinsic ASP objects such
as Request and Response. The following directive sets AspCompat to true:
<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available

18

to the COM components by placing unmanaged wrappers around the equivalent ASP.NET
objects. Second, it improves the performance of calls that the page places to apartmentthreaded COM objects by ensuring that the page (actually, the thread that processes the
request for the page) and the COM objects it creates share an apartment.
AspCompat="true" forces ASP.NET request threads into single-threaded apartments
(STAs). If those threads create COM objects marked ThreadingModel=Apartment then the
objects are created in the same STAs as the threads that created them. Without
AspCompat="true," request threads run in a multithreaded apartment (MTA) and each
call to an STA-based COM object incurs a performance hit when it's marshaled across
apartment boundaries.
Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects
that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or
ThreadingModel=Both.
Explain the differences between Server-side and Client-side code?
Server-side scripting means that all the script will be executed by the server and
interpreted as needed. ASP doesn't have some of the functionality like sockets,
uploading, and so on. For these you need to make custom components usually in VB or
VC++. Client-side scripting means that the script will be executed immediately in the
browser such as form field validation, clock, email validation, and so on. Client-side
scripting is usually done in VBScript or JavaScript. Download time, browser compatibility,
and visible code, since JavaScript and VBScript code is included in the HTML page, then
anyone can see the code by viewing the page source. Also possible security hazards for
the client computer.
What type of code (server or client) is found in a Code-Behind class?

C#.
Should validation (such as did the user enter a real date) occur serverside or client-side? Why?
Client-side validation because there is no need to request a server-side date
when you could obtain a date from the client machine.
What are ASP.NET Web Forms? How is this technology different than
what is available though ASP?
Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface
(UI) elements that provide your Web applications their look and feel. Web Forms
are similar to Windows Forms in that they provide properties, methods, and
events for the controls that are placed onto them. However, these UI elements
render themselves in the appropriate markup language required by the request,
for example HTML. If you use Microsoft Visual Studio .NET then you will also get
the familiar drag-and-drop interface used to create your UI for your Web
application.
What is the difference between Server.Transfer and Response.Redirect?
Why would I choose one over the other?
In earlier versions of IIS, if we wanted to send a user to a new Web page then the
only option we had was Response.Redirect. While this method does accomplish
our goal, it has several important drawbacks. The biggest problem is that this
method causes each page to be treated as a separate transaction. Besides
making it difficult to maintain your transactional integrity, Response.Redirect
19

introduces some additional headaches. First, it prevents good encapsulation of


code. Second, you lose access to all of the properties in the Request object. Sure,
there are workarounds, but they're difficult. Finally, Response.Redirect
necessitates a round trip to the client, which, on high-volume sites, causes
scalability problems.
As you might suspect, Server.Transfer fixes all of these problems. It does this by
performing the transfer on the server without requiring a roundtrip to the client.
How can you provide an alternating color scheme in a Repeater control?
AlternatingItemTemplate Like the ItemTemplate element, but rendered for every
other row (alternating items) in the Repeater control. You can specify a different
appearance for the AlternatingItemTemplate element by setting its style
properties.
Which template must you provide, in order to display data in a Repeater
control?
ItemTemplate.
What event handlers can I include in Global.asax?
Application_Start, Application_End, Application_AcquireRequestState,
Application_AuthenticateRequest, Application_AuthorizeRequest,
Application_BeginRequest, Application_Disposed, Application_EndRequest,
Application_Error, Application_PostRequestHandlerExecute,
Application_PreRequestHandlerExecute, Application_PreSendRequestContent,
Application_PreSendRequestHeaders, Application_ReleaseRequestState,
Application_ResolveRequestCache, Application_UpdateRequestCache,
Session_Start and Session_End.
You can optionally include "On" in any of the method names. For example, you
can name a BeginRequest event handler Application_BeginRequest or
Application_OnBeginRequest. You can also include event handlers in Global.asax
for events fired by custom HTTP modules. Note that not all of the event handlers
make sense for Web Services (they're designed for ASP.NET applications in
general, whereas .NET XML Web Services are specialized instances of an ASP.NET
app). For example, the Application_AuthenticateRequest and
Application_AuthorizeRequest events are designed to be used with ASP.NET
Forms authentication.
What is different between webconfig.xml and Machineconfig.xml?
Web.config and machine.config both are configuration files. Web.config contains
settings specific to an application whereas machine.config contains settings to a
computer. The Configuration system first searches settings in machine.config file
and then looks in application configuration files. Web.config can appear in
multiple directories on an ASP.NET Web application server. Each Web.config file
applies configuration settings to its own directory and all child directories below
it. There is only a Machine.config file on a web server.
If I'm developing an application that must accomodate multiple security levels
using a secure login and my ASP.NET web appplication is spanned across three
20

web-servers (using round-robbin load balancing) then what would be the best
approach to maintain login-in state for the users?
Use the state server or store the state in the database. This can be easily done
through a simple setting change in the web.config.
<SESSIONSTATE
StateConnectionString="tcpip=127.0.0.1:42424" =""
sqlConnectionString="data source=127.0.0.1; user id=sa;" password=""
cookieless="false" =""
timeout="30" =""/>
You can specify mode as "stateserver" or "sqlserver".
Where would you use an iHTTPModule, and what are the limitations of any
approach you might use in implementing one?
"One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path
that data takes between client and server. You can use them to extend your ASP.NET
applications by adding pre-processing and post-processing to each HTTP request coming
into your application. For example, if you wanted custom authentication facilities for your
application then the best technique would be to intercept the request when it comes in
and processes the request in a custom HTTP module.
How do you turn off cookies for one page in your site?
Since no Page Level directive is present, I am afraid that can't be done.
How do you create a permanent cookie?
Permanent cookies are available until a specified expiration date, and are stored on the
hard disk. So set the "Expires" property to a value greater than DataTime.MinValue with
respect to the current datetime. If you want the cookie that never expires set its Expires
property equal to DateTime.maxValue.
Which method do you use to redirect the user to another page without
performing a round trip to the client?
Server.Transfer and Server.Execute
What property do you need to set to tell the grid which page to go to when
using the Pager object?
CurrentPageIndex
Should validation (such as did the user enter a real date) occur server-side or
client-side? Why?
It should occur both at client-side and server-side. By using an expression validator
control with the specified expression, in other words, the regular expression provides the
ability to only validatate the date specified that it is in the correct format. For checking
the date, whether it is the real data or not should hoever be done at the server-side, by
getting the system date ranges and checking the date whether it is between that range
or not.
What does the "EnableViewState" property do? Why would I want it on or off?
Enable ViewState turns on the automatic state management feature that enables server
controls to re-populate their values on a round trip without requiring you to write any

21

code. This feature is not free, however, since the state of a control is passed to and from
the server in a hidden form field. You should be aware of when ViewState is helping you
and when it is not. For example, if you are binding a control to data on every round trip,
then you do not need the control to maintain it's view state, since you will wipe out any
re-populated data in any case. ViewState is enabled for all server controls by default. To
disable it, set the EnableViewState property of the control to false.
What is the difference between Server.Transfer and Response.Redirect? Why
would I choose one over the other?
Server.Transfer(): the client is shown as it is on the requesting page only, but all the
content is of the requested page. Data can be persisted accros the pages using a
Context.Item collection, which is one of the best way to transfer data from one page to
another keeping the page state alive.
Response.Redirect(): client knows the physical location (page name and query string
as well). Context.Items loses the persisitance when nevigating to the destination page. In
earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we
had was Response.Redirect While this method does accomplish our goal, it has several
important drawbacks. The biggest problem is that this method causes each page to be
treated as a separate transaction. Besides making it difficult to maintain your
transactional integrity, Response.Redirect introduces some additionalproblens. First, it
prevents good encapsulation of code. Second, you lose access to all of the properties in
the Request object. Sure, there are workarounds, but they're difficult. Finally,
Response.Redirect necessitates a round trip to the client, which, on high-volume sites,
causes scalability problems. As you might suspect, Server.Transfer fixes all of these
problems. It does this by performing the transfer on the server without requiring a
roundtrip to the client.
Can you give an example of when it would be appropriate to use a web service
as opposed to a non-serviced .NET component?

Communicating through a Firewall when building a distributed application with


100s or 1000s of users spread over multiple locations, there is always the problem
of communicating between client and server because of firewalls and proxy
servers. Exposing your middle tier components as Web Services and invoking
them directly from a Windows UI is a very valid option.

Application Integration When integrating applications written in various languages


and running on disparate systems. Or even applications running on the same
platform that have been written by separate vendors.

Business-to-Business Integration. This is an enabler for B2B intergtation that


allows one to expose vital business processes to authorized suppliers and
customers. An example would be exposing electronic ordering and invoicing,
allowing customers to send you purchase orders and suppliers to send you
invoices electronically.

Software Reuse. This takes place at multiple levels. Code Reuse at the Source
code level or binary componet-based resuse. The limiting factor here is that you
can reuse the code but not the data behind it. Webservice overcomes this
limitation. A scenario could be when you are building an app that aggregates the
functionality of serveral other Applicatons. Each of these functions could be
performed by individual apps, but there is value in perhaps combining the the
multiple apps to present a unifiend view in a Portal or Intranet.

22

When not to use Web Services: Single-machine applicatons are applicatons


running on the same machine and that need to communicate with each other
using a native API. You also have the options of using component technologies
such as COM or .NET Componets since there is very little overhead.

Homogeneous Applications on a LAN. If you have Win32 or Winforms apps that


want to communicate with their server counterpart. It is much more efficient to
use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps.

Can you give an example of what might be most appropriately placed in the
Application_Start and Session_Start events?
The Application_Start event is guaranteed to occur only once throughout the lifetime of
the application. It's a good place to initialize global variables. For example, you might
want to retrieve a list of products from a database table and place the list in application
state or the Cache object. SessionStateModule exposes both Session_Start and
Session_End events.
What are the advantages and disadvantages of viewstate?
The primary advantages of the ViewState feature in ASP.NET are:

1.

Simplicity. There is no need to write possibly complex code to store form data
between page submissions.

2.

Flexibility. It is possible to enable, configure, and disable ViewState on a controlby-control basis, choosing to persist the values of some fields but not others.

There are, however a few disadvantages that are worth pointing out:

1.

Does not track across pages. ViewState information does not automatically
transfer from page to page. With the session
approach, values can be stored in the session and accessed from other pages.
This is not possible with ViewState, so storing
data into the session must be done explicitly.

2.

ViewState is not suitable for transferring data for back-end systems. That is, data
must still be transferred to the back
end using some form of data object.

Describe session handling in a webfarm, how does it work and what are the
limits?
ASP.NET Sessions support storing of session data in 3 ways, i] In-Process (in the same
memory that ASP.NET uses) , ii] Out-of-Process using a Windows NT Service (in memory
separate from ASP.NET) or iii] in SQL Server (persistent storage). Both the Windows
Service and SQL Server solutions support a webfarm scenario where all the web-servers
can be configured to share a common session state store.
1. Windows Service
We can start this service by "Start" | "Control Panel" | "Administrative Tools" | "Services".
In that we service names ASP.NET State Service. We can start or stop a service manually
or configure it to start automatically. Then we need to configure our web.config file as in
the following:

23

<CONFIGURATION>
<configuration>
<system.web>
<SessionState
mode = "StateServer"
stateConnectionString = "tcpip=127.0.0.1:42424"
stateNetworkTimeout = "10"
sqlConnectionString="data source = 127.0.0.1; uid=sa;pwd="
cookieless ="Flase"
timeout= "20" />
</system.web>
</configuration>
</SYSTEM.WEB>
</CONFIGURATION>
Here ASP.Net Session is directed to use a Windows Service for state management on the
local server (the address 127.0.0.1 is the TCP/IP loop-back address). The default port is
42424. We can configure it to any port but for that we need to manually edit the registry.
Use the following simple procedure:

In a webfarm make sure you have the same config file in all your web servers.

Also make sure your objects are serializable.

For the session state to be maintained across various web servers in the webfarm,
the application path of the web-site in the IIS Metabase should be identical in all
the web-servers in the webfarm.

Which template must you provide to display data in a Repeater control?


You need to use the ItemTemplate to display data. The syntax is as follows:
<
<
<
<
<
<

img

div
src="images/<%#
b
>

ItemTemplate
>
class
="rItem"
>
Container.DataItem("ImageURL")%>" hspace="10" />
<%
#
Container.DataItem("Title")%>
/div
>
ItemTemplate
>

How can you provide an alternating color scheme in a Repeater control?


Using

the

AlternatintItemTemplate

What property must you set, and what method must you call in your code, to
bind the data from some data source to the Repeater control?
Set the DataMember property to the name of the table to bind to. (If this property is not
set
then
by
default
the
first
table
in
the
dataset
is
used.)
The DataBind method uses this method to bind data from a source to a server control.
This method is commonly used after retrieving a data set through a database query.
What

method

do

you

use

to

explicitly

kill

user

session?

You can dump (Kill) the session yourself by calling the method Session.Abandon.
ASP.NET automatically deletes a user's Session object, dumping its contents, after it has
been idle for a configurable timeout interval. This interval, in minutes, is set in the

24

<SESSIONSTATE>section
How

do

you

turn

of

the
off

web.config
cookies

file.

for

The

one

default
page

is
in

20

minutes.

your

site?

Use the Cookie.Discard property, Gets or sets the discard flag set by the server. When
true, this property instructs the client application not to save the Cookie on the user's
hard
disk
when
a
session
ends.
Which

two

properties

are

on

every

validation

control?

We have two common properties for every validation control as in the following:

1.

Control to Validate,

2.

Error Message.

What tags do you need to add within the asp:datagrid tags to bind columns manually?
< asp:DataGrid id="dgCart" AutoGenerateColumns="False" CellPadding="4" Width="448px" runat="server" >
< Columns >
< asp:ButtonColumn HeaderText="SELECT" Text="SELECT" CommandName="select" ><
/asp:ButtonColumn >
< asp:BoundColumn DataField="ProductId" HeaderText="Product ID" >< /asp:BoundColumn >
< asp:BoundColumn DataField="ProductName" HeaderText="Product Name" >< /asp:BoundColumn >
< asp:BoundColumn DataField="UnitPrice" HeaderText="UnitPrice" >< /asp:BoundColumn >
< /Columns >
< /asp:DataGrid >
How do you create a permanent cookie?
Permanent cookies are the ones that are most useful. Permanent cookies are available until a specified expiration
date, and are stored on the hard disk. The location of cookies differs with each browser, but this doesn't matter,
as this is all handled by your browser and the server. If you want to create a permanent cookie called Name with
a value of Nigel, that expires in one month then you'd use the following code:
Response.Cookies ("Name") = "Nigel"
Response.Cookies ("Name"). Expires = DateAdd ("m", 1, Now ())
What tag do you use to add a hyperlink column to the DataGrid?
< asp:HyperLinkColumn > </ asp:HyperLinkColumn>
Which method do you use to redirect the user to another page without performing a round trip to the
client?
Server.transfer
What is the transport protocol you use to call a Web service SOAP ?
HTTP Protocol
Explain role based security
Role Based Security lets you identify groups of users to allow or deny based on their role in the organization. In
Windows NT and Windows XP, roles map to names used to identify user groups. Windows defines several builtin groups, including Administrators, Users, and Guests.To allow or deny access to certain groups of users, add
the <ROLES> element to the authorization list in your Web application's Web.config file. For example:
<AUTHORIZATION>< authorization >
< allow roles="Domain Name\Administrators" / > < !-- Allow Administrators in domain. -- >
< deny users="*" / > < !-- Deny anyone else. -- >

25

< /authorization >


How do you register JavaScript for webcontrols ?
You can register JavaScript for controls using the <CONTROL -name>Attribtues.Add(scriptname,scripttext)
method.
When do you set "<IDENTITY impersonate="true" />" ?
Identity is a webconfig declaration under System.web, which helps to control the application Identity of the web
applicaton. Which can be at any level (Machine, Site, application, subdirectory, or page). The attribute
impersonates "true" as the value to specify that client impersonation is used.
What are various templates available in Repeater, DataList and Datagrid?
Templates enable one to apply complicated formatting to each of the items displayed by a control. The Repeater
control supports five types of templates. HeaderTemplate controls how the header of the repeater control is
formatted. ItemTemplate controls the formatting of each item displayed. AlternatingItemTemplate controls how
alternate items are formatted. SeparatorTemplate displays a separator between each item displyed.
FooterTemplate controls how the footer of the repeater control is formatted. DataList and Datagrid supports two
templates in addition to the preceding five. The SelectedItem Template controls how a selected item is formatted
and EditItemTemplate controls how an item selected for editing is formatted.
What is ViewState? How is it managed ?
ASP.NET ViewState is a new kind of state service that developers can use to track UI state on a per-user basis.
Internally it uses an an old Web programming trick, roundtripping state in a hidden form field and bakes it right
into the page-processing framework. It needs less code to write and maintain state in your Web-based forms.
What is the web.config file?
The Web.config file is the configuration file for the ASP.Net web application. There is one web.config file for
one ASP.Net application that configures the specific application. The Web.config file is written in XML with
specific tags having specific meanings. It includes data that includes connections, Session States, Error
Handling, Security and so on.
For example:
< configuration >
< appSettings >
< add key="ConnectionString"
value="server=localhost;uid=sa;pwd=;database=MyDB" / >
< /appSettings >
< /configuration >
What are the advantages and benefits of viewstate?
When a form is submitted in classic ASP, all form values are cleared. Suppose you have
submitted a form with a lot of information and the server returns an error. You will need
to return to the form and correct the information. You click the back button, and what
happens? All form values are cleared, and you will need to start all over again! The site
did not maintain your ViewState. With ASP .NET, the form reappears in the browser
window together with all form values. This is because ASP .NET maintains your
ViewState. The ViewState indicates the status of the page when submitted to the server.
What tags do you need to add within the asp:datagrid tags to bind columns
manually?
Set the AutoGenerateColumns Property to false on the datagrid tag and then use the
Column tag and an ASP:databound tag as in the following:

26

< asp:DataGrid runat="server" id="ManualColumnBinding"


AutoGenerateColumns="False" >
< Columns >
< asp:BoundColumn HeaderText="Column1" DataField="Column1"/ >
< asp:BoundColumn HeaderText="Column2" DataField="Column2"/ >
< /Columns >
< /asp:DataGrid >
<asp:DataGrid id=ManualColumnBinding runat="server"
AutoGenerateColumns="False">
<COLUMNS> <asp:BoundColumn HeaderText="Column2"
DataField="Column2"></asp:BoundColumn>
</asp:DataGrid>Which property on a Combo Box do you set with a column name, prior
to setting the DataSource, to display data in the combo box?
DataTextField and DataValueField
Which control would you use if you needed to ensure the values in two
different controls matched?
CompareValidator is used to ensure that two fields are identical.
What is validationsummary server control? Where is it used?
The ValidationSummary control allows you to summarize the error messages from all
validation controls on a Web page in a single location. The summary can be displayed as
a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode
property. The error message displayed in the ValidationSummary control for each
validation control on the page is specified by the ErrorMessage property of each
validation control. If the ErrorMessage property of the validation control is not set then no
error message is displayed in the ValidationSummary control for that validation control.
You can also specify a custom title in the heading section of the ValidationSummary
control by setting the HeaderText property.
You can control whether the ValidationSummary control is displayed or hidden by setting
the ShowSummary property. The summary can also be displayed in a message box by
setting the ShowMessageBox property to true.
What is the sequence of operations occuring when a page is loaded?
BeginTranaction: only if the request is transacted
Init: every time a page is processed
LoadViewState: Only on postback
ProcessPostData1: Only on postback
Load: every time
ProcessData2: Only on Postback
RaiseChangedEvent: Only on Postback
RaisePostBackEvent: Only on Postback
PreRender: everytime
BuildTraceTree: Only if tracing is enabled
SaveViewState: Every time
Render: Every time
End Transaction: Only if the request is transacted
Trace.EndRequest: Only when tracing is enabled
UnloadRecursive: Every request
What are some of the differences between ASP and ASP.Net?
"Active Server Pages (ASP) and ASP.NET are both server-side technologies for building
web sites and web applications, ASP.NET is Managed compiled code, ASP is interpreted.

27

and ASP.Net is fully Object Oriented. ASP.NET has been entirely re-architected to provide
a highly productive programming experience based on the .NET Framework, and a robust
infrastructure for building reliable and scalable web applications."
Name the validation control available in ASP.Net
RequiredField, RangeValidator, RegularExpression, Custom Validator, Compare Validator.
What are the various ways of securing a web site that could prevent hacking
and so on?

1.

Authentication/Authorization

2.

Encryption/Decryption

3.

Maintaining web servers outside the corporate firewall

4.

and so on.

What is the difference between in-proc and out-of-proc?


An inproc is one that runs in the same process area as that of the client giving tha
advantage of speed but the disadvantage of stability because if it crashes then it takes
the client application also with it. Outproc is one that works outside the client's memory,
thus giving stability to the client, but we need to compromise a bit on speed.
When you're running a component within ASP.NET, what process is it running
within on Windows XP? Windows 2000? Windows 2003?
On Windows 2003 (IIS 6.0) running in native mode, the component is running within the
w3wp.exe process associated with the application pool that has been configured for the
web application containing the component.
On Windows 2003 in IIS 5.0 emulation mode, 2000, or XP, it's running within the IIS
helper process whose name I do not remember, it being quite a while since I last used IIS
5.0.
What does aspnet_regiis -i do?
Aspnet_regiis.exe is the ASP.NET IIS Registration tool that allows an administrator or
installation program to easily update the script maps for an ASP.NET application to point
to the ASP.NET ISAPI version associated with the tool. The tool can also be used to display
the status of all installed versions of ASP. NET, register the ASP.NET version coupled with
the tool, create client-script directories, and perform other configuration operations.
When multiple versions of the .NET Framework are executing side-by-side on a single
computer, the ASP.NET ISAPI version mapped to an ASP.NET application determines which
version of the Common Language Runtime is used for the application.
The tool can be launched with a set of optional parameters. Option "i" installs the version
of ASP.NET associated with Aspnet_regiis.exe and updates the script maps at the IIS
metabase root and below. Note that only applications that are currently mapped to an
earlier version of ASP.NET are affected
What is a PostBack?
The process in which a Web page sends data back to the same page on the server.

28

What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?


ViewState is the mechanism ASP.NET uses to maintain server control state values that
don't otherwise post-back as part of the HTTP form. ViewState Maintains the UI State of a
Page.
ViewState is base64-encoded.
It is not encrypted but it can be encrypted by setting EnableViewStatMAC="true" and
setting the machineKey validation type to 3DES. If you want to not maintain the
ViewState then include the directive < %@ Page EnableViewState="false" % > at the top
of an .aspx page or add the attribute EnableViewState="false" to any control.
What is the < machinekey > element and what two ASP.NET technologies is it
used for?
Configures keys to use for encryption and decryption of forms authentication cookie data
and view state data, and for verification of out-of-process session state
identification.Therefore 2 ASP.Net techniques in which it is used are
Encryption/Decryption and Verification.
What three Session State providers are available in ASP.NET 1.1? What are the
pros and cons of each?
ASP.NET provides three distinct ways to store session data for your application: in-process
session state, out-of-process session state as a Windows service, and out-of-process
session state in a SQL Server database. Each has it advantages.
1. In-process session-state mode
Limitations

When using the in-process session-state mode, session-state data is lost if


aspnet_wp.exe or the application domain restarts.

If you enable Web Garden mode in the < processModel > element of the
application's Web.config file then do not use in-process session-state mode.
Otherwise, random data loss can occur.

Advantage

in-process session state is by far the fastest solution. If you are storing only small
amounts of volatile data in session state, it is recommended that you use the inprocess provider.

2. The State Server simply stores session state in memory when in out-of-proc mode. In
this mode the worker process talks directly to the State Server
3. SQL mode, session states are stored in a SQL Server database and the worker process
talks directly to SQL. The ASP.NET worker processes are then able to take advantage of
this simple storage service by serializing and saving (using .NET serialization services) all
objects within a client's Session collection at the end of each Web request
Both these out-of-process solutions are useful primarily if you scale your application
across multiple processors or multiple computers, or where data cannot be lost if a server
or process is restarted.
What is the difference between HTTP-Post and HTTP-Get?

29

As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying
protocol. Both of these methods encode request parameters as name/value pairs in the
HTTP request.
The GET method creates a query string and appends it to the script's URL on the server
that handles the request.
The POST method creates name/value pairs that are passed in the body of the HTTP
request message.
Name and describe some HTTP Status Codes and what they express to the
requesting client.
When users try to access content on a server that is running Internet Information
Services (IIS) through HTTP or File Transfer Protocol (FTP), IIS returns a numeric code that
indicates the status of the request. This status code is recorded in the IIS log, and it may
also be displayed in the Web browser or FTP client. The status code can indicate whether
a specific request is successful or unsuccessful and can also reveal the exact reason why
a request is unsuccessful. There are 5 groups ranging from 1xx - 5xx of HTTP status
codes that exist as in the following:
101: Switching protocols.
200: OK. The client request has succeeded
302: Object moved.
400: Bad request.
500.13: Web server is too busy.
Explain < @OutputCache% > and the usage of VaryByParam, VaryByHeader.
OutputCache is used to control the caching policies of an ASP.NET page or user control.
To cache a page @OutputCache directive should be defined as follows < %@
OutputCache Duration="100" VaryByParam="none" % >
VaryByParam: A semicolon-separated list of strings used to vary the output cache. By
default, these strings correspond to a query string value sent with GET method
attributes, or a parameter sent using the POST method. When this attribute is set to
multiple parameters then the output cache contains a different version of the requested
document for each specified parameter. Possible values include none, *, and any valid
query string or POST parameter name.
VaryByHeader: A semicolon-separated list of HTTP headers used to vary the output
cache. When this attribute is set to multiple headers, the output cache contains a
different version of the requested document for each specified header.
What is the difference between repeater over datalist and datagrid?
The Repeater class is not derived from the WebControl class, like the DataGrid and
DataList. Therefore, the Repeater lacks the stylistic properties common to both the
DataGrid and DataList. What this boils down to is that if you want to format the data
displayed in the Repeater then you must do so in the HTML markup.
The Repeater control provides the maximum amount of flexibility over the HTML
produced. Whereas the DataGrid wraps the DataSource contents in an HTML < table >,
and the DataList wraps the contents in either an HTML < table > or < span > tags
(depending on the DataList's RepeatLayout property), the Repeater adds absolutely no
HTML content other than what you explicitly specify in the templates.
While using the Repeater control, if we wanted to display the employee names in a bold
font then we'd need to alter the "ItemTemplate" to include an HTML bold tag. Whereas

30

with the DataGrid or DataList, we could have made the text appear in a bold font by
setting the control's ItemStyle-Font-Bold property to True.
The Repeater's lack of style properties can drastically add to the development time
metric. For example, imagine that you decide to use the Repeater to display data that
needs to be bold, centered, and displayed in a specific font-face with a specific
background color. While all this can be specified using a few HTML tags, these tags will
quickly clutter the Repeater's templates. Such clutter makes it much harder to change
the look at a later date. Along with its increased development time, the Repeater also
lacks any built-in functionality to assist in supporting paging, editing, or editing of data.
Due to this lack of feature-support, the Repeater scores poorly on the usability scale.
However, The Repeater's performance is slightly better than that of the DataList's, and is
noticeably better than that of the DataGrid's. The following figure shows the number of
requests per second the Repeater could handle versus the DataGrid and DataList.
Can we handle the error and redirect to some pages using web.config?
Yes, we can do this, but to handle errors, we must know the error codes; only then we
can take the user to a proper error message page, else it may confuse the user.
CustomErrors Configuration section in web.config file:
The default configuration is:
< customErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" >
< error statusCode="404" redirect="Notfound.aspx" / >
< /customErrors >
If the mode is set to Off then the custom error messages will be disabled. Users will
receive detailed exception error messages.
If mode is set to On then custom error messages will be enabled.
If mode is set to RemoteOnly then then users will receive custom errors, but users
accessing the site locally will receive detailed error messages.
Add an < error > tag for each error you want to handle. The error tag will redirect the
user to the Notfound.aspx page when the site returns the 404 (Page not found) error.
[Example]
There is a page MainForm.aspx
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
'Put user code to initialize the page here
Dim str As System.Text.StringBuilder
str.Append("hi") ' Error Line as str is not instantiated
Response.Write(str.ToString)
End Sub
[Web.Config]
< customErrors mode="On" defaultRedirect="Error.aspx"/ >
' a simple redirect will take the user to Error.aspx [user defined] error file.
< customErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" >

31

< error statusCode="404" redirect="Notfound.aspx" / >


< /customErrors >
'This will take the user to NotFound.aspx defined in IIS.
How do you implement Paging in .Net?
The DataGrid provides the means to display a group of records from the data source (for
example, the first 10), and then navigate to the "page" containing the next 10 records,
and so on through the data.
Using ADO.Net we can have explicit control over the number of records returned from the
data source, as well as how much data is to be cached locally in the DataSet as in the
following:

1.

Using the DataAdapter.fill method provides the value of the "Maxrecords"


parameter
(Note:: Don't use it because the query will return all records but fill the dataset
based on the value of the "maxrecords" parameter).

2.

For SQL Server databases, combine a WHERE clause and a ORDER BY clause with
the TOP predicate.

3.

If data does not change often then just cache records locally in a DataSet and take
some records from the DataSet to display.

What is the difference between Server.Transfer and Response.Redirect?


Server.Transfer(): client is shown as it is on the requesting page only, but all the content
is of the requested page. Data can be persisted across the pages using the Context.Item
collection, that is one of the best ways to transfer data from one page to another keeping
the page state alive.
Response.Dedirect(): the client knows the physical location (page name and query string
as well). Context.Items loses the persistence when navigate to destination page. In
earlier versions of IIS, if we wanted to send a user to a new Web page then the only
option we had was Response.Redirect. While this method does accomplish our goal, it
has several important drawbacks. The biggest problem is that this method causes each
page to be treated as a separate transaction. Besides making it difficult to maintain your
transactional integrity, Response.Redirect introduces some additional headaches. First, it
prevents good encapsulation of code. Second, you lose access to all of the properties in
the Request object. Sure, there are workarounds, but they're difficult. Finally,
Response.Redirect necessitates a round trip to the client, which, on high-volume sites,
causes scalability problems. As you might suspect, Server.Transfer fixes all of these
problems. It does this by performing the transfer on the server without requiring a
roundtrip to the client.
Response.Redirect sends a response to the client browser instructing it to request the
second page. This requires a round-trip to the client, and the client initiates the Request
for the second page. Server.Transfer transfers the process to the second page without
making a round-trip to the client. It also transfers the HttpContext to the second page,
enabling the second page access to all the values in the HttpContext of the first page.
Can you create an app domain?
Yes, we can create a user app domain by calling one of the following overload static
methods of the System.AppDomain class:

32

1.

Public static AppDomain CreateDomain(String friendlyName)

2.

Public static AppDomain CreateDomain(String friendlyName, Evidence


securityInfo)

3.

Public static AppDomain CreateDomain(String friendlyName, Evidence


securityInfo, AppDomainSetup info)

4.

Public static AppDomain CreateDomain(String friendlyName, Evidence


securityInfo, String appBasePath, String appRelativeSearchPath, bool
shadowCopyFiles)

What are the various security methods that IIS Provides apart from .NET?
The various security methods that IIS provides are:

Authentication Modes

IP Address and Domain Name Restriction

DNS Lookups DNS Lookups

The Network ID and Subnet Mask

SSL

What is Web Gardening? How would using it affect a design?


The Web Garden Model
The Web Garden model is configurable through the machine.config file. Notice that the
section is the only configuration section that cannot be placed in an application-specific
web.config file. This means that the Web Garden mode applies to all applications running
on the machine. However, by using the node in the machine.config source, you can
adapt machine-wide settings on a per-application basis.
Two attributes in the section affect the Web Garden model. They are webGarden and
cpuMask. The webGarden attribute takes a Boolean value that indicates whether or not
multiple worker processes (one per each affinitized CPU) need to be used. The attribute is
set to false by default. The cpuMask attribute stores a DWORD value whose binary
representation provides a bit mask for the CPUs that are eligible to run the ASP.NET
worker process. The default value is -1 (0xFFFFFF), which means that all available CPUs
can be used. The contents of the cpuMask attribute is ignored when the webGarden
attribute is false. The cpuMask attribute also sets an upper bound to the number of
copies of aspnet_wp.exe that are running.
Web Gardening enables multiple worker processes to run at the same time. However, you
should note that all processes will have their own copy of application state, in-process
session state, ASP.NET cache, static data, and all that is needed to run applications.
When the Web Garden mode is enabled, the ASP.NET ISAPI launches as many worker
processes as there are CPUs, each a full clone of the next (and each affinitized with the
corresponding CPU). To balance the workload, incoming requests are partitioned among
running processes in a round-robin manner. Worker processes get recycled as in the
single processor case. Note that ASP.NET inherits any CPU usage restriction from the

33

operating system and doesn't include any custom semantics for doing this.
All in all, the Web Garden model is not necessarily a big win for all applications. The more
stateful applications are, the more they risk to pay in terms of real performance. Working
data is stored in blocks of shared memory so that any changes entered by a process are
immediately visible to others. However, for the time it takes to service a request, working
data is copied in the context of the process. Each worker process, therefore, will handle
its own copy of working data, and the more stateful the application, the higher the cost in
performance. In this context, careful and savvy application benchmarking is an absolute
must.
Changes made to the section of the configuration file are effective only after IIS is
restarted. In IIS 6, Web Gardening parameters are stored in the IIS metabase; the
webGarden and cpuMask attributes are ignored.
What is view state? Where is it stored? Can we disable it?
The web is a state-less protocol, so the page is instantiated, executed, rendered and then
disposed of on every round trip to the server. The developer's code to add "statefulness"
to the page by using server-side storage for the state or posting the page to itself. When
required to persist and read the data in a control on a webform, the developer must read
the values and store them in a hidden variable (in the form), that were then used to
restore the values. With the advent of the .NET Framework, ASP.NET offers the ViewState
mechanism that tracks the data values of server controls on an ASP.NET webform. In
effect, ViewState can be viewed as "hidden variable managed by the ASP.NET
framework!". When an ASP.NET page is executed, data values from all server controls on
a page are collected and encoded as a single string that is then assigned to the page's
hidden atrribute "< input type=hidden >", that is part of the page sent to the client.
The ViewState value is temporarily saved in the client's browser. ViewState can be
disabled for a single control, for an entire page or for an entire web application. The
syntax is:
Disable ViewState for control (Datagrid in this example)
< asp:datagrid EnableViewState="false" ... / >
Disable ViewState for a page, using Page directive
< %@ Page EnableViewState="False" ... % >
Disable ViewState for application through entry in web.config
< Pages EnableViewState="false" ... / >
.NET FrameWork FAQ's
When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET
"vision". The July 2000 PDC had a number of sessions on .NET technology, and delegates
were given CDs containing a pre-release version of the .NET Framework/SDK and Visual
Studio.NET.
When was the first version of .NET released?
The final version of the 1.0 SDK and runtime was made publicly available around 6 PM
PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made
available to MSDN subscribers.
What platforms does the .NET Framework run on?
The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98.

34

Windows 95 is not supported. Some parts of the framework do not work on all platforms;
for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows
98/ME cannot be used for development.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET.
However, the ASP.NET Web Matrix web server does run on XP Home.
The Mono project is attempting to implement the .NET framework on Linux.
What is the CLR?
CLR = Common Language Runtime. The CLR is a set of standard resources that (in
theory) any .NET program can take advantage of, regardless of programming language.
Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:

Object-oriented programming model (inheritance, polymorphism, exception


handling, garbage collection)

Security model

Type system

All .NET base classes

Many .NET framework classes

Development, debugging, and profiling tools

Execution and code management

IL-to-native translators and optimizers

What this means is that in the .NET world, various programming languages will be more
equal in capability than they have ever been before, although clearly not all languages
will support all CLR services.
What is the CTS?
CTS = Common Type System. This is the range of types that the .NET runtime
understands, and therefore that .NET applications can use. However note that not all
.NET languages will support all the types in the CTS. The CTS is a superset of the CLS.
What is the CLS?
CLS = Common Language Specification. This is a subset of the CTS that all .NET
languages are expected to support. The idea is that any program that uses CLScompliant types can interoperate with any .NET program written in any language.
In theory this allows very tight interop between various .NET languages, for example
allowing a C# class to inherit from a VB class.
What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or
CIL (Common Intermediate Language). All .NET source code (of any language) is
compiled to IL. The IL is then converted to machine code at the point where the software

35

is installed, or at run-time by a Just-In-Time (JIT) compiler.


What does "managed" mean in the .NET context?
The term "managed" is the cause of much confusion. It is used in various places within
.NET, meaning slightly different things. Managed code: The .NET framework provides
several core run-time services to the programs that run within it, for example
exception handling and security. For these services to work, the code must provide a
minimum level of information to the runtime.
Such code is called managed code. All C# and Visual Basic.NET code is managed by
default. Visual Studio 7 C++ code is not managed by default, but the compiler can
produce managed code by specifying a command-line switch (/com+).
Managed data: This is data that is allocated and de-allocated by the .NET runtime's
garbage collector. C# and VB.NET data is always managed. Visual Studio 7 C++ data is
unmanaged by default, even when using the /com+ switch, but it can be marked as
managed using the __gc keyword. Managed classes: This is usually referred to in the
context of Managed Extensions (ME) for C++. When using ME C++, a class can be
marked with the __gc keyword. As the name suggests, this means that the memory for
instances of the class is managed by the garbage collector, but it also means more than
that. The class becomes a fully paid-up member of the .NET community with the benefits
and restrictions that brings. An example of a benefit is proper interop with classes written
in other languages, for example, a managed C++ class can inherit from a VB class. An
example of a restriction is that a managed class can only inherit from one base class.
What is reflection?
All .NET compilers produce metadata about the types defined in the modules they
produce. This metadata is packaged along with the module (modules in turn are
packaged together in assemblies), and can be accessed by a mechanism called
reflection. The System.Reflection namespace contains classes that can be used to
interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to
access type library data in COM, and it is used for similar purposes, for example
determining data type sizes for marshaling data across context/process/machine
boundaries.
Reflection can also be used to dynamically invoke methods (see
System.Type.InvokeMember ) , or even create types dynamically at run-time (see
System.Reflection.Emit.TypeBuilder).
What is the difference between Finalize and Dispose (Garbage collection) ?
Class instances often encapsulate control over resources that are not managed by the
runtime, such as window handles (HWND), database connections, and so on. Therefore,
you should provide both an explicit and an implicit way to free those resources. Provide
implicit control by implementing the protected Finalize Method on an object (destructor
syntax in C# and the Managed Extensions for C++). The garbage collector calls this
method at some point after there are no longer any valid references to the object. In
some cases, you might want to provide programmers using an object with the ability to
explicitly release these external resources before the garbage collector frees the object.
If an external resource is scarce or expensive, better performance can be done if the
programmer explicitly releases resources when they are no longer being used. To provide
explicit control, implement the Dispose method provided by the IDisposable Interface.
The consumer of the object should call this method when it is done using the object.
Dispose can be called even if other references to the object are alive. Note that even
when you provide explicit control by way of Dispose, you should provide implicit cleanup

36

using the Finalize method. Finalize provides a backup to prevent resources from
permanently leaking if the programmer fails to call Dispose.
What is Partial Assembly References?
Full Assembly reference: A full assembly reference includes the assembly's text name,
version, culture, and public key token (if the assembly has a strong name). A full
assembly reference is required if you reference any assembly that is part of the common
language runtime or any assembly located in the Global Assembly Cache.
Partial Assembly reference: We can dynamically reference an assembly by providing only
partial information, such as specifying only the assembly name. When you specify a
partial assembly reference, the runtime looks for the assembly only in the
application directory.
We can make partial references to an assembly in your code in one of the following ways:

Use a method such as System.Reflection.Assembly.Load and specify only a partial


reference. The runtime checks for the assembly in the application directory.

Use the System.Reflection.Assembly.LoadWithPartialName method and specify


only a partial reference. The runtime checks for the assembly in the application
directory and in the Global Assembly Cache.

Changes to which portion of version number indicates an incompatible change?


Major or minor. Changes to the major or minor portion of the version number indicate an
incompatible change. Under this convention, then version 2.0.0.0 would be considered
incompatible with version 1.0.0.0. Examples of an incompatible change would be a
change to the types of some method parameters or the removal of a type or method
altogether.
Build. The Build number is typically used to distinguish between daily builds or smaller
compatible releases.
Revision. Changes to the revision number are typically reserved for an incremental build
needed to fix a specific bug. You'll sometimes hear this referred to as the "emergency
bug fix" number in that the revision is what is often changed when a fix to a specific bug
is shipped to a customer.
What is side-by-side execution? Can two applications, one using private assembly and
the other using Shared assembly be started as side-by-side executables? Side-by-side
execution is the ability to run multiple versions of an application or component on the
same computer. You can have multiple versions of the Common Language Runtime, and
multiple versions of applications and components that use a version of the runtime, on
the same computer at the same time. Since versioning is only applied to shared
assemblies, and not to private assemblies, two applications, one using private assembly
and one using shared assembly cannot be started as side-by-side executables.
Why are strings called an immutable data type?
The memory representation of a string is an Array of Characters, so on re-assigning the
new array of Char is formed and the start address is changed, thus keeping the old string
in memory for the Garbage Collector to dispose.
What does assert() method do?

37

In debug compilations, assert takes in a Boolean condition as a parameter, and shows


the error dialog if the condition is false. The program proceeds without any interruption if
the condition is true.
What's the difference between the Debug class and Trace class?
The documentation looks the same. Use the Debug class for debug builds, use the Trace
class for both debug and release builds.
Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. For applications that are constantly running you
run the risk of overloading the machine and the hard drive. Five levels range from None
to Verbose, allowing you to fine-tune the tracing activities.
Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.
How do assemblies find each other?
By searching directory paths. There are several factors that can affect the path (such as
the AppDomain host, and application configuration files), but for private assemblies the
search path is normally the application's directory and its sub-directories. For shared
assemblies, the search path is normally the same as the private assembly path plus the
shared assembly cache.
How does assembly versioning work?
Each assembly has a version number called the compatibility version. Also each
reference to an assembly (from another assembly) includes both the name and version of
the referenced assembly.The version number has four numeric parts (for example
5.5.2.33). Assemblies with either of the first two parts different are normally viewed as
incompatible. If the first two parts are the same, but the third is different, the assemblies
are deemed as "maybe compatible". If only the fourth part is different then the
assemblies are deemed compatible. However, this is just the default guideline, it is the
version policy that decides to what extent these rules are enforced. The version policy
can be specified via the application configuration file.
What is garbage collection?
Garbage collection is a system whereby a run-time component takes responsibility for
managing the lifetime of objects and the heap memory that they occupy. This concept is
not new to .NET. Java and many other languages/runtimes have used garbage collection
for some time.
Why doesn't the .NET runtime offer deterministic destruction?
Because of the garbage collection algorithm. The .NET garbage collector works by
periodically running through a list of all the objects that are currently being referenced by
an application. All the objects that it doesn't find during this search are ready to be
destroyed and the memory reclaimed. The implication of this algorithm is that the
runtime doesn't get notified immediately when the final reference on an object goes
away, it only determines during the next sweep of the heap.
Futhermore, this type of algorithm works best by performing the garbage collection
sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection
sweep.
Is the lack of deterministic destruction in .NET a problem?

38

It's certainly an issue that affects component design. If you have objects that maintain
expensive or scarce resources (for example database locks), you need to provide some
way for the client to tell the object to release the resource when it is done. Microsoft
recommends that you provide a method called Dispose() for this purpose. However, this
causes problems for distributed objects, in a distributed system who calls the Dispose()
method? Some form of reference-counting or ownership-management mechanism is
needed to handle distributed objects, unfortunately the runtime offers no help with this.
What is serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization
is the opposite process of creating an object from a stream of bytes. Serialization /
Deserialization is mostly used to transport objects (for example during remoting), or to
persist objects (for example to a file or database).
Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library, XmlSerializer and
SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses
SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own
code.
Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure
serialization for a specific class. For example, a field or property can be marked with the
[XmlIgnore] attribute to exclude it from serialization. Another example is the
[XmlElement]
attribute, that can be used to specify the XML element name to be used for a specific
property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by
attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's
[XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by
implementing the the ISerializable interface on the class whose instances are to be
serialized.
Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you
serialize or deserialize an object of a given type in an application, there is a significant
delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a
poor choice for loading configuration settings during startup of a GUI application.
Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary,
for example Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.
What are attributes?
There are at least two types of .NET attributes. The first type I will refer to as a metadata
attribute, it allows some data to be attached to a class or method. This data becomes
part of the metadata for the class, and (like other class metadata) can be accessed via
reflection.
The other type of attribute is a context attribute. Context attributes use a similar syntax
to metadata attributes but they are fundamentally different. Context attributes provide
an interception mechanism whereby instance activation and method calls can be
pre- and/or post-processed.

39

How does CAS work?


The CAS security policy revolves around two key concepts, code groups and permissions.
Each .NET assembly is a member of a specific code group, and each code group is
granted the permissions specified in a named permission set.
For example, using the default security policy, a control downloaded from a web site
belongs to the "Zone - Internet" code group, that adheres to the permissions defined by
the "Internet" named permission set. (Naturally the "Internet" named permission set
represents a very restrictive range of permissions.)
Who defines the CAS code groups?
Microsoft defines some default ones, but you can modify these and even create your
own. To see the code groups defined on your system, run "caspol -lg" from the commandline. On my system it looks like this:
Level = Machine
Code Groups
1. All code: Nothing
1.1. Zone: MyComputer: FullTrust
1.1.1. Honor SkipVerification requests: SkipVerification
1.2. Zone: Intranet: LocalIntranet
1.3. Zone: Internet: Internet
1.4. Zone: Untrusted: Nothing
1.5. Zone: Trusted: Internet
1.6. StrongName:
0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444F
EF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC
8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D
38561AABF5C
AC1DF1734633C602F8F2D5:
Note the hierarchy of code groups, the top of the hierarchy is the most general ("All
code"), that is then sub-divided into several
groups, each of which in turn can be sub-divided. Also note that (somewhat counterintuitively) a sub-group can be associated with a more permissive permission set than its
parent.
How do I define my own code group?
Use caspol. For example, suppose you trust code from http://www.mydomain.com/ and
you want it to have full access to your system, but you want to keep the default
restrictions for all other internet sites. To do this, you would add a new code group as a
sub-group of the "Zone - Internet" group, like this:
caspol -ag 1.3 -site http://www.mydomain.com/ FullTrust
Now if you run caspol -lg then you will see that the new group has been added as group
1.3.1:
1.3. Zone: Internet: Internet
1.3.1. Site: http://www.mydomain.com/: FullTrust
Note that the numeric label (1.3.1) is just a caspol invention to make the code groups

40

easy to manipulate from the command-line. The underlying runtime never sees it.
How do I change the permission set for a code group?
Use caspol. If you are the machine administrator then you can operate at the "machine"
level, which means that not only do the changes you make become the default for the
machine, but also those users cannot change the permissions to be more permissive. If
you are a normal (non-admin) user then you can still modify the permissions, but only to
make them more restrictive. For example, to allow intranet code to do what it likes you
might do this:
caspol -cg 1.2 FullTrust
Note that because this is more permissive than the default policy (on a standard system),
you should only do this at the machine level, doing it at the user level will have no effect.
I can't be bothered with all this CAS stuff. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off
Can I look at the IL for an assembly?
Yes. Microsoft supplies a tool called Ildasm that can be used to view the metadata and IL
for an assembly.
Can source code be reverse-engineered from IL?
Yes, it is often relatively straightforward to regenerate high-level source (for example C#)
from IL.
How can I stop my code being reverse-engineered from IL?
There is currently no simple way to stop code being reverse-engineered from IL. In the
future it is likely that IL obfuscation tools will become available, either from Microsoft or
from third parties. These tools work by "optimising" the IL in such a way that reverseengineering becomes much more difficult.
Of course if you are writing web services then reverse-engineering is not a problem as
clients do not have access to your IL.
Is there built-in support for tracing/logging?
Yes, in the System.Diagnostics namespace. There are two main classes that deal with
tracing, Debug and Trace. They both work in a similar way, the difference is that tracing
from the Debug class only works in builds that have the DEBUG symbol defined, whereas
tracing from the Trace class only works in builds that have the TRACE symbol defined.
Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing
that you want to work in debug and release builds, and
System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug
builds.
Can I redirect tracing to a file?
Yes. The Debug and Trace classes both have a Listeners property, that is a collection of
sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine
respectively. By default the Listeners collection contains a single sink, that is an
instance of the DefaultTraceListener class. This sends output to the Win32
OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method.

41

This is useful when debugging, but if you're trying to trace a problem at a customer site
then redirecting the output to a file is more appropriate. Fortunately, the
TextWriterTraceListener class is provided for this purpose.
What are the contents of an assembly?
In general, a static assembly can consist of the four elements:
1.

The assembly manifest, that contains assembly metadata.

2.

Type metadata.

3.

Microsoft Intermediate Language (MSIL) code that implements the types.

4.

A set of resources.

What is GC (Garbage Collection) and how it works


One of the good features of the CLR is Garbage Collection, that runs in the background
collecting unused object references, freeing us from having to ensure we always destroy
them. In reality the time difference between you releasing the object instance and it
being garbage collected is likely to be very small, since the GC is always running.
[The process of transitively tracing through all pointers to actively used objects to locate
all objects that can be referenced, and then arranging to reuse any heap memory that
was not found during this trace. The Common Language Runtime garbage collector also
compacts the memory that is in use to reduce the working space needed for the heap.]
Heap
A portion of memory reserved for a program to use for the temporary storage of data
structures whose existence or size cannot be determined until the program is running.
Differnce between Managed code and unmanaged code?
Managed Code:
Code that runs under a "contract of cooperation" with the Common Language Runtime.
Managed code must supply the metadata necessary for the runtime to provide services
such as memory management, cross-language integration, code access security,
and automatic lifetime control of objects. All code based on Microsoft Intermediate
Language (MSIL) executes as managed code.
Un-Managed Code
Code that is created without regard for the conventions and requirements of the
Common Language Runtime. Unmanaged code executes in the Common Language
Runtime environment with minimal services (for example, no garbage collection, limited
debugging, and so on).
What is MSIL, IL, CTS and, CLR ?
MSIL: (Microsoft Intermediate Language)
When compiling to managed code, the compiler translates your source code into
Microsoft Intermediate Language (MSIL), that is a CPU-independent set of instructions
that can be efficiently converted to native code. MSIL includes instructions for loading,
storing, initializing, and calling methods on objects, as well as instructions for arithmetic
and logical operations, control flow, direct memory access, exception handling, and other

42

operations. Before code can be executed, MSIL must be converted to CPU-specific code,
usually by a Just-In-Time (JIT) compiler. Because the Common Language Runtime supplies
one or more JIT compilers for each computer architecture it supports, the same set of
MSIL can be JIT-compiled and executed on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the
types in your code, including the definition of each type, the signatures of each type's
members, the members that your code references, and other data that the runtime uses
at execution time. The MSIL and metadata are contained in a Portable Executable (PE) file
that is based on and extends the published Microsoft PE and Common Object File Format
(COFF) used historically for executable content. This file format, that accommodates MSIL
or native code as well as metadata, enables the operating system to recognize Common
Language Runtime images. The presence of metadata in the file along with the MSIL
enables your code to describe itself, that means that there is no need for type libraries or
Interface Definition Language (IDL). The runtime locates and extracts the metadata from
the file as needed during execution.
IL: (Intermediate Language)
A language used as the output of a number of compilers and as the input to a Just-InTime (JIT) compiler. The Common Language Runtime includes a JIT compiler for
converting MSIL to native code.
CTS: (Common Type System)
The specification that determines how the Common Language Runtime defines, uses,
and manages types.
CLR: (Common Language Runtime)
The engine at the core of managed code execution. The runtime supplies managed code
with services such as cross-language integration, code access security, object lifetime
management, and debugging and profiling support.
What is Reference type and value type ?
Reference Type
Reference types are allocated on the managed CLR heap, just like object types. A data
type that is stored as a reference to the value's location. The value of a reference type is
the location of the sequence of bits that represent the type's data. Reference types can
be self-describing types, pointer types, or interface types.
Value Type
Value types are allocated on the stack just like primitive types in VBScript, VB6 and C/C+
+. Value types that are not instantiated using new go out of scope when the function
they are defined within returns. Value types in the CLR are defined as types that derive
from system.valueType.
A data type that fully describes a value by specifying the sequence of bits that
constitutes the value's representation. Type information for a value type instance is not
stored with the instance at run time, but it is available in metadata. Value type instances
can be treated as objects using boxing.
What is Boxing and unboxing ?
Boxing

43

The conversion of a value type instance to an object, that implies that the instance will
carry full type information at run time and will be allocated in the heap. The Microsoft
Intermediate Language (MSIL) instruction set's box instruction converts a value type to
an object by making a copy of the value type and embedding it in a newly allocated
object.
Un-Boxing
The conversion of an object instance to a value type.
What is JIT and how does it work?
An acronym for "Just-In-Time", a phrase that describes an action that is taken only when
it becomes necessary, such as Just-In-Time compilation or Just-In-Time object activation.
What is Portable Executable (PE)?
The file format used for executable programs and for files to be linked together to form
executable programs.
What is a strong name?
A name that consists of an assembly's identity; its simple text name, version number,
and culture information (if provided) strengthened by a public key and a digital signature
generated over the assembly. Because the assembly manifest
contains file hashes for all the files that constitute the assembly implementation, it is
sufficient to generate the digital signature over just the one file in the assembly that
contains the assembly manifest. Assemblies with the same strong name are expected to
be identical.
What is Global Assembly Cache?
A machine-wide code cache that stores assemblies specifically installed to be shared by
many applications on the computer. Applications deployed in the Global Assembly Cache
must have a strong name.
What is the difference between constants, readonly and, static?
Constants: The value can't be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
What is difference between shared and public?
An assembly that can be referenced by more than one application. An assembly must be
explicitly built to be shared by giving it a cryptographically strong name.
What is namespace used for loading assemblies at run time and name the
methods?
System.Reflection
What are the types of authentication in .Net?
We have three types of authentication:

1.

Form authentication

44

2.

Windows authentication

3.

Passport

This has to be declared in the web.config file.


What is the difference between a Struct and a Class ?
The struct type is suitable for representing lightweight objects such as Point, Rectangle,
and Color. Although it is possible to represent a point as a class, a struct is more efficient
in some scenarios. For example, if you declare an array of 1000 Point objects,
you will allocate additional memory for referencing each object. In this case, the struct is
less expensive.
When you create a struct object using the new operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated without using
the new operator. If you do not use new then the fields will remain unassigned and the
object cannot be used until all of the fields are initialized. It is an error to declare a
default (parameterless) constructor for a struct. A default constructor is always provided
to initialize the struct members to their default values.
It is an error to initialize an instance field in a struct.
There is no inheritance for structs as there is for classes. A struct cannot inherit from
another struct or class, and it cannot be the base of a class. Structs, however, inherit
from the base class Object. A struct can implement interfaces, and it does that exactly as
classes do. A struct is a value type, while a class is a reference type.
How big is the datatype int in .NET?
32 bits.
How big is the char?
16 bits (Unicode).
How do you initiate a string without escaping each backslash?
Put an @ sign in front of the double-quoted string.
What's the access level of the visibility type internal?
Current application.
Explain encapsulation ?
The implementation is hidden, the interface is exposed.
What data type should you use if you want an 8-bit value that's signed?
sbyte.
Speaking of Boolean data types, what's different between C# and C/C++?
There's no conversion between 0 and false, as well as any other number and true, like in
C/C++.
Where are the value-type variables allocated in the computer RAM?

45

Stack.
Where do the reference-type variables go in the RAM?
The references go on the stack, while the objects themselves go on the heap.
What is the difference between the value-type variables and reference-type
variables in terms of garbage collection?
The value-type variables are not garbage-collected, they are just popped off the stack
when they go out of scope, the reference-type objects
are picked up by GC when their references go null.
How do you convert a string into an integer in .NET?
Int32.Parse(string)
How do you box a primitive data type variable?
Assign it to the object, pass an object.
Why do you need to box a primitive variable?
To pass it by reference.
What's the difference between Java and .NET garbage collectors?
Sun left the implementation of a specific garbage collector up to the JRE developer, so
their performance varies widely, depending on whose JRE you're using. Microsoft
standardized on their garbage collection.
How do you enforce garbage collection in .NET?
System.GC.Collect();
What's different about namespace declaration when comparing that to
package declaration in Java?
No semicolon.
What's the difference between const and readonly?
You can initialize readonly variables to some runtime values. Let's say your program uses
current date and time as one of the values that won't change. This way you declare
public readonly string DateT = new DateTime().ToString().
What happens when you encounter a continue statement inside the for loop?
The code for the rest of the loop is ignored, the control is transferred back to the
beginning of the loop.
What's the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases where a lot of manipulation is done to the
text. Strings are immutable, so each time it's being operated on, a new instance is
created.
Can you store multiple data types in System.Array?

46

No.
What's the difference between the System.Array.CopyTo() and
System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow.
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
What's the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
What's class SortedList underneath?
A sorted HashTable.
Will a finally block be executed if the exception had not occurred?
Yes.
Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if
there are any) and then whatever follows the finally block.
Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper
code to handle that error instead of passing a new Exception object to the catch block?
Throwing your own exceptions signifies some design flaws in the project.
What's a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as
function pointers.
What's a multicast delegate?
It's a delegate that points to and eventually fires off several methods.
How's the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run
(that was available under Win32), but also the version of the assembly.
What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
What's a satellite assembly?
When you write a multilingual or multi-cultural application in .NET and want to distribute
the core application separately from the localized modules, the localized assemblies that
modify the core application are called satellite assemblies.

47

What namespaces are necessary to create a localized application?


System.Globalization, System.Resources.
What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the
error dialog if the condition is false. The program proceeds without any interruption if the
condition is true.
What's the difference between the Debug class and Trace class?
The documentation looks the same. Use the Debug class for debug builds, use the Trace
class for both debug and release builds.
Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose and for some applications that are constantly
running you run the risk of overloading the machine and the hard drive there. Five levels
range from None to Verbose, allowing to fine-tune the tracing activities.
Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.
What namespaces are necessary to create a localized application?
System.Globalization, System.Resources.
What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing
data, proper handling) and exception test cases (exceptions are thrown and caught
properly).
Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET then just go to the Immediate window.
What's the implicit name of the parameter that gets passed into the class' set
method?
Value, and it's datatype depends on whatever variable we're changing.
How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it's a double colon in C+
+.
Does C# support multiple inheritance?
No, use interfaces instead.
When you inherit a protected class-level variable, who is it available to?
Derived Classes.
What's the top .NET class that everything is derived from?

48

System.Object.
How's method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading
simply involves having a method with the same name within the class.
What does the keyword virtual mean in the method definition?
The method can be overridden.
Can you declare the override method static while the original method is nonstatic?
No, you can't, the signature of the virtual method must remain the same, only the
keyword virtual is changed to keyword override.
Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, you need to be
protected in the base class to allow any sort of access.
Can you prevent your class from being inherited and becoming a base class for
some other classes?
Yes, that's what the keyword sealed in the class definition is for. The developer trying to
derive from your class will get a message: cannot inherit from Sealed class
WhateverBaseClassName. It's the same concept as final class in Java.
Can you allow a class to be inherited, but prevent the method from being
overridden?
Yes, just leave the class public and make the method sealed.
Why can't you specify the accessibility modifier for methods inside the
interface?
They all must be public. Therefore, to prevent you from getting the false impression that
you have any freedom of choice, you are not allowed to specify any accessibility, it's
public by default.
Can you inherit multiple interfaces?
Yes, why not?
And if they have conflicting method names?
It's up to you to implement the method inside your own class, so implementation is left
entirely up to you. This might cause a problem on a higher-level scale if similarly named
methods from different interfaces expect different data, but as far as the compiler cares
you're okay.
What's the difference between an interface and abstract class?
In the interface all methods must be abstract, in the abstract class some methods can be
concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract
classes.
How can you overload a method?

49

Different parameter data types, different number of parameters, different order of


parameters.
If a base class has a bunch of overloaded constructors and an inherited class
has another bunch of overloaded constructors, can you enforce a call from an
inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then the keyword base (parameter list to invoke the
appropriate constructor) in the overloaded constructor definition inside the inherited
class.
What's the difference between the System.String and System.StringBuilder
classes?
System.String is immutable, System.StringBuilder was designed for the purpose of
having a mutable string where a variety of operations can be performed.
Does C# support multiple-inheritance?
No, use interfaces instead.
When you inherit a protected class-level variable, who is it available to?
The derived class.
Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class
interface, they are inherited.
Describe the accessibility modifier "protected internal".
It is available to derived classes and classes within the same Assembly (and naturally
from the base class it's declared in).
What's the top .NET class that everything is derived from?
System.Object.
What's the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string
manipulation. Strings are immutable, so each time it's being operated on, a new instance
is created.
Can you store multiple data types in System.Array?
No.
What's the .NET class that allows the retrieval of a data element using a
unique key?
HashTable.
Will the finally block get executed if an exception has not occurred?
Yes.

50

What's an abstract class?


A class that cannot be instantiated. An abstract class is a class that must be inherited
and have the methods overridden. An abstract class is essentially a blueprint for a class
without any implementation.
When do you absolutely have to declare a class as abstract?

1.

When at least one of the methods in the class is abstract.

2.

When the class itself is inherited from an abstract class, but not all base abstract
methods have been overridden.

What's an interface?
It's an abstract class with public abstract methods all of which must be implemented in
the inherited classes.
Why can't you specify the accessibility modifier for methods inside the
interface?
They all must be public. Therefore, to prevent you from getting the false impression that
you have any freedom of choice,
you are not allowed to specify any accessibility, it's public by default.
What's the difference between an interface and abstract class?
In an interface class, all methods must be abstract. In an abstract class some methods
can be concrete. In an interface class, no accessibility modifiers are allowed, which is ok
in an abstract class.
How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having another method with the same name
within the class.
Can you declare an override method to be static if the original method is nonstatic?
No. The signature of the virtual method must remain the same, only the keyword virtual
is changed to keyword override.
Can you override private virtual methods?
No. Private methods are not accessible outside the class.
Can you write a class without specifying a namespace? Which namespace does
it belong to by default?
Yes, you can, then the class belongs to the global namespace that has no name. For
commercial products, naturally, you wouldn't want the global namespace.
What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into
messages on one end, and deserializing and decoding messages into data on the other
end.

51

Differences between .NET and J2EE


Differences between J2EE and the .NET Platform
Vendor Neutrality
The .NET platform is not vendor neutral, it is tied to the Microsoft operating systems. But
neither are any of the J2EE implementations.
Many companies buy into J2EE believing that it will give them vendor neutrality. And, in
fact, this is a stated goal of Sun's vision:
A wide variety of J2EE product configurations and implementations, all of that meet the
requirements of this specification, are possible. A portable J2EE application will function
correctly when successfully deployed in any of these products. (ref: Java 2 Platform
Enterprise Edition Specification, v1.3, page 2-7 available athttp://java.sun.com/j2ee/)
Overall Maturity
Since the .NET platform has a three year lead over the J2EE, it should be no surprise to
learn that the .NET platform is far more mature than the J2EE platform. We have high
volume and highly reliable web sites using .NET technologies (NASDAQ and Dell being
among many examples).
Interoperability and Web Services
The .NET platform eCollaboration model is, as I have discussed at length, based on the
UDDI and SOAP standards. These standards are widely supported by more than 100
companies. Microsoft, along with IBM and Ariba, are the leaders in this area. Sun is a
member of the UDDI consortium and recognizes the importance of the UDDI standards. In
a recent press release, Sun's George Paolini, Vice President for the Java Community
Development, says:
"Sun has always worked to help establish and support open, standards-based
technologies that facilitate the growth of network-based applications, and we see UDDI
as an important project to establish a registry framework for business-to-business ecommerce
But while Sun publicly says it believes in the UDDI standards, in reality, Sun has done
nothing whatsoever to incorporate any of the UDDI standards into J2EE.
Scalability
The following is a typical comparision of w.r.t Systems and their costs.
J2EE
Company System
Bull
$1,980,179
IBM
$2,026,681
Bull
$3,037,499
IBM
$3,097,055
Bull
$9,563,263
IBM
$9,560,594

Total Sys.

Cost

Escala T610 c/s


RS/6000 Enterprise Server F80
Escala EPC810 c/s

16,785
16,785
33,375

RS/6000 Enterprise Server M80

33,375

Escala EPC2450

110,403

IBM eServer pSeries 680 Model 7017-S85

110,403

52

.NET platform systems


Company System
Dell
Compaq
Dell
IBM
Compaq
Compaq
Compaq
Compaq
Compaq

Total Sys.

Cost

PowerEdge 4400
ProLiant ML-570-6/700-3P
PowerEdge 6400 30,
Netfinity 7600 c/s
ProLiant 8500-X550-64P
ProLiant 8500-X700-64P
ProLiant 8500-X550-96P
ProLiant 8500-X700-96P
ProLiant 8500-700-192P

16,263 $273,487
20,207 $201,717
231 $334,626
32,377 $443,463
161,720 $3,534,272
179,658 $3,546,582
229,914 $5,305,571
262,244 $5,305,571
505,303 $10,003,826

Framework Support
The .NET platform includes an eCommerce framework called Commerce Server. At this
point, there is no equivalent vendor-neutral framework in the J2EE space. With J2EE, you
should assume that you will be building your new eCommerce solution from scratch.
Moreover, no matter what [J2EE] vendor you choose, if you expect a component
framework that will allow you to quickly field complete e-business applications, you are in
for a frustrating experience.
Language
In the language arena, the choice is about as simple as it gets. J2EE supports Java, and
only Java. It will not support any other language in the foreseeable future. The .NET
platform supports every language except Java (although it does support a language that
is syntactically and functionally equivalent to Java, C#). In fact, given the importance of
the .NET platform as a language independent vehicle, it is likely that any language that
comes out in the near future will include support for the .NET platform.
Some companies are under the impression that J2EE supports other languages. Although
both IBM's WebSphere and BEA's WebLogic support other languages, neither does it
through their J2EE technology. There are only two official ways in the J2EE platform to
access other languages, one through the Java Native Interface and the other through
CORBA interoperability. Sun recommends the later approach. As Sun's Distinguished
Scientist and Java Architect Rick Cattell said in a recent interview.
Portability
The reason that operating system portability is a possibility with J2EE is not so much
because of any inherent portability of J2EE, as it is that most of the J2EE vendors support
multiple operating systems. Therefore as long as one sticks with a given J2EE vendor and
a given database vendor, moving from one operating system to another should be
possible. This is probably the single most important benefit in favor of J2EE over the .NET
platform, that is limited to the Windows operating system. It is worth noting, however,
that Microsoft has submitted the specifications for C# and a subset of the .NET
Framework (called the Common Language Infrastructure) to ECMA, the group that
standardizes JavaScript.
J2EE offers an acceptable solution to ISVs when the product must be marketed to nonWindows customers, particularly when the J2EE platform itself can be bundled with the
ISV's product as an integrated offering.
If the primary customer base for the ISV is Windows customers then the .NET platform
should be chosen. It will provide much better performance at a much lower cost.
Client device independence

53

The major difference is that with Java, it is the presentation tier programmer that
determines the ultimate HTML that will be delivered to the client, and with .NET, it is a
Visual Studio.NET control.
This Java approach has three problems. First, it requires a lot of code on the presentation
tier, since every possible thin client system requires a different code path. Second, it is
very difficult to test the code with every possible thin client system. Third, it is very
difficult to add new thin clients to an existing application, since to do so involves
searching through, and modifying a tremendous amount of presentation tier logic.
The .NET Framework approach is to write device independent code that interacts with
visual controls. It is the control, not the programmer, that is responsible for determining
what HTML to deliver, based on the capabilities of the client device.. In the .NET
Framework model, one can forget that such a thing as HTML even exists!
Conclusion
Sun's J2EE vision is based on a family of specifications that can be implemented by many
vendors. It is open in the sense that any company can license and implement the
technology, but closed in the sense that it is controlled by a single vendor, and a selfcontained architectural island with very limited ability to interact outside of itself. One of
J2EE's major disadvantages is that the choice of the platform dictates the use of a single
programming language, and a programming language that is not well suited for most
businesses. One of J2EE's major advantages is that most of the J2EE vendors do offer
operating system portability.
Microsoft's .NET platform vision is a family of products rather than specifications, with
specifications used primarily to define points of interoperability. The major disadvantage
of this approach is that it is limited to the Windows platform, so applications written for
the .NET platform can only be run on .NET platforms. Their are several important
advantages to the .NET platform:

The cost of developing applications is much lower, since standard business


languages can be used and device independent presentation tier logic can be
written.

The cost of running applications is much lower, since commodity hardware


platforms (at 1/5 the cost of their Unix counterparts) can be used.

The ability to scale up is much greater, with the proven ability to support at least
ten times the number of clients any J2EE platform has shown itself able to
support.

Interoperability is much stronger, with industry standard eCollaboration built into


the platform.

What are the Main Features of .NET platform?


The following are the features of the .NET Platform.
Common Language Runtime
Explains the features and benefits of the Common Language Runtime, a run-time environment that manages the
execution of code and provides services that simplify the development process.

54

Assemblies
Defines the concept of assemblies, that are a collections of types and resources that form logical units of
functionality. Assemblies are the fundamental units of deployment, version control, reuse, activation scoping,
and security permissions.
Application Domains
Explains how to use application domains to provide isolation between applications.
Runtime Hosts
Describes the runtime hosts supported by the .NET Framework, including ASP.NET, Internet Explorer, and shell
executables.
Common Type System
Identifies the types supported by the Common Language Runtime.
Metadata and Self-Describing Components
Explains how the .NET Framework simplifies component interoperation by allowing compilers to emit
additional declarative information, or metadata, into all modules and assemblies.
Cross-Language Interoperability
Explains how managed objects created in various programming languages can interact with one another.
.NET Framework Security
Describes mechanisms for protecting resources and code from unauthorized code and unauthorized users.
.NET Framework Class Library
Introduces the library of types provided by the .NET Framework, that expedites and optimizes the development
process and gives you access to system functionality.
What is the use of JIT ?
Just- In-Time (JIT) is a compiler that converts MSIL code to Native Code (in other words, CPU-specific code
that runs on the same computer architecture).
Because the Common Language Runtime supplies a JIT compiler for each supported CPU architecture,
developers can write a set of MSIL that can be JIT-compiled and run on computers with various architectures.
However, your managed code will run only on a specific operating system if it calls platform-specific native
APIs, or a platform-specific class library.
JIT compilation takes into account the fact that some code might never get called during execution. Rather than
using time and memory to convert all the MSIL in a Portable Executable (PE) file to native code, it converts the
MSIL as needed during execution and stores the resulting native code so that it is accessible for subsequent
calls. The loader creates and attaches a stub to each of a type's methods when the type is loaded. On the initial
call to the method, the stub passes control to the JIT compiler, that converts the MSIL for that method into
native code and modifies the stub to direct execution to the location of the native code. Subsequent calls of the
JIT-compiled method proceed directly to the native code that was previously generated, reducing the time it
takes to JIT-compile and run the code.
Assembly and Global Assembly Cache (GAC) and Metadata
Assembly: An assembly is the primary building block of a .NET based application. It is a collection of
functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All

55

managed types and resources are marked either as accessible only within their implementation unit, or as
accessible by code outside that unit. It overcomes the problem of "DLL Hell".The .NET Framework uses
assemblies as the fundamental unit for several purposes:

Security

Type Identity

Reference Scope

Versioning

Deployment

Global Assembly Cache: Assemblies can be shared among multiple applications on the
machine by registering them in the Global Assembly Cache (GAC). The GAC is a machine
wide local cache of assemblies maintained by the .NET Framework. We can register the
assembly to the Global Assembly Cache using the gacutil command.
We can navigate to the GAC directory, "C:\winnt\Assembly", in Windows Explorer. In the
tools menu select the cache properties; in the windows displayed you can set the
memory limit in MB used by the GAC
MetaData: Assemblies have Manifests. This Manifest contains Metadata information of
the Module/Assembly as well as detailed Metadata of other assemblies/modules
referenced (exported). It's the Assembly Manifest that differentiates between an
Assembly and a Module.
What are the mobile devices supported by the .Net platform
The Microsoft .NET Compact Framework is designed to run on mobile devices such as
mobile phones, Personal Digital Assistants (PDAs), and embedded devices. The easiest
way to develop and test a Smart Device Application is to use an emulator.
These devices are divided into the following two main divisions:

1.

Those that are directly supported by .NET (Pocket PCs, i-Mode phones, and WAP
devices)

2.

Those that are not (Palm OS and J2ME-powered devices).

What are GUIDs and why and where do we use them?


GUID is an acronym for Globally Unique Identifier, a unique 128-bit number produced by
the Windows OS or by some Windows applications to identify a specific component,
application, file, database entry, and/or user. For instance, a Web site may generate a
GUID and assign it to a user's browser to record and track the session. A GUID is also
used in a Windows registry to identify COM DLLs. Knowing where to look in the registry
and having the correct GUID yields a lot information about a COM object (in other words,
information in the type library, its physical location, and so on). Windows also identifies
user accounts by a username (computer/domain and username) and assigns it a GUID.
Some database administrators even will use GUIDs as primary key values in databases.
GUIDs can be created in a number of ways, but usually they are a combination of a few
unique settings based on a specific point in time (for example, an IP address, network

56

MAC address, clock date/time, and so on).


Describe the difference between inline and code behind; which is best in a
loosely coupled solution
ASP.NET supports two modes of page development: Page logic code that is written inside
<runat="server"> blocks within an .aspx file and dynamically compiled the first time the
page is requested on the server. Page logic code that is written within an external class
that is compiled prior to deployment on a server and linked "behind" the .aspx file at run
time.
Whats MSIL, and why should my developers need an appreciation of it if at all?
When compiling the source code to managed code, the compiler translates the source
into Microsoft Intermediate Language (MSIL). This is a CPU-independent set of
instructions that can efficiently be converted to native code. Microsoft Intermediate
Language (MSIL) is a translation used as the output of a number of compilers. It is the
input to a Just-In-Time (JIT) compiler. The Common Language Runtime includes a JIT
compiler for the conversion of MSIL to native code.
Before Microsoft Intermediate Language (MSIL) can be executed, it must be converted by
the .NET Framework Just-In-Time (JIT) compiler to native code. This is CPU-specific code
that runs on the same computer architecture as the JIT compiler. Rather than using time
and memory to convert all of the MSIL in a Portable Executable (PE) file to native code, it
converts the MSIL as needed during execution, then caches the resulting native code so
its accessible for any subsequent calls.
How many .NET languages can a single .NET DLL contain?
One
What type of code (server or client) is found in a Code-Behind class?
Server
What's an assembly?
Assemblies are the building blocks of .NET Framework applications; they form the
fundamental unit of deployment, version control, reuse, activation scoping, and security
permissions. An assembly is a collection of types and resources that are built to work
together and form a logical unit of functionality. An assembly provides the Common
Language Runtime with the information it needs to be aware of type implementations. To
the runtime, a type does not exist outside the context of an assembly.
How many classes can a single .NET DLL contain?
Unlimited.
What is the difference between string and String ?
No difference.
What is manifest?
It is the metadata that describes the assemblies.
What is metadata?
Metadata is machine-readable information about a resource, or "data about data". Such

57

information might include details on content, format, size, or other characteristics of a


data
source. In .NET, metadata includes type definitions, version information, external
assembly references, and other standardized information.
What are the types of assemblies?
The following are the four types of assemblies in .NET.
Static assemblies
These are the .NET PE files that you create at compile time.
Dynamic assemblies
These are PE-formatted, in-memory assemblies that you dynamically create at runtime
using the classes in the System.Reflection.Emit namespace.
Private assemblies
These are static assemblies used by a specific application.
Public or shared assemblies
These are static assemblies that must have a unique shared name and can be used by
any application.
An application uses a private assembly by referring to the assembly using a static path or
through an XML-based application configuration file. While the CLR doesn't enforce
versioning policies, in other words checking whether the correct version is used, for
private assemblies, it ensures that an application uses the correct shared assemblies
with which the application was built. Thus, an application uses a specific shared assembly
by referring to the specific shared assembly, and the CLR ensures that the correct version
is loaded at runtime.
In .NET, an assembly is the smallest unit of which you can associate a version number;
What are delegates?where are they used?
A delegate defines a reference type that encapsulates a method with a specific
signature. A delegate instance encapsulates a static or an instance method. Delegates
are roughly similar to function pointers in C++; however, delegates are type-safe and
secure.
When to you use the virutal keyword?
When we need to override a method of the base class in the sub class, then we provide
the virtual keyword in the base class method. This makes the method in the base class
overridable. Methods, properties, and indexers can be virtual, which means that their
implementation can be overridden in derived classes.
What are class access modifiers?
Access modifiers are keywords specifying the declared accessibility of a member or a
type. This section introduces the four access modifiers:

Public: Access is not restricted.

58

Protected: Access is limited to the containing class or types derived from the
containing class.

Internal: Access is limited to the current assembly.

Protected intetnal: Access is limited to the current assembly or types derived from
the containing class.

Private: Access is limited to the containing type.

What Is Boxing And Unboxing?


Boxing: Boxing is an implicit conversion of a value type to the type object type.
For example, consider the following declaration of a value-type variable:
int i = 123;
object o = (object) i;
Boxing Conversion
UnBoxing: Unboxing is an explicit conversion from the type object to a value type.
For example:
int i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing
What is value type and refernce type in .Net?.
Value Type: A variable of a value type always contains a value of that type. The assignment to a variable of a
value type creates a copy of the assigned value, while the assignment to a variable of a reference type creates a
copy of the reference but not of the referenced object.
The value types consist of the following two main categories:

Struct Type

Enumeration Type

Reference Type: Variables of reference types, referred to as objects, store references to


the actual data. This section introduces the following keywords used to declare reference
types:

Class

Interface

Delegate

This section also introduces the following built-in reference types:

59

object

string

Note: A few of the references are taken from other sites/sources.


What is the difference between structures and enumerations?
Unlike classes, structs are value types and do not require heap allocation. A variable of a
struct type directly contains the data of the struct, whereas a variable of a class type
contains a reference to the data. They are derived from the System.ValueType class.
An enum type is a distinct type that declares a set of named constants. They are
strongly-typed constants. They are unique types that allow declaration of symbolic
names with integral values. Enums are value types, which means they contain their own
value, can't inherit or be inherited from and assignments copy the value of one enum to
another.
public enum Grade
{
A,
B,
C
}
What are namespaces?
A namespace is a logical naming scheme for group related types. Some class types that
logically belong together can be put into a common namespace. They prevent
namespace collisions and they provide scoping. They are imported as "using" in C# or
"Imports" in Visual Basic. It seems as if these directives specify a specific assembly, but
they don't. A namespace can span multiple assemblies, and an assembly can define
multiple namespaces. When the compiler needs the definition for a class type, it tracks
through each of the various imported namespaces to the type name and searches each
referenced assembly until it is found.
Namespaces can be nested. This is very similar to packages in Java as far as scoping is
concerned.
How do you create shared assemblies?
Just look through the definition of Assemblies..

An Assembly is a logical unit of code

Assembly physically exist as DLLs or EXEs

One assembly can contain one or more files

The constituent files can include any file types like image files, text files and so
on. along with DLLs or EXEs

When you compile your source code by default the exe/DLL generated is actually
an assembly

60

Unless your code is bundled as assembly it can not be used in any other
application

When you talk about version of a component you are actually talking about
version of the assembly to which the component belongs.

Every assembly file contains information about itself. This information is called as
Assembly Manifest.

Following steps are involved in creating shared assemblies:

Create your DLL/EXE source code

Generate unique assembly name using SN utility

Sign your DLL/EXE with the private key by modifying AssemblyInfo file

Compile your DLL/EXE

Place the resultant DLL/EXE in Global Assembly Cache using AL utility

What is Global Assembly Cache?


Each computer where the Common Language Runtime is installed has a machine-wide
code cache called the Global Assembly Cache. The Global Assembly Cache stores
assemblies specifically designated to be shared by several applications on the computer.
There are several ways to deploy an assembly into the Global Assembly Cache:

Use an installer designed to work with the Global Assembly Cache. This is the
preferred option for installing assemblies into the Global Assembly Cache.

Use a developer tool called the Global Assembly Cache tool (Gacutil.exe),
provided by the .NET Framework SDK.

Use Windows Explorer to drag assemblies into the cache.

What is MSIL?
When compiling to managed code, the compiler translates your source code into
Microsoft Intermediate Language (MSIL), which is a CPU-independent set of instructions
that can be efficiently converted to native code. MSIL includes instructions for loading,
storing, initializing, and calling methods on objects, as well as instructions for arithmetic
and logical operations, control flow, direct memory access, exception handling, and other
operations. Before code can be run, MSIL must be converted to CPU-specific code, usually
by a Just-In-Time (JIT) compiler. Because the Common Language Runtime supplies one or
more JIT compilers for each computer architecture it supports, the same set of MSIL can
be JIT-compiled and run on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the
types in your code, including the definition of each type, the signatures of each type's
members, the members that your code references, and other data that the runtime uses

61

at execution time. The MSIL and metadata are contained in a Portable Executable (PE) file
that is based on and extends the published Microsoft PE and common object file format
(COFF) used historically for executable content. This file format, that accommodates MSIL
or native code as well as metadata, enables the operating system to recognize Common
Language Runtime images. The presence of metadata in the file along with the MSIL
enables your code to describe itself, that means that there is no need for type libraries or
Interface Definition Language (IDL). The runtime locates and extracts the metadata from
the file as needed during execution.
What is Jit compilers?.how many are available in clr?
Just-In-Time compiler- it converts the language that you write in .Net into machine
language that a computer can understand. there are tqo types of JITs one is memory
optimized and other is performace optimized.
What is tracing?Where it used.Explain few methods available
Tracing refers to collecting information about the application while it is running. You use
tracing information to troubleshoot an application.
Tracing allows us to observe and correct programming errors. Tracing enables you to
record information in various log files about the errors that might occur at run time. You
can analyze these log files to find the cause of the errors.
In .NET we have objects called Trace Listeners. A listener is an object that receives the
trace output and outputs it somewhere; that somewhere could be a window in your
development environment, a file on your hard drive, a Windows Event log, a SQL Server
or Oracle database, or any other customized data store.
The System.Diagnostics namespace provides the interfaces, classes, enumerations and
structures that are used for tracing The System.Diagnostics namespace provides two
classes named Trace and Debug that are used for writing errors and application execution
information in logs.
All Trace Listeners have the following functions. Functionality of these functions is same
except that the target media for the tracing output is determined by the Trace Listener.
Method Name
Result Fail Outputs the specified text with the Call Stack.
Write Outputs the specified text.
WriteLine Outputs the specified text and a carriage return.
Flush Flushes the output buffer to the target media.
Close Closes the output stream in order to not receive the tracing/debugging output.
How to set the debug mode?
Debug Mode for ASP.NET applications - To set ASP.NET appplication in debugging mode,
edit the application's web.config and assign the "debug" attribute in < compilation >
section to "true" as show below:
< configuration >
< system.web >
< compilation defaultLanguage="vb" debug="true" / >
....

62

...
..
< / configuration >
This case-sensitive attribute "debug tells ASP.NET to generate symbols for dynamically
generated files and enables the
debugger to attach to the ASP.NET application. ASP.NET will detect this change
automatically, without the need to restart the server. Debug Mode for ASP.NET
Webservices, Debugging an XML Web service created with ASP.NET is similar to the
debugging an ASP.NET Web application.
What is the property available to check if the page posted or not?
The Page_Load event handler in the page checks for IsPostBack property value, to
ascertain whether the page is posted. The Page.IsPostBack gets a value indicating
whether the page is being loaded in response to the client postback, or it is for the first
time. The value of Page.IsPostBack is True, if the page is being loaded in response to the
client postback; while its value is False, when the page is loaded for the first time. The
Page.IsPostBack property facilitates execution of certain routine in Page_Load, only once
(for for example in Page load, we need to set default value in controls, when page is
loaded for the first time. On post-back, we check for true value for IsPostback value and
then invoke server-side code to update data).
What are the abstract classes available under system.xml namespace?
The System.XML namespace provides XML related processing ability in .NET framework.
XmlReader and XMLWriter are the two abstract classes at the core of .NET Framework
XML classes:

1.

XmlReader provides a fast, forward-only, read-only cursor for processing an XML


document stream.

2.

XmlWriter provides an interface for producing XML document streams that


conform to the W3C's XML standards.

Both XmlReader and XmlWriter are abstract base classes, that define the functionality
that all derived classes must support.
Is it possible to use multipe inheritance in .net?
Multiple Inheritance is an ability to inherit from more than one base class in other words
ability of a class to have more than one superclass, by inheriting from different sources
and thus combine separately-defined behaviors in a single class. There are two types of
multiple inheritance: multiple type/interface inheritance and multiple implementation
inheritance. C# and VB.NET supports only multiple type/interface inheritance, in other
words
you can derive an class/interface from multiple interfaces. There is no support for
multiple implementation inheritance in .NET. That means a class can only derived from
one class.
What are the derived classes from xmlReader and xmlWriter?
Both XmlReader and XmlWriter are abstract base classes, that define the functionality
that all derived classes must support.
There are three concrete implementations of XmlReader:

63

1.

XmlTextReader

2.

XmlNodeReader

3.

XmlValidatingReader

There are two concrete implementations of XmlWriter:

1.

XmlTextWriter

2.

XmlNodeWriter

XmlTextReader and XmlTextWriter support reading data to/from text-based stream, while
XmlNodeReader and XmlNodeWriter are designed for working with in-memory DOM tree
structure. The custom readers and writers can also be developed to extend the built-in
functionality of XmlReader and XmlWriter.
What is managed and unmanaged code?
The .NET framework provides several core run-time services to the programs that run
within it, for example exception handling and security. For these services to work, the
code must provide a minimum level of information to the runtime. in other words., code
executing under the control of the CLR is called managed code. For example, any code
written in C# or Visual Basic .NET is managed code.
Code that runs outside the CLR is referred to as "unmanaged code." COM components,
ActiveX components, and Win32 API functions are examples of unmanaged code.
How you deploy .NET assemblies?
One way is simply use xcopy. others are use and the setup projects in .net. and one more
way is use of nontuch deployment.
What is Globalizationa and Localization ?
Globalization is the process of creating an application that meets the needs of users from
multiple cultures. It includes using the correct currency, date and time format, calendar,
writing direction, sorting rules, and other issues. Accommodating these cultural
differences in an application is called localization.Using classes of System.Globalization
namespace, you can set application's current culture.
This can be done by using any of the following 3 approaches.

1.

Detect and redirect

2.

Run-time adjustment

3.

Using Satellite assemblies.

Whate are Resource Files ? How are they used in .NET?


Resource files are the files containing data that is logically deployed with an
application.These files can contain data in a number of formats including strings, images
and persisted objects. It has the main advantage of If we store data in these files then we
don't need to compile these if the data get changed. In .NET we basically require them
storing culture specific informations by localizing application's resources. You can deploy
your resources using satellite assemblies.

64

Difference between Dispose and Finallize method?


Finalize method is used to free the memory used by some unmanaged resources like
window handles (HWND). It's similar to the destructor syntax in C#. The GC calls this
method when it founds no more references to the object. But, In some cases we may
need release the memory used by the resources explicitely.To release the memory
explicitly we need to implement the Dispose method of IDisposable interface.
What is encapsulation ?
Encapsulation is the ability to hide the internal workings of an object's behavior and its
data. For instance, let's say you have a object named Bike and this object has a method
named start(). When you create an instance of a Bike object and call its start() method
you are not worried about what happens to accomplish this, you just want to ensure the
state of the bike is changed to "running" afterwards. This kind of behavior hiding is
encapsulation and it makes programming much easier.
How can you prevent your class to be inherated further?
By setting Sealed - Key word
public sealed class Planet
{
//code goes here
}
class Moon : Planet
{
//Not allowed as base class is sealed
}
What is GUID and why we need to use it and in what condition? How this is
created.
A GUID is a 128-bit integer (16 bytes) that can be used across all computers and
networks wherever a unique identifier is required. Such an identifier has a very low
probability of being duplicated. Visual Studio .NET IDE has a utility under the tools menu
to generate GUIDs.
Why do you need to serialize.?
We need to serialize the object,if you want to pass object from one computer/application
domain to another.Process of converting complex objects into stream of bytes that can
be persisted or transported.Namespace for serialization is
System.Runtime.Serialization.The ISerializable interface allows you to make any class
Serializable..NET framework features 2 serializing method.
1. Binary Serialization 2. XML Serialization
What is inline schema, how does it works?
Schemas can be included inside of XML file is called Inline Schemas.This is useful when it
is inconvenient to physically seprate the schema and the XML document.A schema is an
XML document that defines the structure, constraints, data types, and relationships of
the elements that constitute the data contained inside the XML document or in another
XML document.Schema can be an external file that uses the XSD or XDR extension called
external schema. Inline schema can take place even when validation is turned off.
Describe the advantages of writing a managed code application instead of

65

unmanaged one. What's involved in certain piece of code being managed?


"Advantage includes automatic garbage collection,memory management,security,type
checking,versioning
Managed code is compiled for the .NET run-time environment. It runs in the Common
Language Runtime (CLR), which is the heart of the .NET Framework. The CLR provides
services such as security,
memory management, and cross-language integration. Managed applications written to
take advantage of the features of the CLR perform more efficiently and safely, and take
better advantage of developers existing expertise in languages that support the .NET
Framework.
Unmanaged code includes all code written before the .NET Framework was introduced
this includes code written to use COM, native Win32, and Visual Basic 6. Because it does
not run inside the .NET environment, unmanaged code cannot make use of any .NET
managed facilities."
What are multicast delegates ? give me an example ?
Delegate that can have more than one element in its invocation List.
using System;
namespace SampleMultiCastDelegate
{
class MultiCast
{
public delegate string strMultiCast(string s);
}
}
MainClass defines the static methods having same signature as delegate.
using System;
namespace SampleMultiCastDelegate
{
public class MainClass
{
public MainClass()
{
}
public static string Jump(string s)
{
Console.WriteLine("Jump");
return String.Empty;
}
public static string Run(string s)
{
Console.WriteLine("Run");
return String.Empty;
}
public static string Walk(string s)
{
Console.WriteLine("Walk");
return String.Empty;
}
}
}

66

The Main class:


using System;
using System.Threading;
namespace SampleMultiCastDelegate
{

public class MainMultiCastDelegate


{
public static void Main()
{
MultiCast.strMultiCast Run, Walk, Jump;
MultiCast.strMultiCast myDelegate;
///here mydelegate used the Combine method of System.MulticastDelegate
///and the delegates combine
myDelegate = (MultiCast.strMultiCast)System.Delegate.Combine(Run, Walk);
}
}

Can a nested object be used in Serialization ?


Yes. If a class that is to be serialized contains references to objects of other classes, and if
those classes have been marked as serializable, then their objects are serialized too.
Difference between int and int32 ?
Both are same. System.Int32 is a .NET class. Int is an alias name for System.Int32.
Describe the difference between a Thread and a Process?
A Process is an instance of an running application. And a thread is the Execution stream
of the Process. A process can have multiple Thread.
When a process starts a specific memory area is allocated to it. When there is multiple
thread in a process, each thread gets a memory for storing the variables in it and plus
they can access to the global variables that is common for all the thread. Eg.A Microsoft
Word is a Application. When you open a Word file,an instance of the Word starts and a
process is allocated to this instance that has one thread.
What is the difference between an EXE and a DLL?
You can create an objects of DLL but not of the EXE.
DLL is an In-Process Component whereas EXE is an OUt-Process Component.
Exe is for single use whereas you can use DLL for multiple use.
Exe can be started as standalone where DLL cannot be.
What is strong-typing versus weak-typing? Which is preferred? Why?
Strong typing implies that the types of variables involved in operations are associated to
the variable, checked at compile-time, and require explicit conversion; weak typing
implies that they are associated to the value, checked at run-time, and are implicitly
converted as required. (Which is preferred is a disputable point, but I personally prefer
strong typing because I like my errors to be found as soon as possible.)
What is a PID? How is it useful when troubleshooting a system?

67

PID is the process Id of the application in Windows. Whenever a process starts running in
the Windows environment, it is associated with an individual process Id or PID.
The PID (Process ID) a unique number for each item on the Process Tab, Image Name list.
How do you get the PID to appear? In Task Manger, select the View menu, then select
columns and check PID (Process Identifier).
In Linux, PID is used to debug a process explicitly. However we cannot do this in a
windows environment.
Microsoft has launched a SDK called as Microsoft Operations Management (MOM). This
uses the PID to determine which DLL's have been loaded by a process in the memory.
This is essentially helpful in situations where the Process that has a memory leak is to be
traced to a erring DLL. Personally I have never used a PID, our Windows debugger does
the things required to determine.
What is the GAC? What problem does it solve?
Each computer where the Common Language Runtime is installed has a machine-wide
code cache called the Global Assembly Cache. The Global Assembly Cache stores
assemblies that are to be shared by several applications on the computer. This area is
typically the folder under windows or winnt in the machine.
All the assemblies that need to be shared across applications need to be done through
the Global Assembly Cache only. However it is not necessary to install assemblies into
the Global Assembly Cache to make them accessible to COM interop or unmanaged code.
There are several ways to deploy an assembly into the Global Assembly Cache:

Use an installer designed to work with the Global Assembly Cache. This is the
preferred option for installing assemblies into the Global Assembly Cache.

Use a developer tool called the Global Assembly Cache tool (Gacutil.exe),
provided by the .NET Framework SDK.

Use Windows Explorer to drag assemblies into the cache.

GAC solves the problem of DLL Hell and DLL versioning. Unlike earlier situations, GAC can
hold two assemblies of the same name but different version. This ensures that the
applications that access a specific assembly continue to access the same assembly even
if another version of that assembly is installed on that machine.
Describe what an Interface is and how it's different from a Class.
An interface is a structure of code that is similar to a class. An interface is a prototype for
a class and is useful from a logical design perspective. Interfaces provide a means to
define the protocols for a class without worrying about the implementation details. The
syntax for creating interfaces follows:
interface Identifier {
InterfaceBody
}
Identifier is the name of the interface and InterfaceBody refers to the abstract methods
and static final variables that make up the interface. Because it is assumed that all the
methods in an interface are abstract, it isn't necessary to use the abstract keyword
An interface is a description of some of the members available from a class. In practice,
the syntax typically looks similar to a class definition, except that there's no code defined

68

for the methods just their name, the arguments passed and the type of the value
returned.
So what good is it? None by itself. But you create an interface so that classes will
implement it.
But what does it mean to implement an interface. The interface acts as a contract or
promise. If a class implements an interface, then it must have the properties and
methods of the interface defined in the class. This is enforced by the compiler.
Broadly the differentiators between classes and interfaces is as follows

Interface should not have any implementation.

Interface can not create any instance.

Interface should provide high level abstraction from the implementation.

Interface can have multiple inheritances.

Default access level of the interface is public.

What is the difference between XML Web Services using ASMX and .NET
Remoting using SOAP?
ASP.NET Web services and .NET Remoting provide a full suite of design options for crossprocess and cross-plaform communication in distributed applications. In general, ASP.NET
Web services provide the highest levels of interoperability with full support for WSDL and
SOAP over HTTP, while .NET Remoting is designed for Common Language Runtime typesystem fidelity and supports additional data format and communication channels. Hence
if we looking cross-platform communication than web services is the choice coz for .NET
remoting .Net framework is requried that may or may not present for the other platform.
Serialization and Metadata
ASP.NET Web services rely on the System.Xml.Serialization.XmlSerializer class to marshal
data to and from SOAP messages at runtime. For metadata, they generate WSDL and
XSD definitions that describe what their messages contain. The reliance on pure WSDL
and XSD makes ASP.NET Web services metadata portable; it expresses data structures in
a way that other Web service toolkits on various platforms and with various programming
models can understand. In some cases, this imposes constraints on the types you can
expose from a Web serviceXmlSerializer will only marshal things that can be expressed
in XSD. Specifically, XmlSerializer will not marshal object graphs and it has limited
support for container types.
.NET Remoting relies on the pluggable implementations of the IFormatter interface used
by the System.Runtime.Serialization engine to marshal data to and from messages.
There are two standard formatters,
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and
System.Runtime.Serialization.Formatters.Soap.SoapFormatter. The BinaryFormatter and
SoapFormatter, as the names suggest, marshal types in binary and SOAP format
respectively. For metadata, .NET Remoting relies on the Common Language Runtime
assemblies, that contain all the relevant information about the data types they
implement, and expose it via reflection. The reliance on the assemblies for metadata
makes it easy to preserve the full runtime type-system fidelity. As a result, when the .NET
Remoting plumbing marshals data, it includes all of a class's public and private members;
handles object graphs correctly; and supports all container types (for example,

69

System.Collections.Hashtable). However, the reliance on runtime metadata also limits


the reach of a .NET Remoting systema client has to understand .NET constructs in
order to communicate with a .NET Remoting endpoint. In addition to pluggable
formatters, the .NET Remoting layer supports pluggable channels, that abstract away the
details of how messages are sent. There are two standard channels, one for raw TCP and
one for HTTP. Messages can be sent over either channel independent of format.
Distributed Application Design: ASP.NET Web Services visual Studio. .NET
Remoting
ASP.NET Web services favor the XML Schema type system, and provide a simple
programming model with broad cross-platform reach. .NET Remoting favors the runtime
type system, and provides a more complex programming model with much more limited
reach. This essential difference is the primary factor in determining which technology to
use. However, there are a wide range of other design factors, including transport
protocols, host processes, security, performance, state management, and support for
transactions to consider as well.
Security
Since ASP.NET Web services rely on HTTP, they integrate with the standard Internet
security infrastructure. ASP.NET leverages the security features available with IIS to
provide strong support for standard HTTP authentication schemes including Basic, Digest,
digital certificates, and even Microsoft .NET Passport. (You can also use Windows
Integrated authentication, but only for clients in a trusted domain.) One advantage of
using the available HTTP authentication schemes is that no code change is required in a
Web service; IIS performs authentication before the ASP.NET Web services are called.
ASP.NET also provides support for .NET Passport-based authentication and other custom
authentication schemes. ASP.NET supports access control based on target URLs, and by
integrating with the .NET code access security (CAS) infrastructure. SSL can be used to
ensure private communication over the wire.
Although these standard transport-level techniques to secure Web services are quite
effective, they only go so far. In complex scenarios involving multiple Web services in
different trust domains, you need to build custom ad hoc solutions. Microsoft and others
are working on a set of security specifications that build on the extensibility of SOAP
messages to offer message-level security capabilities. One of these is the XML Web
Services Security Language (WS-Security), which defines a framework for message-level
credential transfer, message integrity, and message confidentiality.
As noted in the previous section, the .NET Remoting plumbing does not secure crossprocess invocations in the general case. A .NET Remoting endpoint hosted in IIS with
ASP.NET can leverage all the same security features available to ASP.NET Web services,
including support for secure communication over the wire using SSL. If you are using the
TCP channel or the HTTP channel hosted in processes other than aspnet_wp.exe, you
need to implement authentication, authorization and privacy mechanisms yourself.
One additional security concern is the ability to execute code from a semi-trusted
environment without having to change the default security policy. ASP.NET Web Services
client proxies work in these environments, but .NET Remoting proxies do not. In order to
use a .NET Remoting proxy from a semi-trusted environment, you need a special
serialization permission that is not given to code loaded from your intranet or the
Internet by default. If you want to use a .NET Remoting client from within a semi-trusted
environment, you have to alter the default security policy for code loaded from those
zones. In situations where you are connecting to systems from clients running in a
sandboxlike a downloaded Windows Forms application, for instanceASP.NET Web
Services are a simpler choice because security policy changes are not required.
Conceptually, what is the difference between early-binding and late-binding?

70

Early binding Binding at Compile Time


Late Binding Binding at Run Time
Early binding implies that the class of the called object is known at compile-time; latebinding implies that the class is not known until run-time, such as a call through an
interface or via Reflection.
Early binding is the preferred method. It is the best performer because your application
binds directly to the address of the function being called and there is no extra overhead
in doing a run-time lookup. In terms of overall execution speed, it is at least twice as fast
as late binding.
Early binding also provides type safety. When you have a reference set to the
component's type library, Visual Basic provides IntelliSense support to help you code
each function correctly. Visual Basic also warns you if the data type of a parameter or
return value is incorrect, saving a lot of time when writing and debugging code.
Late binding is still useful in situations where the exact interface of an object is not
known at design-time. If your application seeks to talk with multiple unknown servers or
needs to invoke functions by name (using the Visual Basic 6.0 CallByName function for
example) then you need to use late binding. Late binding is also useful to work around
compatibility problems between multiple versions of a component that has improperly
modified or adapted its interface between versions.
What is an Asssembly Qualified Name? Is it a filename? How is it different?
An assembly qualified name isn't the filename of the assembly; it's the internal name of
the assembly combined with the assembly version, culture, and public key, thus making
it unique.
for example (""System.Xml.XmlDocument, System.Xml, Version=1.0.3300.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"")
How is a strongly-named assembly different from one that isn't stronglynamed?
Strong names are used to enable the stricter naming requirements associated with
shared assemblies. These strong names are created by a .NET utility sn.exe
Strong names have three goals:

Name uniqueness. Shared assemblies must have names that are globally unique.

Prevent name spoofing. Developers don't want someone else releasing a


subsequent version of one of your assemblies and falsely claim it came from you,
either by accident or intentionally.

Provide identity on reference. When resolving a reference to an assembly, strong


names are used to guarantee the assembly that is loaded came from the
expected publisher.

Strong names are implemented using standard public key cryptography. In general, the
process works as follows: The author of an assembly generates a key pair (or uses an
existing one), signs the file containing the manifest with the private key, and makes the
public key available to callers. When references are made to the assembly, the caller
records the public key corresponding to the private key used to generate the strong
name.

71

Weak named assemblies are not suitable to be added in GAC and shared. It is essential
for an assembly to be strong named.
Strong naming prevents tampering and enables assemblies to be placed in the GAC
alongside other assemblies of the same name.
How does the generational garbage collector in the .NET CLR manage object
lifetime? What is non-deterministic finalization?
The hugely simplistic version is that every time it garbage-collects, it starts by assuming
everything to be garbage, then goes through and builds a list of everything reachable.
Those become not-garbage, everything else doesn't, and gets thrown away. What makes
it generational is that every time an object goes through this process and survives, it is
noted as being a member of an older generation (up to 2, right now). When the garbagecollector is trying to free memory, it starts with the lowest generation (0) and only works
up to higher ones if it can't free up enough space, on the grounds that shorter-lived
objects are more likely to have been freed than longer-lived ones.
Non-deterministic finalization implies that the destructor (if any) of an object will not
necessarily be run (nor its memory cleaned up, but that's a relatively minor issue)
immediately upon its going out of scope. Instead, it will wait until first the garbage
collector gets around to finding it, and then the finalisation queue empties down to it;
and if the process ends before this happens, it may not be finalised at all. (Although the
operating system will usually clean up any process-external resources left open, note the
usually there, especially as the exceptions tend to hurt a lot.)
What is the difference between Finalize() and Dispose()?
Dispose() is called by the user of an object to indicate that he is finished with it, enabling
that object to release any unmanaged resources it holds. Finalize() is called by the runtime to allow an object that has not had Dispose() called on it to do the same. However,
Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will
be called immediately when an object goes out of scope, or indeed at all, if the program
ends before that object is GCed, and as such Dispose() is generally preferred.
How is the using() pattern useful? What is IDisposable? How does it support
deterministic finalization?
The using() pattern is useful because it ensures that Dispose() will always be called when
a disposable object (defined as one that implements IDisposable, and thus the Dispose()
method) goes out of scope, even if it does so by an exception being thrown, and thus
that resources are always released.
What does this useful command line do? tasklist /m "mscor*"
Lists all the applications and associated tasks/process currently running on the system
with a module whose name begins "mscor" loaded into them; that in nearly all cases in
other words "all the .NET processes".
What's wrong with a line like this? DateTime.Parse(myString);
Therez nothing wrong with this declaration.Converts the specified string representation of
a date and time to its DateTime equivalent.But If the string is not a valid DateTime,It
throws an exception.
What are PDBs? Where must they be located for debugging to work?
A program database (PDB) files holds debugging and project state information that allows
incremental linking of debug configuration of your program.There are several different
types of symbolic debugging information. The default type for Microsoft compiler is the

72

so-called PDB file. The compiler setting for creating this file is /Zi, or /ZI for C/C++(that
creates a PDB file with additional information that enables a feature called ""Edit and
Continue"") or a Visual Basic/C#/JScript .NET program with /debug.
A PDB file is a separate file, placed by default in the Debug project subdirectory, that has
the same name as the executable file with the extension .pdb. Note that the Visual C++
compiler by default creates an additional PDB file called VC60.pdb for VisulaC++6.0 and
VC70.PDB file for VisulaC++7.0. The compiler creates this file during compilation of the
source code, when the compiler isn't aware of the final name of the executable. The
linker can merge this temporary PDB file into the main one if you tell it to, but it won't do
it by default. The PDB file can be useful to display the detailed stack trace with source
files and line numbers.
What is FullTrust? Do GAC'ed assemblies have FullTrust?
Before the .NET Framework existed, Windows had two levels of trust for downloaded
code. This old model was a binary trust model. You only had two choices: Full Trust, and
No Trust. The code could either do anything you could do, or it wouldn't run at all.
The permission sets in .NET include FullTrust, SkipVerification, Execution, Nothing,
LocalIntranet, Internet and Everything. Full Trust Grants unrestricted permissions to
system resources. Fully trusted code run by a normal, nonprivileged user cannot do
administrative tasks, but can access any resources the user can access, and do anything
the user can do. From a security standpoint, you can think of fully trusted code as being
similar to native, unmanaged code, like a traditional ActiveX control.
GAC assemblies are granted FullTrust. In v1.0 and 1.1, the fact that assemblies in the
GAC seem to always get a FullTrust grant is actually a side effect of the fact that the GAC
lives on the local machine. If anyone were to lock down the security policy by changing
the grant set of the local machine to something less than FullTrust, and if your assembly
did not get extra permission from some other code group, it would no longer have
FullTrust even though it lives in the GAC.
What does this do? gacutil /l | find /i "Corillian"
The Global Assembly Cache tool allows you to view and manipulate the contents of the
Global Assembly Cache and download cache.The tool comes with various optional
params to do that.
""/l"" option Lists the contents of the Global Assembly Cache. If you specify the
assemblyName parameter(/l [assemblyName]), the tool lists only the assemblies
matching that name.
What does this do .. sn -t foo.dll ?
Sn -t option displays the token for the public key stored in infile. The contents of infile
must be previously generated using -p.
Sn.exe computes the token using a hash function from the public key. To save space, the
Common Language Runtime stores public key tokens in the manifest as part of a
reference to another assembly when it records a dependency to an assembly that has a
strong name. The -tp option displays the public key in addition to the token.
How do you generate a strong name?
.NET provides an utility called strong name tool. You can run this toolfrom the VS.NET
command prompt to generate a strong name with an option "-k" and providing the strong
key file name. in other words sn- -k < file-name >
What is the difference between a Debug and Release build? Is there a

73

significant speed difference? Why or why not?


The Debug build is the program compiled with full symbolic debug information and no
optimization. The Release build is the program compiled employing optimization and
contains no symbolic debug information. These settings can be changed as per need
from Project Configuration properties. The release runs faster since it does not have any
debug symbols and is optimized.
Explain the use of virtual, sealed, override, and abstract.
Abstract: The keyword can be applied for a class or method.
1. Class: If we use abstract keyword for a class it makes the class an abstract class,
which means it cant be instantiated. Though it is not necessary to make all the method
within the abstract class to be virtual. ie, Abstract class can have concrete methods
2. Method: If we make a method as abstract, we don't need to provide implementation
of the method in the class but the derived class need to implement/override this method.
Sealed: It can be applied on a class and methods. It stops the type from further
derivation in other words no one can derive class from a sealed class, ie A sealed class
cannot be inherited. A sealed class cannot be a abstract class. A compile time error is
thrown if you try to specify sealed class as a base class. When an instance method
declaration includes a sealed modifier, that method is said to be a sealed method. If an
instance method declaration includes the sealed modifier, it must also include the
override modifier. Use of the sealed modifier prevents a derived class from further
overriding the method For Egs: sealed override public void Sample()
{ Console.WriteLine("Sealed Method"); }
Virtual and Override: Virtual and Override keywords provides runtime polymorphism. A
base class can make some of its methods as virtual that allows the derived class a
chance to override the base class implementation by using override keyword.
For example:
class Shape
{
int a
public virtual void Display()
{
Console.WriteLine("Shape");
}
}
class Rectangle:Shape
{
public override void Display()
{
Console.WriteLine("Derived");
}
}
Explain the importance and use of each, Version, Culture and PublicKeyToken
for an assembly.
This three alongwith name of the assembly provide a strong name or fully qualified name
to the assembly. When a assebly is referenced with all three.
PublicKeyToken: Each assembly can have a public key embedded in its manifest that
identifies the developer. This ensures that once the assembly ships, no one can modify
the code or other resources contained in the assembly.

74

Culture: Specifies which culture the assembly supports


Version: The version number of the assembly.It is of the following form
major.minor.build.revision.
Explain the differences between public, protected, private and internal.
These all are access modifier and they governs the access level. They can be applied to
class, methods, fields.
Public: Allows class, methods, fields to be accessible from anywhere in other words within
and outside an assembly.
Private: When applied to field and method allows to be accessible within a class.
Protected: Similar to private but can be accessed by members of derived class also.
Internal: They are public within the assembly in other words they can be accessed by
anyone within an assembly but outside assembly they are not visible.
What is the difference between typeof(foo) and myFoo.GetType()?
Typeof is operator that applied to a object returns System.Type object. Typeof cannot be
overloaded white GetType has lot of overloads.GetType is a method that also returns
System.Type of an object. GetType is used to get the runtime type of the object.
Example from MSDN showing Gettype used to retrive type at untime:
public class MyBaseClass : Object
{
}
public class MyDerivedClass : MyBaseClass
{
}
public class Test
{
public static void Main()
{
MyBaseClass myBase = new MyBaseClass();
MyDerivedClass myDerived = new MyDerivedClass();
object o = myDerived;
MyBaseClass b = myDerived;
Console.WriteLine("mybase: Type is {0}", myBase.GetType());
Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
}
}
/*
This code produces the following output.
mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass
*/
Can "this" be used within a static method?

75

No "This" cannot be used in a static method. As only static variables/methods can be


used in a static method.
What is the purpose of XML Namespaces?
An XML Namespace is a collection of element types and attribute names. It consists of 2
parts

1.

The first part is the URI used to identify the namespace

2.

The second part is the element type or attribute name itself.

Together they form a unique name. The various purpose of XML Namespace are

<
<
<
<
<
<
<
<
<
<
<
<
<
<

1.

Combine fragments from various documents without any naming conflicts. (See
example below.)

2.

Write reusable code modules that can be invoked for specific elements and
attributes. Universally unique names guarantee that such modules are invoked
only for the correct elements and attributes.

3.

Define elements and attributes that can be reused in other schemas or instance
documents without fear of name collisions. For example, you might use XHTML
elements in a parts catalog to provide part descriptions. Or you might use the nil
attribute defined in XML Schemas to indicate a missing value.

Department >
Name >DVS1< /Name >
addr:Address xmlns:addr="http://www.tu-darmstadt.de/ito/addresses" >
addr:Street >Wilhelminenstr. 7< /addr:Street >
addr:City >Darmstadt< /addr:City >
addr:State >Hessen< /addr:State >
addr:Country >Germany< /addr:Country >
addr:PostalCode >D-64285< /addr:PostalCode >
/addr:Address >
serv:Server xmlns:serv="http://www.tu-darmstadt.de/ito/servers" >
serv:Name >OurWebServer< /serv:Name >
serv:Address >123.45.67.8< /serv:Address >
/serv:Server >
/Department >

What is difference between MetaData and Manifest ?


Metadata and Manifest forms an integral part of an assembly( DLL / exe ) in .net
framework.
Out of which Metadata is a mandatory component , which as the name suggests gives
the details about various components of IL code viz: Methods , properties , fields , class
and so on.
Essentially Metadata maintains details in form of tables like Methods Metadata tables ,
Properties Metadata tables , that maintains the list of given type and other details like
access specifier , return type and so on.
Now Manifest is a part of metadata only , fully called as "manifest metadata tables" , it
contains the details of the references needed by the assembly of any other external

76

assembly / type , it could be a custom assembly or standard System namespace.


Now for an assembly that can independently exists and used in the .Net world both the
things ( Metadata with Manifest ) are mandatory , so that it can be fully described
assembly and can be ported anywhere without any system dependency . Essentially .Net
framework can read all assembly related information from assembly itself at runtime.
But for .Net modules , that can't be used independently , until they are being packaged
as a part of an assembly , they don't contain Manifest but their complete structure is
defined by their respective metadata.
Ultimately . .Net modules use Manifest Metadata tables of parent assembly that contain
them.
What is the use of Internal keyword?
Internal keyword is one of the access specifier available in .Net framework , that makes a
type visible in a given assembly , for e.g: a single DLL can contain multiple modules ,
essentially a multi file assembly , but it forms a single binary component , so any type
with internal keyword will be visible throughout the assembly and can be used in any of
the modules.
What actually happes when you add a something to arraylistcollection ?
Following things will happen:
Arraylist is a dynamic array class in C# in System.Collections namespace derived from
interfaces ICollection , IList , ICloneable , IConvertible . It terms of in memory structure
following is the implementation.

1.

Check up the total space if there's any free space on the declared list.

2.

If yes add the new item and increase count by 1 .

3.

If No Copy the entire thing to a temporary Array of Last Max. Size.

4.

Create new Array with size ( Last Array Size + Increase Value )

5.

Copy back values from temp and reference this new array as original array.

6.

Must doing Method updates too , need to check it up.

What is Boxing and unboxing? Does it occure automaatically or you need to


write code to box and unbox?
Boxing - Process of converting a System.ValueType to Reference Type , Mostly base class
System.Object type and allocating it memory on Heap .Reverse is unboxing , but can only
be done with prior boxed variables.
Boxing is always implicit but Unboxing needs to be explicitly done via casting , thus
ensuring the value type contained inside.
How Boxing and unboxing occures in memory?
Boxing converts value type to reference type , thus allocating memory on Heap.
Unboxing converts already boxed reference types to value types through explicit casting ,
thus allocating memory on stack.

77

Why only boxed types can be unboxed?


Unboxing is the process of converting a Reference type variable to Value type and thus
allocating memory on the stack . It happens only to those Reference type variables that
have been earlier created by Boxing of a Value Type , therefore internally they contain a
value type , that can be obtained through explicit casting . For any other Reference type ,
they don't internally contain a Value type to Unboxed via explicit casting . This is why
only boxed types can be unboxed.
Com +
What are various transaction options available for services components ?
There are 5 transactions types that can be used with COM+. Whenever an object is
registered with COM+ it has to abide either to these 5 transaction types.
Disabled: There is no transaction. COM+ does not provide transaction support for this
component.
Not Supported: Component does not support transactions. Hence even if the calling
component in the hierarchy is transaction enabled this component will not participate in
the transaction.
Supported: Components with transaction type supported will be a part of the transaction
if the calling component has an active transaction.
If the calling component is not transaction enabled this component will not start a new
transaction.
Required: Components with this attribute require a transaction in other words either the
calling should have a transaction in place else this component will start a new
transaction.
Required New: Components enabled with this transaction type always require a new
transaction. Components with required new transaction type instantiate a new
transaction for themselves every time.
Can we use com Components in .net?.How ?.can we use .net components in
vb?.Explain how ?
COM components have different internal architecture from .NET components hence they
are not innately compatible. However .NET framework supports invocation of unmanaged
code from managed code (and vice-versa) through COM/.NET interoperability. .NET
application communicates with a COM component through a managed wrapper of the
component called Runtime Callable Wrapper (RCW); it acts as managed proxy to the
unmanaged COM component. When a method call is made to COM object, it goes onto
RCW and not the object itself. RCW manages the lifetime management of the COM
component. Implementation Steps Create Runtime Callable Wrapper out of COM component. Reference the metadata
assembly DLL in the project and use its methods and properties RCW can be created
using Type Library Importer utility or through VS.NET. Using VS.NET, add reference
through COM tab to select the desired DLL. VS.NET automatically generates metadata
assembly putting the classes provided by that component into a namespace with the
same name as COM DLL (XYZRCW.dll)
.NET components can be invoked by unmanaged code through COM Callable Wrapper
(CCW) in COM/.NET interop. The unmanaged code will talk to this proxy, that translates
call to managed environment. We can use COM components in .NET through COM/.NET
interoperability. When managed code calls an unmanaged component, behind the
scene, .NET creates proxy called COM Callable wrapper (CCW), that accepts commands
from a COM client, and forwards it to .NET component. There are two prerequisites to
creating .NET component, to be used in unmanaged code:

78

1.

.NET class should be implement its functionality through interface. First define
interface in code, then have the class to imlpement it. This way, it prevents
breaking of COM client, if/when .NET component changes.

2.

Secondly, .NET class, that is to be visible to COM clients must be declared public.
The tools that create the CCW only define types based on public classes. The
same rule applies to methods, properties, and events that will be used by COM
clients.

Implementation Steps -

1.

Generate type library of .NET component, using TLBExporter utility. A type library
is the COM equivalent of the metadata contained within
a .NET assembly. Type libraries are generally contained in files with the
extension .tlb. A type library contains the necessary information to allow a COM
client to determine which classes are located in a specific server, as well as the
methods, properties, and events supported by those classes.

2.

Secondly, use Assembly Registration tool (regasm) to create the type library and
register it.

3.

Lastly install .NET assembly in GAC, so it is available as shared assembly.

What is Runtime Callable wrapper?.when it will created?.


The Common Language Runtime exposes COM objects through a proxy called the
runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object
to .NET clients, its primary function is to marshal calls between a .NET client and a COM
object. This wrapper turns the COM interfaces exposed by the COM component into .NETcompatible interfaces. For oleautomation (attribute indicates that an interface is
compatible with Automation) interfaces, the RCW can be generated automatically from a
type library. For non-oleautomation interfaces, it may be necessary to develop a custom
RCW that manually maps the types exposed by the COM interface to .NET-compatible
types.
What is Com Callable wrapper?when it will created?
.NET components are accessed from COM via a COM Callable Wrapper (CCW). This is
similar to a RCW, but works in the opposite direction. Again, if the wrapper cannot be
automatically generated by the .NET development tools, or if the automatic behaviour is
not desirable, a custom CCW can be developed. Also, for COM to "see" the .NET
component, the .NET component must be registered in the registry.CCWs also manage
the object identity and object lifetime of the managed objects they wrap.
What is a primary interop ?
A primary interop assembly is a collection of types that are deployed, versioned, and
configured as a single unit. However, unlike other managed assemblies, an interop
assembly contains type definitions (not implementation) of types that have already been
defined in COM. These type definitions allow managed applications to bind to the COM
types at compile time and provide information to the Common Language Runtime
about how the types should be marshaled at run time.
What are tlbimp and tlbexp tools used for ?

79

The Type Library Exporter generates a type library that describes the types defined in a
Common Language Runtime assembly.
The Type Library Importer converts the type definitions found within a COM type library
into equivalent definitions in a Common Language Runtime assembly. The output of
Tlbimp.exe is a binary file (an assembly) that contains runtime metadata for the types
defined within the original type library.
What benefit do you get from using a Primary Interop Assembly (PIA)?
PIAs are important because they provide unique type identity. The PIA distinguishes the
official type definitions from counterfeit definitions provided by other interop assemblies.
Having a single type identity ensures type compatibility among applications that share
the types defined in the PIA. Because the PIA is signed by its publisher and labeled with
the PrimaryInteropAssembly attribute, it can be differentiated from other interop
assemblies that define the same types.
ADO.NET
Explain what a diffgram is and its usage ?
A DiffGram is an XML format that is used to identify current and original versions of data
elements. The DataSet uses the DiffGram format to load and persist its contents, and to
serialize its contents for transport across a network connection. When a DataSet is
written as a DiffGram, it populates the DiffGram with all the necessary information to
accurately recreate the contents, though not the schema, of the DataSet, including
column values from both the Original and Current row versions, row error information,
and row order.
When sending and retrieving a DataSet from an XML Web service, the DiffGram format is
implicitly used. Additionally, when loading the contents of a DataSet from XML using the
ReadXml method, or when writing the contents of a DataSet in XML using the WriteXml
method, you can select that the contents be read or written as a DiffGram.
The DiffGram format is divided into three sections: the current data, the original (or
"before") data, and an errors section, as shown in the following example.
<?xml version="1.0"?>
<diffgr:diffgram
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DataInstance>
</DataInstance>
<diffgr:before>
</diffgr:before>
<diffgr:errors>
</diffgr:errors>
</diffgr:diffgram>
The DiffGram format consists of the following blocks of data:
<DataInstance>
The name of this element, DataInstance, is used for explanation purposes in this
documentation. A DataInstance element represents a DataSet or a row of a DataTable.
Instead of DataInstance, the element would contain the name of the DataSet or
DataTable. This block of the DiffGram format contains the current data, whether it has
been modified or not. An element, or row, that has been modified is identified with the

80

diffgr:hasChanges annotation.
<diffgr:before>
This block of the DiffGram format contains the original version of a row. Elements in this
block are matched to elements in the DataInstance block using the diffgr:id annotation.
<diffgr:errors>
This block of the DiffGram format contains error information for a specific row in the
DataInstance block. Elements in this block are matched to elements in the DataInstance
block using the diffgr:id annotation.
Which method do you invoke on the DataAdapter control to load your
generated dataset with data?
You must use the Fill method of the DataAdapter control and pass the dataset object as
an argument to load the generated data.
Can you edit data in the Repeater control?
NO.
Which are the various IsolationLevels ?
Following are the various IsolationLevels:

Serialized Data read by a current transaction cannot be changed by another


transaction until the current transaction finishes. No new data can be inserted
that would affect the current transaction. This is the safest isolation level and is
the default.

Repeatable Read Data read by a current transaction cannot be changed by


another transaction until the current transaction finishes. Any type of new data
can be inserted during a transaction.

Read Committed A transaction cannot read data that is being modified by another
transaction that has not committed. This is the default isolation level in
Microsoft SQL Server.

Read Uncommitted A transaction can read any data, even if it is being modified by
another transaction. This is the least safe isolation level but allows the highest
concurrency.

Any Any isolation level is supported. This setting is most commonly used by
downstream components to avoid conflicts. This setting is useful because any
downstream component must be configured with an isolation level that is equal to
or less than the isolation level of its immediate upstream component. Therefore, a
downstream component that has its isolation level configured as Any always uses
the same isolation level that its immediate upstream component uses. If the root
object in a transaction has its isolation level configured to Any, its isolation level
becomes Serialized.

How XML files and be read and write using dataset?.


DataSet exposes method like ReadXml and WriteXml to read and write XML
What are the various rowversions available?

81

There are four types of Rowversions.


Current
The current values for the row. This row version does not exist for rows with a RowState
of Deleted.
Default
The row the default version for the current DataRowState. For a DataRowState value of
Added, Modified or Current, the default version is Current. For a DataRowState of
Deleted, the version is Original. For a DataRowState value of Detached, the version is
Proposed.
Original
The row contains its original values.
Proposed
The proposed values for the row. This row version exists during an edit operation on a
row, or for a row that is not part of a DataRowCollection
Explain acid properties?.
The term ACID conveys the role transactions play in mission-critical applications. Coined
by transaction processing pioneers, ACID stands for atomicity, consistency, isolation, and
durability.
These properties ensure predictable behavior, reinforcing the role of transactions as allor-none propositions designed to reduce the management load when there are many
variables.
Atomicity
A transaction is a unit of work in which a series of operations occur between the BEGIN
TRANSACTION and END TRANSACTION statements of an application. A transaction
executes exactly once and is atomic all the work is done or none of it is.
Operations associated with a transaction usually share a common intent and are
interdependent. By performing only a subset of these operations, the system could
compromise the overall intent of the transaction. Atomicity eliminates the chance of
processing a subset of operations.
Consistency
A transaction is a unit of integrity because it preserves the consistency of data,
transforming one consistent state of data into another consistent state of data.
Consistency requires that data bound by a transaction be semantically preserved. Some
of the responsibility for maintaining consistency falls to the application developer who
must ensure that all known integrity constraints are enforced by the application. For
example, in developing an application that transfers money, you should avoid arbitrarily
moving decimal points during the transfer.
Isolation
A transaction is a unit of isolation, allowing concurrent transactions to behave as though
each were the only transaction running in the system.
Isolation requires that each transaction appear to be the only transaction manipulating

82

the data store, even though other transactions may be running at the same time. A
transaction should never see the intermediate stages of another transaction.
Transactions attain the highest level of isolation when they are serializable. At this level,
the results obtained from a set of concurrent transactions are identical to the results
obtained by running each transaction serially. Because a high degree of isolation can
limit the number of concurrent transactions, some applications reduce the isolation level
in exchange for better throughput.
Durability
A transaction is also a unit of recovery. If a transaction succeeds, the system guarantees
that its updates will persist, even if the computer crashes immediately after the commit.
Specialized logging allows the system's restart procedure to complete unfinished
operations, making the transaction durable.
Whate are various types of Commands available with DataAdapter ?
The SqlDataAdapter has SelectCommand, InsertCommand, DeleteCommand and
UpdateCommand
What is a Dataset?
Datasets are the result of bringing together ADO and XML. A dataset contains one or
more data of tabular XML, known as DataTables, these data can be treated separately, or
can have relationships defined among them. Indeed these relationships give you ADO
data SHAPING without needing to master the SHAPE language, that many people are not
comfortable with.
The dataset is a disconnected in-memory cache database. The dataset object model
looks like this:
Dataset
DataTableCollection
DataTable
DataView
DataRowCollection
DataRow
DataColumnCollection
DataColumn
ChildRelations
ParentRelations
Constraints
PrimaryKey
DataRelationCollection
Let's have a look at each of these:
DataTableCollection: As we say that a DataSet is an in-memory database. So it has this
collection, that holds data from multiple tables in a single DataSet object.
DataTable: In the DataTableCollection, we have DataTable objects, that represents the
individual tables of the dataset.
DataView: The way we have views in database, same way we can have DataViews. We
can use these DataViews to do Sort, filter data.
DataRowCollection: Similar to DataTableCollection, to represent each row in each Table
we have DataRowCollection.
DataRow: To represent each and every row of the DataRowCollection, we have
DataRows.

83

DataColumnCollection: Similar to DataTableCollection, to represent each column in


each Table we have DataColumnCollection.
DataColumn: To represent each and every Column of the DataColumnCollection, we
have DataColumn.
PrimaryKey: Dataset defines Primary key for the table and the primary key validation
will take place without going to the database.
Constraints: We can define various constraints on the Tables, and can use
Dataset.Tables(0).enforceConstraints. This will execute all the constraints, whenever we
enter data in DataTable.
DataRelationCollection: as we know that we can have more than 1 table in the
dataset, we can also define relationship among these tables using this collection and
maintain a parent-child relationship.
Explain the ADO . Net Architecture ( .Net Data Provider)
ADO.Net is the data access model for .Net based applications. It can be used to access
relational database systems such as SQL Server 2000, Oracle, and many other data
sources for which there is an OLD DB or ODBC provider. To a certain extent, ADO.NET
represents the latest evolution of ADO technology. However, ADO.NET introduces some
major changes and innovations that are aimed at the loosely coupled and inherently
disconnected nature of web applications.
A .Net Framework data provider is used to connecting to a database, executing
commands, and retrieving results. Those results are either processed directly, or placed
in an ADO.NET DataSet in order to be exposed to the user in an ad-hoc manner,
combined with data from multiple sources, or remoted between tiers. The .NET
Framework data provider is designed to be lightweight, creating a minimal layer between
the data source and your code, increasing performance without sacrificing functionality.
Following are the 4 core objects of .Net Framework Data provider:

Connection: Establishes a connection to a specific data source

Command: Executes a command against a data source. Exposes Parameters and


can execute within the scope of a Transaction from a Connection.

DataReader: Reads a forward-only, read-only stream of data from a data source.

DataAdapter: Populates a DataSet and resolves updates with the data source.

The .NET Framework includes the .NET Framework Data Provider for SQL Server (for
Microsoft SQL Server version 7.0 or later), the .NET Framework Data Provider for OLE DB,
and the .NET Framework Data Provider for ODBC.
The .NET Framework Data Provider for SQL Server: The .NET Framework Data Provider for
SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and
performs well because it is optimized to access a SQL Server directly without adding an
OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts
the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider
for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB
data source through both the OLE DB Service component, that provides connection
pooling and transaction services, and the OLE DB Provider for the data source
The .NET Framework Data Provider for OLE DB: The .NET Framework Data Provider for
OLE DB uses native OLE DB through COM interoperability to enable data access. The
.NET Framework Data Provider for OLE DB supports both local and distributed

84

transactions. For distributed transactions, the .NET Framework Data Provider for OLE DB,
by default, automatically enlists in a transaction and obtains transaction details from
Windows 2000 Component Services.
The .NET Framework Data Provider for ODBC: The .NET Framework Data Provider for
ODBC uses native ODBC Driver Manager (DM) through COM interoperability to enable
data access. The ODBC data provider supports both local and distributed transactions.
For distributed transactions, the ODBC data provider, by default, automatically enlists in
a transaction and obtains transaction details from Windows 2000 Component Services.
The .NET Framework Data Provider for Oracle: The .NET Framework Data Provider for
Oracle enables data access to Oracle data sources through Oracle client connectivity
software. The data provider supports Oracle client software version 8.1.7 and later. The
data provider supports both local and distributed transactions (the data provider
automatically enlists in existing distributed transactions, but does not currently support
the EnlistDistributedTransaction method).
The .NET Framework Data Provider for Oracle requires that Oracle client software (version
8.1.7 or later) be installed on the system before you can use it to connect to an Oracle
data source.
.NET Framework Data Provider for Oracle classes are located in the
System.Data.OracleClient namespace and are contained in the
System.Data.OracleClient.dll assembly. You will need to reference both the
System.Data.dll and the System.Data.OracleClient.dll when compiling an application that
uses the data provider.
Choosing a .NET Framework Data Provider
.NET Framework Data Provider for SQL Server: Recommended for middle-tier applications
using Microsoft SQL Server 7.0 or later. Recommended for single-tier applications using
Microsoft Data Engine (MSDE) or Microsoft SQL Server 7.0 or later.
Recommended over use of the OLE DB Provider for SQL Server (SQLOLEDB) with the .NET
Framework Data Provider for OLE DB. For Microsoft SQL Server version 6.5 and earlier,
you must use the OLE DB Provider for SQL Server with the .NET Framework Data Provider
for OLE DB.
.NET Framework Data Provider for OLE DB: Recommended for middle-tier applications
using Microsoft SQL Server 6.5 or earlier, or any OLE DB provider. For Microsoft SQL
Server 7.0 or later, the .NET Framework Data Provider for SQL Server is recommended.
Recommended for single-tier applications using Microsoft Access databases. Use of a
Microsoft Access database for a middle-tier application is not recommended.
.NET Framework Data Provider for ODBC: Recommended for middle-tier applications
using ODBC data sources. Recommended for single-tier applications using ODBC data
sources.
.NET Framework Data Provider for Oracle: Recommended for middle-tier applications
using Oracle data sources. Recommended for single-tier applications using Oracle data
sources. Supports Oracle client software version 8.1.7 and later. The .NET Framework
Data Provider for Oracle classes are located in the System.Data.OracleClient namespace
and are contained in the System.Data.OracleClient.dll assembly. You need to reference
both the System.Data.dll and the System.Data.OracleClient.dll when compiling an
application that uses the data provider.
Can you explain the difference between an ADO.NET Dataset and an ADO
Recordset?
Let's have a look at the differences between ADO Recordset and ADO.Net DataSet:

85

1.

Table Collection: ADO Recordset provides the ability to navigate through a single
table of information. That table would have been formed with a join of multiple
tables and returning columns from multiple tables. ADO.NET DataSet is capable of
holding instances of multiple tables. It has got a Table Collection, that holds
multiple tables in it. If the tables are having a relation, then it can be manipulated
on a Parent-Child relationship. It has the ability to support multiple tables with
keys, constraints and interconnected relationships. With this ability the DataSet
can be considered as a small, in-memory relational database cache.

2.

Navigation: Navigation in ADO Recordset is based on the cursor mode. Even


though it is specified to be a client-side Recordset, still the navigation pointer will
move from one location to another on cursor model only. ADO.NET DataSet is an
entirely offline, in-memory, and cache of data. All of its data is available all the
time. At any time, we can retrieve any row or column, constraints or relation
simply by accessing it either ordinarily or by retrieving it from a name-based
collection.

3.

Connectivity Model: The ADO Recordset was originally designed without the
ability to operate in a disconnected environment. ADO.NET DataSet is specifically
designed to be a disconnected in-memory database. ADO.NET DataSet follows a
pure disconnected connectivity model and this gives it much more scalability and
versatility in the amount of things it can do and how easily it can do that.

4.

Marshalling and Serialization: In COM, through Marshalling, we can pass data


from 1 COM component to another component at any time. Marshalling involves
copying and processing data so that a complex type can appear to the receiving
component the same as it appeared to the sending component. Marshalling is an
expensive operation. ADO.NET Dataset and DataTable components support
Remoting in the form of XML serialization. Rather than doing expensive
Marshalling, it uses XML and sent data across boundaries.

5.

Firewalls and DCOM and Remoting: Those who have worked with DCOM know
that how difficult it is to marshal a DCOM component across a router. People
generally came up with workarounds to solve this issue. ADO.NET DataSet uses
Remoting, through which a DataSet / DataTable component can be serialized into
XML, sent across the wire to a new AppDomain, and then Desterilized back to a
fully functional DataSet. As the DataSet is completely disconnected, and it has no
dependency, we lose absolutely nothing by serializing and transferring it through
Remoting.

How do you handle data concurrency in .NET ?


One of the key features of the ADO.NET DataSet is that it can be a self-contained and
disconnected data store. It can contain the schema and data from several rowsets in
DataTable objects as well as information about how to relate the DataTable objects-all in
memory. The DataSet neither knows nor cares where the data came from, nor does it
need a link to an underlying data source. Because it is data source agnostic you can pass
the DataSet around networks or even serialize it to XML and pass it across the Internet
without losing any of its features. However, in a disconnected model, concurrency
obviously becomes a much bigger problem than it is in a connected model.
In this column, I'll explore how ADO.NET is equipped to detect and handle concurrency
violations. I'll begin by discussing scenarios in which concurrency violations can occur
using the ADO.NET disconnected model. Then I will walk through an ASP.NET application
that handles concurrency violations by giving the user the choice to overwrite the
changes or to refresh the out-of-sync data and begin editing again. Because part of
managing an optimistic concurrency model can involve keeping a timestamp
(rowversion) or another type of flag that indicates when a row was last updated, I will

86

show how to implement this type of flag and how to maintain its value after each
database update.
Is Your Glass Half Full?
There are three common techniques for managing what happens when users try to
modify the same data at the same time: pessimistic, optimistic, and last-in wins. They
each handle concurrency issues differently.
The pessimistic approach says: "Nobody can cause a concurrency violation with my data
if I do not let them get at the data while I have it." This tactic prevents concurrency in the
first place but it limits scalability because it prevents all concurrent access. Pessimistic
concurrency generally locks a row from the time it is retrieved until the time updates are
flushed to the database. Since this requires a connection to remain open during the
entire process, pessimistic concurrency cannot successfully be implemented in a
disconnected model like the ADO.NET DataSet, that opens a connection only long enough
to populate the DataSet then releases and closes, so a database lock cannot be held.
Another technique for dealing with concurrency is the last-in wins approach. This model
is pretty straightforward and easy to implement-whatever data modification was made
last is what gets written to the database. To implement this technique you only need to
put the primary key fields of the row in the UPDATE statement's WHERE clause. No
matter what is changed, the UPDATE statement will overwrite the changes with its own
changes since all it is looking for is the row that matches the primary key values. Unlike
the pessimistic model, the last-in wins approach allows users to read the data while it is
being edited on screen. However, problems can occur when users try to modify the same
data at the same time because users can overwrite each other's changes without being
notified of the collision. The last-in wins approach does not detect or notify the user of
violations because it does not care. However the optimistic technique does detect
violations. Contd....
In optimistic concurrency models, a row is only locked during the update to the database.
Therefore the data can be retrieved and updated by other users at any time other than
during the actual row update operation. Optimistic concurrency allows the data to be
read simultaneously by multiple users and blocks other users less often than its
pessimistic counterpart, making it a good choice for ADO.NET. In optimistic models, it is
important to implement some type of concurrency violation detection that will catch any
additional attempt to modify records that have already been modified but not committed.
You can write your code to handle the violation by always rejecting and canceling the
change request or by overwriting the request based on some business rules. Another way
to handle the concurrency violation is to let the user decide what to do. The sample
application that is shown in Figure 1 illustrates some of the options that can be presented
to the user in the event of a concurrency violation.
Where Did My Changes Go?
When users are likely to overwrite each other's changes, control mechanisms should be
put in place. Otherwise, changes could be lost. If the technique you're using is the last-in
wins approach, then these types of overwrites are entirely possible.For example, imagine
Julie wants to edit an employee's last name to correct the spelling. She navigates to a
screen that loads the employee's information into a DataSet and has it presented to her
in a Web page. Meanwhile, Scott is notified that the same employee's phone extension
has changed. While Julie is correcting the employee's last name, Scott begins to correct
his extension. Julie saves her changes first and then Scott saves his.Assuming that the
application uses the last-in wins approach and updates the row using a SQL WHERE
clause containing only the primary key's value, and assuming a change to one column
requires the entire row to be updated, neither Julie nor Scott may immediatelyrealize the
concurrency issue that just occurred. In this specific situation, Julie's changes were
overwritten by Scott's changes because he saved last, and the last name reverted to the
misspelled version.

87

So as you can see, even though the users changed various fields, their changes collided
and caused Julie's changes to be lost. Without some sort of concurrency detection and
handling, these types of overwrites can occur and even go unnoticed.When you run the
sample application included in this column's download, you should open two separate
instances of Microsoft Internet Explorer. When I generated the conflict, I opened two
instances to simulate two users with two separate sessions so that a concurrency
violation would occur in the sample application. When you do this, be careful not to use
Ctrl+N because if you open one instance and then use the Ctrl+N technique to open
another instance, both windows will share the same session.
Detecting Violations
The concurrency violation reported to the user in Figure 1 demonstrates what can happen
when multiple users edit the same data at the same time. In Figure 1, the user attempted
to modify the first name to "Joe" but since someone else had already modified the last
name to "Fuller III," a concurrency violation was detected and reported. ADO.NET detects
a concurrency violation when a DataSet containing changed values is passed to a
SqlDataAdapter's Update method and no rows are actually modified. Simply using the
primary key (in this case the EmployeeID) in the UPDATE statement's WHERE clause will
not cause a violation to be detected because it still updates the row (in fact, this
technique has the same outcome as the last-in wins technique). Instead, more conditions
must be specified in the WHERE clause in order for ADO.NET to detect the violation.
The key here is to make the WHERE clause explicit enough so that it not only checks the
primary key but that it also checks for another appropriate condition. One way to
accomplish this is to pass in all modifiable fields to the WHERE clause in addition to the
primary key. For example, the application shown in Figure 1 could have its UPDATE
statement look like the Stored Procedure that's shown in Figure 2.
Notice that in the code in Figure 2 nullable columns are also checked to see if the value
passed in is NULL. This technique is not only messy but it can be difficult to maintain by
hand and it requires you to test for a significant number of WHERE conditions just to
update a row. This yields the desired result of only updating rows where none of the
values have changed since the last time the user got the data, but there are other
techniques that do not require such a huge WHERE clause.
Another way to ensure that the row is only updated if it has not been modified by another
user since you got the data is to add a timestamp column to the table. The SQL
Server(tm) TIMESTAMP datatype automatically updates itself with a new value every time
a value in its row is modified. This makes it a very simple and convenient tool to help
detect concurrency violations.
A third technique is to use a DATETIME column in which to track changes to its row. In my
sample application I added a column called LastUpdateDateTime to the Employees
table.
ALTER TABLE Employees ADD LastUpdateDateTime DATETIME
There I update the value of the LastUpdateDateTime field automatically in the UPDATE
Stored Procedure using the built-in SQL Server GETDATE function.
The binary TIMESTAMP column is simple to create and use since it automatically
regenerates its value each time its row is modified, but since the DATETIME column
technique is easier to display on screen and demonstrate when the change was made, I
chose it for my sample application. Both of these are solid choices, but I prefer the
TIMESTAMP technique since it does not involve any additional code to update its value.
Retrieving Row Flags

88

One of the keys to implementing concurrency controls is to update the timestamp or


datetime field's value back into the DataSet. If the same user wants to make more
modifications, this updated value is reflected in the DataSet so it can be used again.
There are a few various ways to do this. The fastest is using output parameters within the
Stored Procedure. (This should only return if @@ROWCOUNT equals 1.) The next fastest
involves selecting the row again after the UPDATE within the Stored Procedure. The
slowest involves selecting the row from another SQL statement or Stored Procedure from
the SqlDataAdapter's RowUpdated event.
I prefer to use the output parameter technique since it is the fastest and incurs the least
overhead. Using the RowUpdated event works well, but it requires me to make a second
call from the application to the database. The following code snippet adds an output
parameter to the SqlCommand object that is used to update the Employee information:
oUpdCmd.Parameters.Add(new SqlParameter("@NewLastUpdateDateTime",
SqlDbType.DateTime, 8, ParameterDirection.Output,
false, 0, 0, "LastUpdateDateTime", DataRowVersion.Current, null));
oUpdCmd.UpdatedRowSource = UpdateRowSource.OutputParameters;
The output parameter has its sourcecolumn and sourceversion arguments set to point
the output parameter's return value back to the current value of the LastUpdateDateTime
column of the DataSet. This way the updated DATETIME value is retrieved and can be
returned to the user's .aspx page. Contd....
Saving Changes
Now that the Employees table has the tracking field (LastUpdateDateTime) and the
Stored Procedure has been created to use both the primary key and the tracking field in
the WHERE clause of the UPDATE statement, let's have a look at the role of ADO.NET. In
order to trap the event when the user changes the values in the textboxes, I created an
event handler for the TextChanged event for each TextBox control:
private void txtLastName_TextChanged(object sender, System.EventArgs e)
{
// Get the employee DataRow (there is only 1 row, otherwise I could
// do a Find)
dsEmployee.EmployeeRow oEmpRow =
(dsEmployee.EmployeeRow)oDsEmployee.Employee.Rows[0];
oEmpRow.LastName = txtLastName.Text;
// Save changes back to Session
Session["oDsEmployee"] = oDsEmployee;
}
This event retrieves the row and sets the appropriate field's value from the TextBox.
(Another way of getting the changed values is to grab them when the user clicks the
Save button.) Each TextChanged event executes after the Page_Load event fires on a
postback, so assuming the user changed the first and last names, when the user clicks
the Save button, the events could fire in this order: Page_Load,
txtFirstName_TextChanged, txtLastName_TextChanged, and btnSave_Click.
The Page_Load event grabs the row from the DataSet in the Session object; the
TextChanged events update the DataRow with the new values; and the btnSave_Click
event attempts to save the record to the database. The btnSave_Click event calls the
SaveEmployee method (shown in Figure 3) and passes it a bLastInWins value of false
since we want to attempt a standard save first. If the SaveEmployee method detects that
changes were made to the row (using the HasChanges method on the DataSet, or
alternatively using the RowState property on the row), it creates an instance of the
Employee class and passes the DataSet to its SaveEmployee method. The Employee

89

class could live in a logical or physical middle tier. (I wanted to make this a separate class
so it would be easy to pull the code out and separate it from the presentation logic.)
Notice that I did not use the GetChanges method to pull out only the modified rows and
pass them to the Employee object's Save method. I skipped this step here since there is
only one row. However, if there were multiple rows in the DataSet's DataTable, it would
be better to use the GetChanges method to create a DataSet that contains only the
modified rows.
If the save succeeds, the Employee.SaveEmployee method returns a DataSet containing
the modified row and its newly updated row version flag (in this case, the
LastUpdateDateTime field's value). This DataSet is then merged into the original DataSet
so that the LastUpdateDateTime field's value can be updated in the original DataSet. This
must be done because if the user wants to make more changes she will need the current
values from the database merged back into the local DataSet and shown on screen. This
includes the LastUpdateDateTime value that is used in the WHERE clause. Without this
field's current value, a false concurrency violation would occur.
Reporting Violations
If a concurrency violation occurs, it will bubble up and be caught by the exception
handler shown in Figure 3 in the catch block for DBConcurrencyException. This block calls
the FillConcurrencyValues method, that displays both the original values in the DataSet
that were attempted to be saved to the database and the values currently in the
database. This method is used merely to show the user why the violation occurred.
Notice that the exDBC variable is passed to the FillConcurrencyValues method. This
instance of the special database concurrency exception class (DBConcurrencyException)
contains the row where the violation occurred. When a concurrency violation occurs, the
screen is updated to look like Figure 1.
The DataSet not only stores the schema and the current data, it also tracks changes that
have been made to its data. It knows which rows and columns have been modified and it
keeps track of the before and after versions of these values. When accessing a column's
value via the DataRow's indexer, in addition to the column index you can also specify a
value using the DataRowVersion enumerator. For example, after a user changes the value
of the last name of an employee, the following lines of C# code will retrieve the original
and current values stored in the LastName column:
string sLastName_Before = oEmpRow["LastName", DataRowVersion.Original];
string sLastName_After = oEmpRow["LastName", DataRowVersion.Current];
The FillConcurrencyValues method uses the row from the DBConcurrencyException and
gets a fresh copy of the same row from the database. It then displays the values using
the DataRowVersion enumerators to show the original value of the row before the update
and the value in the database alongside the current values in the textboxes.
User's Choice
Once the user has been notified of the concurrency issue, you could leave it up to her to
decide how to handle it. Another alternative is to code a specific way to deal with
concurrency, such as always handling the exception to let the user know (but refreshing
the data from the database). In this sample application I let the user decide what to do
next. She can either cancel changes, cancel and reload from the database, save changes,
or save anyway.
The option to cancel changes simply calls the RejectChanges method of the DataSet and
rebinds the DataSet to the controls in the ASP.NET page. The RejectChanges method
reverts the changes that the user made back to its original state by setting all of the
current field values to the original field values. The option to cancel changes and reload

90

the data from the database also rejects the changes but additionally goes back to the
database via the Employee class in order to get a fresh copy of the data before rebinding
to the control on the ASP.NET page.
The option to save changes attempts to save the changes but will fail if a concurrency
violation is encountered. Finally, I included a "save anyway" option. This option takes the
values the user attempted to save and uses the last-in wins technique, overwriting
whatever is in the database. It does this by calling a different command object associated
with a Stored Procedure that only uses the primary key field (EmployeeID) in the WHERE
clause of the UPDATE statement. This technique should be used with caution as it will
overwrite the record.
If you want a more automatic way of dealing with the changes, you could get a fresh
copy from the database. Then overwrite just the fields that the current user modified,
such as the Extension field. That way, in the example I used the proper LastName would
not be overwritten. Use this with caution as well, however, because if the same field was
modified by both users, you may want to just back out or ask the user what to do next.
What is obvious here is that there are several ways to deal with concurrency violations,
each of which must be carefully weighed before you decide on the one you will use in
your application.
Wrapping It Up
Setting the SqlDataAdapter's ContinueUpdateOnError property tells the SqlDataAdapter
to either throw an exception when a concurrency violation occurs or to skip the row that
caused the violation and to continue with the remaining updates. By setting this property
to false (its default value), it will throw an exception when it encounters a concurrency
violation. This technique is ideal when only saving a single row or when you are
attempting to save multiple rows and want them all to commit or all to fail.
I have split the topic of concurrency violation management into two parts. Next time I will
focus on what to do when multiple rows could cause concurrency violations. I will also
discuss how the DataViewRowState enumerators can be used to show what changes
have been made to a DataSet.
How you will set the datarelation between two columns?
ADO.NET provides DataRelation object to set relation between two columns.It helps to
enforce the following constraints,a unique constraint, that guarantees that a column in
the table contains no duplicates and a foreign-key constraint,that can be used to
maintain referential integrity.A unique constraint is implemented either by simply setting
the Unique property of a data column to true, or by adding an instance of the
UniqueConstraint class to the DataRelation object's ParentKeyConstraint. As part of the
foreign-key constraint, you can specify referential integrity rules that are applied at three
points,when a parent record is updated,when a parent record is deleted and when a
change is accepted or rejected.
WebServices And Windows Services
Can you give an example of when it would be appropriate to use a web service as
opposed to non-serviced .NET component
Web service is one of main component in Service Oriented Architecture. You could use
web services when your clients and servers are running on different networks and also
different platforms. This provides a loosely coupled system. And also if the client is
behind the firewall it would be easy to use web service since it runs on port 80 (by
default) instead of having some thing else in Service Oriented Architecture applications.
What is the standard you use to wrap up a call to a Web service
"SOAP.

91

"
What is the transport protocol you use to call a Web service SOAP
HTTP with SOAP
What does WSDL stand for?
"WSDL stands for Web Services Dsescription Langauge. There is WSDL.exe that creates a
.wsdl Files that defines how an XML Web service behaves and instructs clients as to how
to interact with the service.
eg: wsdl http://LocalHost/WebServiceName.asmx"
Where on the Internet would you look for Web Services?
www.uddi.org
What does WSDL stand for?
Web Services Description Language
True or False: To test a Web service you must create a windows application or
Web application to consume this service?
False.
What are the various ways of accessing a web service ?
1. Asynchronous Call
Application can make a call to the Webservice and then continue todo watever oit wants
to do.When the service is ready it will notify the application.Application can use BEGIN
and END method to make asynchronous call to the webmethod.We can use either a
WaitHandle or a Delegate object when making asynchronous call.
The WaitHandle class share resources between several objects. It provides several
methods that will wait for the resources to become available
The easiest and most powerful way to to implement an asynchronous call is using a
delegate object. A delegate object wraps up a callback function. The idea is to pass a
method in the invocation of the web method. When the webmethod has finished it will
call this callback function to process the result
2. Synchronous Call
Application has to wait until execution has completed.
Note: Few of the references are taken from other sites/sources
What are VSDISCO files?
VSDISCO files are DISCO files that support dynamic discovery of Web services. If you
place the following VSDISCO file in a directory on your Web server, for example, it returns
references to all ASMX and DISCO files in the host directory and any subdirectories not
noted in <EXCLUDE>elements:
<DYNAMICDISCOVERY
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<EXCLUDE path="_vti_cnf" />
<EXCLUDE path="_vti_pvt" />
<EXCLUDE path="_vti_log" />

92

<EXCLUDE path="_vti_script" />


<EXCLUDE path="_vti_txt" />
</DYNAMICDISCOVERY>
How does dynamic discovery work?
ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host
directory and subdirectories for ASMX and DISCO files and returns a dynamically
generated DISCO document. A client who requests a VSDISCO file gets back what
appears to be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable
them by uncommenting the line in the <HTTPHANDLERS>section of Machine.config that
maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting
the ASPNET user account permission to read the IIS metabase. However, Microsoft is
actively discouraging the use of VSDISCO files because they could represent a threat to
Web server security.
Is it possible to prevent a browser from caching an ASPX page?
Just call SetNoStore on the HttpCachePolicy object exposed through the Response
object's Cache property, as demonstrated here:
<%@ Page Language="C#" %>
<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP
response. In this example, it prevents caching of a Web page that shows the current
time.
What does AspCompat="true" mean and when should I use it?
AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but
should be set to true in any ASPX file that creates apartment-threaded COM objects--that
is, COM objects registered ThreadingModel=Apartment. That includes all COM objects
written with Visual Basic 6.0. AspCompat should also be set to true (regardless of
threading model) if the page creates COM objects that access intrinsic ASP objects such
as Request and Response. The following directive sets AspCompat to true:
<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available
to the COM components by placing unmanaged wrappers around the equivalent ASP.NET
objects. Second, it improves the performance of calls that the page places to apartmentthreaded COM objects by ensuring that the page (actually, the thread that processes the
request for the page) and the COM objects it creates share an apartment.
AspCompat="true" forces ASP.NET request threads into single-threaded apartments
(STAs). If those threads create COM objects marked ThreadingModel=Apartment, then
the objects are created in the same STAs as the threads that created them. Without
AspCompat="true," request threads run in a multithreaded apartment (MTA) and each
call to an STA-based COM object incurs a performance hit when it's marshaled across
apartment boundaries.
Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects
that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or
ThreadingModel=Both.

93

Can two different programming languages be mixed in a single ASMX file?


No.
What namespaces are imported by default in ASMX files?
The following namespaces are imported by default. Other namespaces must be imported
manually. System, System.Collections,System.ComponentModel,System.Data,
System.Diagnostics,System.Web,System.Web.Services
How do I provide information to the Web Service when the information is
required as a SOAP Header?
The key here is the Web Service proxy you created using wsdl.exe or through Visual
Studio .NET's Add Web Reference menu option. If you happen to download a WSDL file for
a Web Service that requires a SOAP header, .NET will create a SoapHeader class in the
proxy source file. Using the previous example:
public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol
{
public AuthToken AuthTokenValue;
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/",
IsNullable = false)]
public class AuthToken : SoapHeader { public string Token; }
}
In this case, when you create an instance of the proxy in your main application file, you'll
also create an instance of the AuthToken class and assign the string:
Service1 objSvc = new Service1();
processingobjSvc.AuthTokenValue = new AuthToken();
objSvc.AuthTokenValue.Token = <ACTUAL token value>;
Web Servicestring strResult = objSvc.MyBillableWebMethod();
What is WSDL?
WSDL is the Web Service Description Language, and it is implemented as a specific XML
vocabulary. While it's very much more complex than what can be described here, there
are two important aspects to WSDL with which you should be aware. First, WSDL provides
instructions to consumers of Web Services to describe the layout and contents of the
SOAP packets the Web Service intends to issue. It's an interface description document, of
sorts. And second, it isn't intended that you read and interpret the WSDL. Rather, WSDL
should be processed by machine, typically to generate proxy source code (.NET) or
create dynamic proxies on the fly (the SOAP Toolkit or Web Service Behavior).
What is a Windows Service and how does its lifecycle differ from a "standard"
EXE?
Windows service is a application that runs in the background. It is equivalent to a NT
service.
The executable created is not a Windows application, and hence you can't just click and
run it . it needs to be installed as a service, VB.Net has a facility where we can add an
installer to our program and then use a utility to install the service. Where as this is not
the case with standard exe
How can a win service developed in .NET be installed or used in Win98?
Windows service cannot be installed on Win9x machines even though the .NET
framework runs on machine.

94

Can you debug a Windows Service? How ?


Yes we can debug a Windows Service.
Attach the WinDbg debugger to a service after the service starts
This method is similar to the method that you can use to attach a debugger to a process
and then debug a process.
Use the process ID of the process that hosts the service that you want to debug
1. To determine the process ID (PID) of the process that hosts the service that you want
to debug, use one of the following methods.
Method 1: Use the Task Manager

Right-click the Taskbar, and then click Task Manager. The Windows Task Manager
dialog box appears.

Click the Processes tab of the Windows Task Manager dialog box.

Under Image Name, click the image name of the process that hosts the service
that you want to debug. Note the process ID of this process as specified by the
value of the corresponding PID field.

Method 2: Use the Task List Utility (tlist.exe)

Click Start, and then click Run. The Run dialog box appears.

In the Open box, type cmd, and then click OK.

At the command prompt, change the directory path to reflect the location of the
tlist.exe file on your computer
Note: The tlist.exe file is typically located in the following directory: C:\Program
Files\Debugging Tools for Windows

d. At the command prompt, type tlist to list the image names and the process IDs
of all processes that are currently running on your computer.

Note Make a note of the process ID of the process that hosts the service that you want to
debug.
2. At a command prompt, change the directory path to reflect the location of the
windbg.exe file on your computer.
Note: If a command prompt is not open, follow steps a and b of Method 1. The
windbg.exe file is typically located in the following directory: C:\Program Files\Debugging
Tools for Windows.
3. At the command prompt, type windbg p ProcessID to attach the WinDbg debugger to
the process that hosts the service that you want to debug.
Note ProcessID is a placeholder for the process ID of the process that hosts the service
that you want to debug.

95

Use the image name of the process that hosts the service that you want to debug
You can use this method only if there is exactly one running instance of the process that
hosts the service that you want to run. To do this, follow these steps:
1.

Click Start, and then click Run. The Run dialog box appears.

2.

In the Open box, type cmd, and then click OK to open a command prompt.

3.

At the command prompt, change the directory path to reflect the location of the
windbg.exe file on your computer.

Note: The windbg.exe file is typically located in the following directory: C:\Program
Files\Debugging Tools for Windows.
4. At the command prompt, type windbg pn ImageName to attach the WinDbg
debugger to the process that hosts the service that you want to debug.
NoteImageName is a placeholder for the image name of the process that hosts the
service that you want to debug. The "-pn" command-line option specifies that the
ImageName command-line argument is the image name of a process.
back to the top
Start the WinDbg debugger and attach to the process that hosts the service that you
want to debug
1.

Start Windows Explorer.

2.

Locate the windbg.exe file on your computer.


Note: The windbg.exe file is typically located in the following directory:
C:\Program Files\Debugging Tools for Windows

3.

Run the windbg.exe file to start the WinDbg debugger.

4.

On the File menu, click Attach to a Process to display the Attach to Process dialog
box.

5.

Click to select the node that corresponds to the process that hosts the service
that you want to debug, and then click OK.

6.

In the dialog box that appears, click Yes to save base workspace information.
Notice that you can now debug the disassembled code of your service.

Configure a service to start with the WinDbg debugger attached


You can use this method to debug services if you want to troubleshoot service-startuprelated problems.
1. Configure the "Image File Execution" options. To do this, use one of the following
methods:
Method 1: Use the Global Flags Editor (gflags.exe)

96

Start Windows Explorer.

Locate the gflags.exe file on your computer.


Note: The gflags.exe file is typically located in the following directory: C:\Program
Files\Debugging Tools for Windows.

Run the gflags.exe file to start the Global Flags Editor.

In the Image File Name text box, type the image name of the process that hosts
the service that you want to debug. For example, if you want to debug a service
that is hosted by a process that has MyService.exe as the image name, type
MyService.exe.

Under Destination, click to select the Image File Options option.

Under Image Debugger Options, click to select the Debugger check box.

In the Debugger text box, type the full path of the debugger that you want to use.
For example, if you want to use the WinDbg debugger to debug a service, you can
type a full path that is similar to the following: C:\Program Files\Debugging Tools
for Windows\windbg.exe

Click Apply, and then click OK to quit the Global Flags Editor.

Method 2: Use Registry Editor

Click Start, and then click Run. The Run dialog box appears.

In the Open box, type regedit, and then click OK to start Registry Editor.

Warning If you use Registry Editor incorrectly, you may cause serious problems
that may require you to reinstall your operating system. Microsoft cannot
guarantee that you can solve problems that result from using Registry Editor
incorrectly. Use Registry Editor at your own risk.
In Registry Editor, locate, and then right-click the following registry subkey:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image
File Execution Options

Point to New, and then click Key. In the left pane of Registry Editor, notice that
New Key #1 (the name of a new registry subkey) is selected for editing.

Type ImageName to replace New Key #1, and then press ENTER.
Note ImageName is a placeholder for the image name of the process that hosts
the service that you want to debug. For example, if you want to debug a service
that is hosted by a process that has MyService.exe as the image name, type
MyService.exe.

Right-click the registry subkey that you created in step e.

97

Point to New, and then click String Value. In the right pane of Registry Editor,
notice that New Value #1, the name of a new registry entry, is selected for
editing.

Replace New Value #1 with Debugger, and then press ENTER.

Right-click the Debugger registry entry that you created in step h, and then click
Modify. The Edit String dialog box appears.

In the Value data text box, type DebuggerPath, and then click OK.
Note: DebuggerPath is a placeholder for the full path of the debugger that you
want to use. For example, if you want to use the WinDbg debugger to debug a
service, you can type a full path that is similar to the following: C:\Program
Files\Debugging Tools for Windows\windbg.exe

2. For the debugger window to appear on your Desktop, and to interact with the
debugger, make your service interactive. If you do not make your service interactive, the
debugger will start but you cannot see it and you cannot issue commands. To make your
service interactive, use one of the following methods:
Method 1: Use the Services console

Click Start, and then point to Programs.

On the Programs menu, point to Administrative Tools, and then click Services. The
Services console appears.

In the right pane of the Services console, right-click ServiceName, and then click
Properties.
Note: ServiceName is a placeholder for the name of the service that you want to
debug.

On the Log On tab, click to select the Allow service to interact with Desktop check
box under Local System account, and then click OK.

Method 2: Use Registry Editor

In Registry Editor, locate, and then click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ServiceName
Note Replace ServiceName with the name of the service that you want to debug.
For example, if you want to debug a service named MyService, locate and then
click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService

Under the Name field in the right pane of Registry Editor, right-click Type, and
then click Modify. The Edit DWORD Value dialog box appears.

Change the text in the Value data text box to the result of the binary OR operation
with the binary value of the current text and the binary value, 0x00000100, as the
two operands. The binary value, 0x00000100, corresponds to the
SERVICE_INTERACTIVE_PROCESS constant that is defined in the WinNT.h header

98

file on your computer. This constant specifies that a service is interactive in


nature.

3. When a service starts, the service communicates to the Service Control Manager how
long the service must need to start (the time-out period for the service). If the Service
Control Manager does not receive a "service started" notice from the service within this
time-out period, the Service Control Manager terminates the process that hosts the
service. This time-out period is typically less than 30 seconds. If you do not adjust this
time-out period, the Service Control Manager ends the process and the attached
debugger while you are trying to debug. To adjust this time-out period, follow these
steps:

In Registry Editor, locate, and then right-click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control

Point to New, and then click DWORD Value. In the right pane of Registry Editor,
notice that New Value #1 (the name of a new registry entry) is selected for
editing.

Type ServicesPipeTimeout to replace New Value #1, and then press ENTER.

Right-click the ServicesPipeTimeout registry entry that you created in step c, and
then click Modify. The Edit DWORD Value dialog box appears.

In the Value data text box, type TimeoutPeriod, and then click OK
Note: TimeoutPeriod is a placeholder for the value of the time-out period (in
milliseconds) that you want to set for the service. For example, if you want to set
the time-out period to 24 hours (86400000 milliseconds), type 86400000.

Restart the computer. You must restart the computer for Service Control Manager
to apply this change.

4. Start your Windows service. To do this, follow these steps:

Click Start, and then point to Programs.

On the Programs menu, point to Administrative Tools, and then click Services. The
Services console appears.

In the right pane of the Services console, right-click ServiceName, and then click
Start.
Note: ServiceName is a placeholder for the name of the service that you want to
debug.

Note: Few of the references are taken from other sites/sources


Conclusion
Now we have a many question at one single place and we can brush-up anytime when
we need to.

99

Note: Some Contents are copied from various Interview Websites.

Top Frequently Asked Questions in .Net


Interview
1. What is the difference between an abstract class and interfaces?
Probably "Difference Between abstract Class and Interface" is the most frequent question
being asked in the .Net world. In this tutorial, I will explain the differences theoretically
followed by code snippets.
Theoretically there are basically 5 differences between Abstract Classes and Interfaces as
listed below.
1. A class can implement any number of interfaces but a subclass can at most use
only one abstract class.
2. An abstract class can have non-abstract methods (concrete methods) whereas all
methods of interfaces must be abstract.
3. An abstract class can declare or use any variables whereas an interface is not
allowed to do so.
The following code compiles properly since no field declaration is in the interface.
interface TestInterface
{
int x = 4; // Filed Declaration in Interface
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
int i = 4;
int k = 3;
public abstract void getClassName();
}
It will generate a compile time error as:
Error1- Interfaces cannot contain fields.
So we need to omit the Field Declaration to compile the code properly.
interface TestInterface
{
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
int i = 4;
int k = 3;
public abstract void getClassName();
}

100

4. An abstract class can have a constructor declaration whereas an interface cannot.


So the following code will not compile:
interface TestInterface
{
// Constructor Declaration
public TestInterface()
{
}
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
public TestAbstractClass()
{
}
int i = 4;
int k = 3;
public abstract void getClassName();
}
The code above will generate the compile time error:
Error 1-Interfaces cannot contain constructors
So we need to omit the constructor declaration from the interface to compile our
code.
The following code compiles perfectly:
interface TestInterface
{
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
public TestAbstractClass()
{
}
int i = 4;
int k = 3;
public abstract void getClassName();
}

5. An abstract class is allowed to have all access modifiers for all of its member
declarations whereas in an interface we cannot declare any access modifier
(including public) since all the members of an interface are implicitly public.
Note: here I am talking about the access specifiers of the member of interfaces
and not about the interface.

101

The following code will explain it better.


It is perfectly legal to provide an access specifier as Public (remember only public
is allowed).
public interface TestInterface
{
void getMethod();
string getName();
}
The code above compiles perfectly.
It is not allowed to provide any access specifier to the members of the interface.
interface TestInterface
{
public void getMethod();
public string getName();
}
The code above will generate the compile time error:
Error 1: The modifier 'public' is not valid for this item.
But the best way of declaring an interface will be to avoid access specifiers on
interfaces as well as members of interfaces.
interface Test
{
void getMethod();
string getName();
}
2. What is the difference between overriding and overloading?
Overloading

In this approach we can define multiple methods with the same name changing
their signature. In other words different parameters

This can be performed within a class as well as within a child class

Doesn't require any permission from the parent for overloading its method in the
child

Overriding

It is an approach of defining multiple methods with the same name and the same
signature

This can be performed only under child classes

Requires an explicit permission from the parent to override its methods in the
child

102

3. String Builder and String class


String
A string is a sequential collection of Unicode characters that represent text. String is a
class that belongs to the namespace System.String.
String concatenation can be done using the '+' opearator or the String.Concat method.
The String.Concat method concatenates one or more instances of a String.
Sample code
string string1 = "Today is " + DateTime.Now.ToString ("D") + ".";
Console.WriteLine (string1);
string string2 = "Hi " + "This is Jitendra ";
string2 += "SampathiRao.";
Console.WriteLine(string2);
StringBuilder
StringBuilder is a class that belongs to the namespace System.Text. This class cannot be
inherited.
In StringBuilder we use the Append () method.
Sample code
StringBuilder number = new StringBuilder (10000);
for (int i = 0; i<1000; i++)
{
returnNumber.Append (i.ToString ());
}
So where do we use these classes?
The answer is for simple String manipulations we can use the String class. But when
there are more string manipulations it is better to use the StringBuilder class.
Why is the StringBuilder class better for more string manipulations instead of the String
class?
The String object is immutable. Every time you use one of the methods in
the System.String class, you create a new string object in memory, that requires a new
allocation of space for that new object. In situations where you need to perform repeated
modifications to a string, the overhead associated with creating a new String object can
be costly. The performance of the application might be degraded. So we use StringBuilder
in such cases.
A StringBuilder object is mutable. The System.Text.StringBuilder class can be used when
you want to modify a string without creating a new object. For example, using
the StringBuilder class can boost performance when concatenating many strings
together in a loop.
Differences between String and StringBuilder
It belongs to String namespace

It belongs to String.Text namespace

103

String object is immutable

StringBuilder object is mutable

Assigning:
StringBuilder sbuild= new
StringBuilder("something important");

Assigning:
String s= "something important";

We can use the '+' operator or Concat


method to concatenate the strings.

We use the Append method.

When string concatenation is done,


additional memory will be allocated.

Here additional memory will only be


allocated when the string buffer capacity is
exceeded.

4. What is the difference between array and array list?


Mirosoft.Net has many namespaces for many purposes. Among them
the System.Collections is a very important namespace in the programmer's perceptive.
While coding, we look for classes that can reduce manual operation. For instance if you
want to sort the values in an array then you need to do the manual operations. Here
obviously we look for the classes that can automate the sorting by just calling a method.
In other words we can call this namespace as a utility namespace. Let us see the classes
in this namespace.
Collection Classes
The System.Collections namespace has many classes for the individual purpose. We will
discuss the frequently used classes in this article.

ArrayList

BitArray

Stack

Queue

Comparer

HashTable

SortedList

ArrayList
The ArrayList is one of the important classes in the System.Collection namespace. We
can say it is the next generation of the Array in C#.
ArrayList is a dynamic array; it will increase the size of the storage location as required. It
stores the value as an object. The allocation of the ArrayList can be done through the
TrimToSize property.
Methods
1 Add

It will add the element as object in the ArrayList

2 AddRange

It will add the collections of elements in the object as individual objects


in the ArrayList

104

3 Clear
4

It will clear the all objects in the ArrayList

BinarySearc
It will return the position of the search object as integer value.
h

5 Insert

It will insert the element in the specified location of the index in the
ArrayList.

6 InsertRange

It will insert the elements in the object as individual objects in the


specified location.

7 Remove

It will remove the given object in the first occurrence in the ArrayList.

8 RemoveAt

It will remove the object as specified in the argument.

RemoveRan
It will remove the set of objects in the ArrayList from the range specified.
ge

1
Sort
0

It will sort the elements in ascending order.

1
Reverse
1

It will arrange the elements in the reverse order in the ArrayList.

1 GetEnumera
2 tor
It will return the collection of objects in the ArrayList as an enumerator.
1
Contains
3

It checks whether the objects exist.

Properties in the ArrayList


S.N Property
o
Name

Description

Capcity

This property sets or gets the size of the ArrayList.


As you know it will increase the size of the storage as much as
required. The default size will be 16.

Count

It returns the total number of elements in the ArrayList.

IsFixedSize

It returns whether the ArrayList is fixed in size. It returns a Boolean


value.

IsReadOnly

It returns whether the ArrayList is Readyonly. It returns a Boolean


value.

Advantages

An ArrayList is not a specific data type storage location, it stores everything as an


object.

No need to do allocation and deallocation explicitly to store the data.

It has explicit sorting methods.

It can insert and delete the elements between positions in the ArrayList.

It can store the object as elements.

Disadvantages

ArrayList is not strongly typed. Type casting is necessary when retrieving the
content. When we do the type casting every time, it affects performance.

105

It uses the LinkedList storage approach, because if you insert or delete the
specific position then it must adjust forward/backward in the storage address.

Sometimes it leads to a runtime error. Consider an example in which we store the


ids of the employee in the arraylist and then we want to retrieve the element for
some other operations. Obviously we need to do type casting and when there is a
string element then what will happen? It will throw the error.

Differences between Array and ArrayList


Array

ArrayList

Array uses the Vector array to


store the elements

ArrayList uses the LinkedList to store the elements.

Size of the Array must be defined


until redim is used (vb)

No need to specify the storage size.

Array is a specific data type


storage

ArrayList can store everything as an object.

No need to do the type casting

Type casting must be done every time.

It will not lead to Runtime


exception

It leads to a run time error exception.

Element cannot be inserted or


deleted in between.

Elements can be inserted and deleted.

There are no built-in members to


do ascending or descending.

An ArrayList has many methods to do operations like


Sort, Insert, Remove, BinarySeacrh and so on.

Conclusion
So far we have seen the ArrayList and its members and properties. I hope that this has
provided enough of a practical idea about ArrayList. Next we will discuss the BitArray in
the same collection class. If you have any queries or further clarifications about ArrayList
then please free to post your feedback and corrections.
5. What are cursors and constraints ?
Cursors
A cursor is a database object that helps in accessing and manipulating data in a given
result set.The main advantage of cursors is that you can process data row-by-row.
A result set is defined as a collection of rows obtained from a SELECT statement that
meet the criteria specified in the WHERE clause.
Cursors, therefore, serve as a mechanism for applications to operate on a single row or a
set of rows. Cursors enable the processing of rows in the given result set in the following
ways:
1. Allow specific rows to be retrieved from the result set.
2. Allow the current row in the result set to be modified.
3. Help navigate from the current row in the result set to a different row.
4. Allow data modified by other users to be visible in the result set.

106

Declare the cursor

Initialize the cursor

Open the cursor

Fetch each row until the status is 0

close the cursor

deallocate the cursor

/* Create two variables that would store the values returned by the fetch statement */
DECLARE @DepartmentName char(25)
DECLARE @DepartmentHead char(25)
/* Define the cursor that can be used to access the records of the table,row by row */
DECLARE curDepartment cursor for
SELECT vDepartmentName,vDepartmentHead from Department
-- Open the cursor
OPEN curDepartment
-- Fetch the rows into variables
FETCH curDepartment into @DepartmentName,@DepartmentHead
--Start a loop to display all the rows of the cursor
WHILE(@@fetch_status=0)
BEGIN
Print 'Department Name =' + @DepartmentName
Print 'Department Head =' + @DepartmentHead
--Fetch the next row from the cursor
FETCH curDepartment into @DepartmentName,@DepartmentHead
END
-- Close the cursor
CLOSE curDepartment
-- Deallocate the cursor
DEALLOCATE curDepartment
The following are various types of cursors available in SQL Server 2005:
1. Base table
2. Static
3. Forward-only
4. Forward-only/Read-only
5. Keyset-driven

107

Base table: Base table cursors are the lowest level of cursor available. Base table
cursors can scroll forward or backward with minimal cost, and can be updated
Static: Cursors can move to any record but the changes on the data can't be seen.
Dynamic: Most resource-intensive. Cursors can move anywhere and all the changes on
the data can be viewed.
Forward-only: The cursor moves forward but can't move backward.
Keyset-driven: Only updated data can be viewed, deleted and inserted data cannot be
viewed.
Constraint
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted
by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE
statement) or after the table is created (inside the ALTER TABLE statement).
SQL CREATE TABLE + CONSTRAINT Syntax:
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
In SQL, we have the following constraints:

NOT NULL: Indicates that a column cannot store a NULL value

UNIQUE: Ensures that each row for a column must have a unique value

PRIMARY KEY: A combination of a NOT NULL and UNIQUE. Ensures that a column
(or combination of two or more columns) have a unique identity that helps to find
a specific record in a table more easily and quickly

FOREIGN KEY: Ensures the referential integrity of the data in one table to match
values in another table

CHECK: Ensures that the value in a column meets a specific condition

DEFAULT: Specifies a default value when none is specified for this column

6. What are the differences among foreign, primary, and unique keys
While unique and primary keys both enforce uniqueness on the column(s) of one table,
foreign keys define a relationship between two tables. A foreign key identifies a column
or group of columns in one (referencing) table that refers to a column or group of
columns in another (referenced) table; in our example above, the Employee table is the
referenced table and the Employee Salary table is the referencing table.
7. Difference Between SCOPE_IDENTITY() and @@IDENTITY

108

@@IDENTITY: Returns the last identity values that were generated in any table in the
current session. @@IDENTITY is not limited to a specific scope.
SCOPE_IDENTITY(): Returns the last identity values that are generated in any table in the
current session. SCOPE_IDENTITY returns values inserted only within the current scope.
8. Delegates and Events
The delegate topic seems to be confusing and tough for most developers. This article
explains the basics of delegates and event handling in C# in a simple manner.
A delegate is one of the base types in .NET. Delegate is a class to create delegates at
runtime.
A delegate in C# is similar to a function pointer in C or C++. It's a new type of object in
C#. A delegate is a very special type of object since earlier the entire the object was
used to defined contained data but a delegate just contains the details of a method.
The need for delegates
There might be a situation in which you want to pass methods around to other methods.
For this purpose we create delegates.
A delegate is a class that encapsulates a method signature. Although it can be used in
any context, it often serves as the basis for the event-handling model in C# but can be
used in a context removed from event handling (for example passing a method to a
method through a delegate parameter).
One good way of understanding delegates is by thinking of a delegate as something that
gives a name to a method signature.
Example
public delegate int DelegateMethod(int x, int y);
Any method that matches the delegate's signature, that consists of the return type and
parameters, can be assigned to the delegate. This makes is possible to programmatically
change method calls, and also plug new code into existing classes. As long as you know
the delegate's signature, you can assign your own-delegated method.
This ability to refer to a method as a parameter makes delegates ideal for defining
callback methods.
Delegate magic
In a class we create its object, that is an instance, but in a delegate when we create an
instance it is also referred to as a delegate (in other words whatever you do, you will get
a delegate).
A delegate does not know or care about the class of the object that it references. Any
object will do; all that matters is that the method's argument types and return type
match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
Benefit of delegates
In simple words delegates are object oriented and type-safe and very secure since
they ensure that the signature of the method being called is correct. Delegates help in
code optimization.

109

Types of delegates
1. Singlecast delegates
2. Multiplecast delegates
A delegate is a class. Any delegate is inherited from the base delegate class of the .NET
class library when it is declared. This can be from either of the
two classes System.Delegate or System.MulticastDelegate.
Singlecast delegate
a Singlecast delegate points to a single method at a time. In this the delegate is assigned
to a single method at a time. They are derived from the System.Delegate class.
Multicast Delegate
When a delegate is wrapped with more than one method then that is known as a
multicast delegate.
In C#, delegates are multicast, which means that they can point to more than one
function at a time. They are derived from the System.MulticastDelegate class.
There are three steps in defining and using delegates:
1. Declaration
To create a delegate, you use the delegate keyword.
[attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);
The attributes factor can be a normal C# attribute.
The modifier can be one, or an appropriate combination, of the following keywords: new,
public, private, protected, or internal.
The ReturnType can be any of the data types we have used so far. It can also be a type
void or the name of a class.
"Name" must be a valid C# name.
Because a delegate is some type of a template for a method, you must use parentheses,
required for every method. If this method will not take any arguments then leave the
parentheses empty.
Example
public delegate void DelegateExample();
The code piece defines a delegate DelegateExample() that has a void return type and
accepts no parameters.
2. Instantiation
DelegateExample d1 = new DelegateExample(Display);
The preceding code piece shows how the delegate is initiated.

110

3. Invocation
d1();
The preceding code piece invokes the delegate d1().
The following is a sample to demonstrate a Singlecast delegate:
using System;
namespace ConsoleApplication5
{
class Program
{
public delegate void delmethod();
public class P
{
public static void display()
{
Console.WriteLine("Hello!");
}
public static void show()
{
Console.WriteLine("Hi!");
}
public void print()
{
Console.WriteLine("Print");
}
}
static void Main(string[] args)
{
// here we have assigned static method show() of class P to delegate delmethod()
delmethod del1 = P.show;
// here we have assigned static method display() of class P to delegate
delmethod() using new operator
// you can use both ways to assign the delagate
delmethod del2 = new delmethod(P.display);
P obj = new P();
// here first we have create instance of class P and assigned the method print() to
the delegate i.e. delegate with class
delmethod del3 = obj.print;

}
}

del1();
del2();
del3();
Console.ReadLine();

The following is a sample to demonstrate a Multicast delegate:

111

using System;
namespace delegate_Example4
{
class Program
{
public delegate void delmethod(int x, int y);
public class TestMultipleDelegate
{
public void plus_Method1(int x, int y)
{
Console.Write("You are in plus_Method");
Console.WriteLine(x + y);
}
public void subtract_Method2(int x, int y)
{
Console.Write("You are in subtract_Method");
Console.WriteLine(x - y);
}
}
static void Main(string[] args)
{
TestMultipleDelegate obj = new TestMultipleDelegate();
delmethod del = new delmethod(obj.plus_Method1);
// Here we have multicast
del += new delmethod(obj.subtract_Method2);
// plus_Method1 and subtract_Method2 are called
del(50, 10);
Console.WriteLine();
//Here again we have multicast
del -= new delmethod(obj.plus_Method1);
//Only subtract_Method2 is called
del(20, 10);
Console.ReadLine();
}

The following are points to remember about delegates:

Delegates are similar to C++ function pointers, but are type safe.

Delegate gives a name to a method signature.

Delegates allow methods to be passed as parameters.

Delegates can be used to define callback methods.

Delegates can be chained together; for example, multiple methods can be called
on a single event.

C# version 2.0 introduces the concept of Anonymous Methods, that permit code
blocks to be passed as parameters in place of a separately defined method.

112

Delegates helps in code optimization.

Usage areas of delegates

The most common example of using delegates is in events.

They are extensively used in threading.

Delegates are also used for generic class libraries, that have generic functionality,
defined.

An Anonymous Delegate
You can create a delegate, but there is no need to declare the method associated with it.
You do not need to explicitly define a method prior to using the delegate. Such a method
is referred to as anonymous.
In other words, if a delegate itself contains its method definition then it is known as an
anonymous method.
The following is a sample to show an anonymous delegate:
using System;
public delegate void Test();
public class Program
{
static int Main()
{
Test Display = delegate()
{
Console.WriteLine("Anonymous Delegate method");
};
Display();
return 0;
}

Note: You can also handle events by anonymous methods.


Events
Events and delegates are linked together.
An event is a reference of a delegate, in other words when an event is raised a
delegate will be called.
In C# terms, events are a special form of delegates. Events are nothing but a
change of state. Events play an important part in GUI programming. Events and
delegates work hand-in-hand to provide a program's functionality.
A C# event is a class member that is activated whenever the event it was
designed for occurs.

113

It starts with a class that declares an event. Any class, including the same class
that the event is declared in, may register one of its methods for the event. This
occurs through a delegate, that specifies the signature of the method that is
registered for the event. The event keyword is a delegate modifier. It must
always be used in connection with a delegate.
The delegate may be one of the pre-defined .NET delegates or one you declare
yourself. Whichever is appropriate, you assign the delegate to the event, that
effectively registers the method that will be called when the event fires.
How to use events?
Once an event is declared, it must be associated with one or more event
handlers before it can be raised. An event handler is nothing but a method that is
called using a delegate. Use the += operator to associate an event with an
instance of a delegate that already exists.
The following is an example:
obj.MyEvent += new MyDelegate(obj.Display);
An event has the value null if it has no registered listeners.
Although events are most commonly used in Windows Controls programming,
they can also be implemented in console, web and other applications.
The following is a sample of creating a custom Singlecast delegate and event:
using System;
namespace delegate_custom
{
class Program
{
public delegate void MyDelegate(int a);
public class XX
{
public event MyDelegate MyEvent;
public void RaiseEvent()
{
MyEvent(20);
Console.WriteLine("Event Raised");
}

public void Display(int x)


{
Console.WriteLine("Display Method {0}", x);
}

static void Main(string[] args)


{
XX obj = new XX();
obj.MyEvent += new MyDelegate(obj.Display);

114

}
}

obj.RaiseEvent();
Console.ReadLine();

9. ASP.NET page cycle?


Each request for an .aspx page that hits IIS is handed over to the HTTP Pipeline. The
HTTP Pipeline is a chain of managed objects that sequentially process the request and
convert it to plain HTML text content. The starting point of a HTTP Pipeline is
the HttpRuntime class. The ASP.NET infrastructure creates each instance of this class per
AppDomain hosted within the worker process. The HttpRuntime class picks up
an HttpApplication object from an internal pool and sets it to work on the request. It
determines what class handles the request. The association between the resources and
handlers are stored in the configurable file of the application. In web.config and also
inmachine.config you will find these lines in section.
If you run through the following program then it will be much easier to follow:
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>
This extension can be associated
with HandlerClass or HandlerFactory class. HttpApplicationobject gets the page object
that implements the IHttpHandler Interface. The process of generating the output to the
browser is started when the object calls the ProcessRequest method.
Page Life Cycle
Once the HTTP page handler class is fully identified, the ASP.NET runtime calls the
handler's ProcessRequest to start the process. This implementation begins by calling the
methodFrameworkInitialize(), that builds the control trees for the page. This is a
protected and virtual member of the TemplateControl class, the class from which the
page itself derives.
Next processRequest() makes the page transition through various phases: initialization,
the loading of viewstate and postback data, the loading of the page's user code and the
execution of postback server-side events. Then the page enters into render mode, the
viewstate is updated and the HTML is generated and sent to the output console. Finally
the page is unloaded and the request is considered completely served.
Stages and corresponding events in the life cycle of the ASP.NET page cycle:
Stage

Events/Method

Page Initialization

Page_Init

View State Loading

LoadViewState

Postback data processing

LoadPostData

Page Loading

Page_Load

PostBack Change Notification

RaisePostDataChangedEvent

PostBack Event Handling

RaisePostBackEvent

Page Pre Rendering Phase

Page_PreRender

View State Saving

SaveViewState

Page_Render

Page Rendering

Page_UnLoad

Page Unloading

115

Some of the events listed above are not visible at the page level. It will be visible if you
happen to write server controls and write a class that is derived from page.
1. PreInit
The entry point of the page life cycle is the pre-initialization phase called "PreInit". This is
the only event where programmatic access to master pages and themes is allowed. You
can dynamically set the values of master pages and themes in this event. You can also
dynamically create controls in this event.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_PreInit(object sender, EventArgs e)
{
// Use this event for the following:
// Check the IsPostBack property to determine whether this is the first time the
page is being processed.
// Create or re-create dynamic controls.
// Set a master page dynamically.
// Set the Theme property dynamically.
}
2. Init
This event fires after each control has been initialized, each control's UniqueID is set and
any skin settings have been applied. You can use this event to change initialization
values for controls. The "Init" event is fired first for the most bottom control in the
hierarchy, and then fired up the hierarchy until it is fired for the page itself.
Example : Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_Init(object sender, EventArgs e)
{
// Raised after all controls have been initialized and any skin settings have been
applied.
// Use this event to read or initialize control properties.
}
3. InitComplete
Raised once all initializations of the page and its controls have been completed. Until now
the viewstate values are not yet loaded, hence you can use this event to make changes
to view state that you want to ensure are persisted after the next postback.
Example : Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_InitComplete(object sender, EventArgs e)

116

{
// Raised by the Page object. Use this event for processing tasks that require all
initialization be complete.
}
4. PreLoad
Raised after the page loads the view state for itself and all controls and then processes
postback data included with the Request instance.
Loads ViewState: ViewState data are loaded to controls
Note: The page viewstate is managed by ASP.NET and persists information over a page
roundtrip to the server. Viewstate information is saved as a string of name/value pairs
and contains information such as control text or value. The viewstate is held in the value
property of a hidden control that is passed from page request to page request.
Loads Postback data: postback data are now handed to the page controls.
Note: During this phase of the page creation, form data that was posted to
the server (termed postback data in ASP.NET) is processed against each control that
requires it. Hence, the page fires the LoadPostData event and parses through the page to
find each control and updates the control state with the correct postback data. ASP.NET
updates the correct control by matching the control's unique ID with the name/value pair
in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each
control on any given page.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected override void OnPreLoad(EventArgs e)
{
// Use this event if you need to perform processing on your page or control before
the Load event.
// Before the Page instance raises this event, it loads view state for itself and all
controls, and
// then processes any postback data included with the Request instance.
}
5. Load
The important thing to note about this event is the fact that by now, the page has been
restored to its previous state in case of postbacks. Code inside the page load event
typically checks for PostBack and then sets control properties appropriately. This method
is typically used for most code, since this is the first place in the page lifecycle that all
values are restored. Most code checks the value of IsPostBack to avoid unnecessarily
resetting state. You may also wish to call Validate and check the value of IsValid in this
method. You can also create dynamic controls in this method.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_Load(object sender, EventArgs e)
{
// The Page calls the OnLoad event method on the Page, then recursively does the
same for each child
// control, which does the same for each of its child controls until the page and all
controls are loaded.
// Use the OnLoad event method to set properties in controls and establish database

117

connections.
}
6. Control (PostBack) event(s)
ASP.NET now calls any events on the page or its controls that caused the PostBack to
occur. This might be a button's click event or a dropdown's selectedindexchange event,
for example.
These are the events, the code for which is written in your code-behind class (.cs file).
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Button1_Click(object sender, EventArgs e)
{
// This is just an example of control event.. Here it is button click event that caused
the postback
}
7. LoadComplete
This event signals the end of Load.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Use this event for tasks that require that all other controls on the page be loaded.
}
8. PreRender
Allows final changes to the page or its control. This event takes place after all regular
PostBack events have taken place. This event occurs before saving ViewState, so any
changes made here are saved.
For example: After this event, you cannot change any property of a button or change any
viewstate value. Because, after this event, the SaveStateComplete and Render events
are called.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected override void OnPreRender(EventArgs e)
{
// Each data bound control whose DataSourceID property is set calls its DataBind
method.
// The PreRender event occurs for each control on the page. Use the event to make
final
// changes to the contents of the page or its controls.
}
9. SaveStateComplete
Prior to this event the view state for the page and its controls is set. Any changes to the
page's controls at this point or beyond are ignored.

118

Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected override void OnSaveStateComplete(EventArgs e)
{
// Before this event occurs, ViewState has been saved for the page and for all
controls.
// Any changes to the page or controls at this point will be ignored.
// Use this event perform tasks that require view state to be saved, but that do not
make any changes to controls.
}
10. Render
This is a method of the page object and its controls (and not an event). At this point,
ASP.NET calls this method on each of the page's controls to get its output. The Render
method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML),
and script that are necessary to properly display a control at the browser.
Note: Right-click on the web page displayed in the client's browser and view the page's
source. You will not find any aspx server control in the code. Because all aspx controls are
converted to their respective HTML representation. The browser is capable of displaying
HTML and client-side scripts.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
// Render stage goes here. This is not an event
11. UnLoad
This event is used for cleanup code. After the page's HTML is rendered, the objects are
disposed of. During this event, you should destroy any objects or references you have
created in building the page. At this point, all processing has occurred and it is safe to
dispose of any remaining objects, including the Page object.
Cleanup can be performed on:
(a)Instances of classes in other words objects
(b)Closing opened files
(c)Closing database connections.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_UnLoad(object sender, EventArgs e)
{
// This event occurs for each control and then for the page. In controls, use this
event to do final cleanup
// for specific controls, such as closing control-specific database connections.
// During the unload stage, the page and its controls have been rendered, so you
cannot make further
// changes to the response stream.
//If you attempt to call a method such as the Response.Write method, the page will
throw an exception.
}
}
10. Request and response in IIS

119

When the client requests some information from a web server, the request first reaches
to HTTP.SYS of IIS. HTTP.SYS then sends the request to the respective Application Pool.
The Application Pool then forwards the request to the worker process to load the ISAPI
Extension that will create an HTTPRuntime Object to process the request via HTTPModule
and HTTPHanlder. After that the ASP.NET Page LifeCycle events start.
11. What are ADO.net objects ?
ADO.NET is designed to help developers work efficiently with multi tier databases, across
intranet or internet scenarios.
The ADO.NET object model consists of two key components as follows:

Connected model (.NET Data Provider: a set of components including the


Connection, Command, DataReader, and DataAdapter objects)

Disconnected model (DataSet).

Connection
The Connection object is the first component of ADO.NET. The connection object opens a
connection to your data source.
All of the configurable aspects of a database connection are represented in the
Connection object, that includes ConnectionString and ConnectionTimeout.
Connection object helps in accessing and manipulating a database. Database
transactions are also dependent upon the Connection object.
In ADO.NET the type of the Connection is dependent on what database system you are
working with. The following are the most commonly used for connections in ADO.NET:

SqlConnection

OleDbConnection

OdbcConnection

Command
The Command object is used to perform an action on the data source. The Command
object can execute Stored Procedures and T-SQL commands.
You can execute SQL queries to return data in a DataSet or a DataReader object. The
Command object performs the standard Select, Insert, Delete and Update T-SQL
operations.
DataReader
The DataReader is built as a way to retrieve and examine the rows returned in response
to your query as quickly as possible.
No DataSet is created; in fact, no more than one row of information from the data source
is in-memory at a time. This makes the DataReader very efficient at returning large
amounts of data.

120

The data returned by a DataReader is always read only. This class was built to be a
lightweight forward only, read only, way to run through data quickly (this was called a
Firehose cursor in ADO).
However, if you need to manipulate a schema or use some advanced display features
such as automatic paging then you must use a DataAdapter and DataSet.
A DataReader object works in the connected model.
DataAdapter
The DataAdapter takes the results of a database query from a Command object and
pushes them into a DataSet using the DataAdapter.Fill() method. Additionally the
DataAdapter.Update() method will negotiate any changes to a DataSet back to the
original data source.
A DataAdapter object works in a connected model. A DataAdapter performs the following
five steps:
1. Create/open the connection
2. Fetch the data as per command specified
3. Generate XML file of data
4. Fill data into DataSet.
5. Close connection.
Command Builder
It is used to save changes made in an in-memory cache of data on the backend. The
work of Command Builder is to generate a Command as per changes in DataRows.
Command Builder generates commands on the basis of row state. There are five row
states:
1. Unchanged
2. Added
3. Deleted
4. Modified
5. Detached
Command Builder works on add, delete and modified row state only.
Detached is used when an object is not created from row state.
Transaction
The Transaction object is used to execute a backend transaction. Transactions are used to
ensure that multiple changes to database rows occur as a single unit of work.
The Connection class has a BeginTransaction method that can be used to create a

121

Transaction.
A definite best practice is to ensure that transactions are placed in Using statements for
rapid cleanup if they are not committed. Otherwise the objects (and any internal locks
that may be needed) will remain active until the GC gets around to cleaning it up.
Parameters
A Parameter object is used to solve SQL Injection attack problems while dealing with the
user input parameters.
A Parameter object allows passing parameters into a Command object. The Parameter
class allows you to quickly put parameters into a query without string concatenation.
Note: See my other article on ADO.NET Objects Part II.
Conclusion
Hope the article has helped you to understand ADO.NET objects.
Your feedback and constructive contributions are welcome. Please feel free to contact
me for feedback or comments you may have about this article. ADO.NET is designed to
help developers work efficiently with multi-tier databases, across intranet or Internet
scenarios.
The ADO.NET object model consists of two key components as follows:

Connected model (.NET Data Provider: a set of components including the


Connection, Command, DataReader, and DataAdapter objects)

Disconnected model (DataSet).

DataSet
The DataSet Object is the parent object to most of the other objects in the System.Data
namespace. The DataSet is a disconnected, in-memory representation of data.
Its primary role is to store a collection of DataTables and the relations and constraints
between those DataTables.
DataSet also contains several methods for reading and writing XML, as well as merging
other DataSets, DataTables and DataRows.
Some of the advantages of the new DataSet object are:

Read / Write

Connectionless

Contains one or more DataTable objects with relationships defined in a collection


of DataRelation objects

Supports filtering and sorting

The contained DataView object can be bound to data-aware forms controls

Supports automatic XML serialization (creation of XML document)

122

DataTable
DataTable stores a table of information, typically retrieved from a data source. DataTable
allows you to examine the actual rows of a DataSet through rows and columns
collections.
Once the DataTable is filled the database connection is released and operates
disconnected only.
You can complex-bind a control to the information contained in a data table. Controls like
DataGrid are used for this purpose.
DataTable also stores metatable information such as the primary key and constraints.
DataRows
The DataRow class permits you to reference a specific row of data in a DataTable. This is
the class that permits you to edit, accept, or reject changes to the individual
DataColumns of the row.
You would use a DataRow object and its properties and methods to retrieve and evaluate
the values in a DataTable object.
The DataRowCollection represents the actual DataRow objects that are in the DataTable
object, and the DataColumnCollection contains the DataColumn objects that describe the
schema of the DataTable object.
DataColumns
DataColumns is the building block of the DataTable. A number of such objects make up a
table. Each DataColumn object has a DataType property that determines the kind of data
that the column is holding. data table.
DataColumn instances are also the class of object that you use to read and write
individual columns of a database. The Items property of a DataRow returns a
DataColumn.
DataView
A DataView is an object that provides a custom view of data in a DataTable. DataViews
provide sorting, filtering, and other types of customizations.
Each DataTable object has a DefaultView property, that holds the default DataView object
for that DataTable. Modifying the DefaultView object sets the default display
characteristics for the DataTable.
You can create an instance of a DataView and associate it with a specific DataTable in a
DataSet. This permits you to have two or more different views of the same DataTable
simultaneously available.
DataRelation
A DataRelation identifies that two or more of the DataTables in a DataSet contain data
related in a one-to-one or one-to-many (parent-child) association. You define a
relationship between two tables by adding a new DataRelation object to the DataSets.
Constraints
Each DataColumn may have multiple Constraints. Conditions such as unique are applied

123

through this class. Constraint objects are maintained through the DataTables Constraints
collection.
DataRowView
A DataRowView is a special object that represents a row in a DataView. Each DataView
can have a different RowStateFilter, the DataRowView obtained from a DataView will
contain data consistent with the DataView's RowStateFilter, providing a custom view of
the data.
12. What is the difference between Stored Procedures and functions?
1. Procedures can have input/output parameters for it whereas functions can have only
input parameters. 2. Procedure allows select as well as DML statement in it whereas a
function only allows select statements in it. 3. We can go for transaction management in
procedures whereas we can't for functions. 4. Procedures cannot be utilized in a select
statement whereas functions can be embedded in a select statement.
13. What is the difference between Stored Procedures and triggers?

The Stored Procedures are used for performing tasks

Stored Procedures normally used to performing user specified tasks. It can have the
parameters. It can return multiple results set.

The Triggers for auditing work

Triggers normally are used for auditing work. It can be used to trace the activities of the
table events.

The Stored Procedures can have the parameters

Procedures can have the input and output parameters with all the data types available in
the SQL Server as well as user defined data types.

The Triggers cannot have any parameters

Triggers cannot have any parameters.

Stored Procedure can be run independently

The Stored Procedures can be run independently. They are stored as a database object. It
can be called from the application.

The triggers executes based on table events

The DML triggers are get executed based on the table events defined on the specific
table. There are various types of triggers, like DML triggers, DDL triggers (from 2005
onwards) and logon triggers (from 2008 onwards).
The DDL triggers can control the Stored Procedures creation, drop and so on.

The Stored Procedure cannot call triggers

124

The Stored Procedures cannot call the triggers directly. But when we do the DML
operations on the table, if the corresponding table has the trigger then it will then be
triggered.

The triggers can call Stored Procedures

The triggers can call Stored Procedures.

14. Difference between DataSet and DataReader?


DataReader
DataReader reads data from a database. It only reads using a forward-only connection
oriented architecture during the fetching of the data from the database. A DataReader
will fetch the data very fast compared with a DataSet. Generally we will use an
ExecuteReader object to bind data to a DataReader.
To bind DataReader data to a GridView we need to write the code such as shown below:
Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location
FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}

Holds the connection open until you are finished (don't forget to close it!).

Can typically only be iterated over once

Is not as useful for updating back to the database

DataSet
DataSet is a disconnected oriented architecture. That means that there is no need for
active connections to work with DataSets and it is a collection of DataTables and relations
between tables. It holds multiple tables with data. You can select data form tables, create
views based on tables and ask child rows over relations. Also DataSet provides you with
rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
SqlConnection conn = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();

125

da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
DataAdapter
A DataAdapter will act as a bridge between a DataSet and the database. This
DataAdapter object reads the data from the database and binds that data to a DataSet.
DataAdapter is a disconnected oriented architecture. Check the following sample code to
see how to use a DataAdapter in code:
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}

Lets you close the connection as soon it's done loading data, and may even close
it for you automatically

All of the results are available in memory

You can iterate over it as many times as you need, or even look up a specific
record by index

Has some built-in faculties for updating back to the database.

DataTable
DataTable represents a single table in the database. It has rows and columns. There is
not much difference between DataSet and datatable, a DataSet is simply a collection of
datatables.
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview1.DataSource = dt;
gvidview1.DataBind();
}
15. Differnce between JavaScript jQuery and AJAX?

126

JavaScript
1. JavaScript is a client-side (in the browser) scripting language.
2. JavaScript lets you supercharge your HTML with animation, interactivity, and
dynamic visual effects
3. JavaScript can make web pages more useful by supplying immediate feedback.
4. JavaScript is the common term for a combination of the ECMAScript programming
language plus some means for accessing a web browser's windows and the
document object model (DOM).
5. JavaScript was designed to add interactivity to HTML pages
6. Everyone can use JavaScript without purchasing a license
jQuery
1. jQuery is a library/framework built with JavaScript.
2. It abstracts away cross-browser compatibility issues and it emphasises
unobtrusive and callback-driven JavaScript programming
3. jQuery (website) is a JavaScript framework that makes working with the DOM
easier by building many high level functionality that can be used to search and
interact with the DOM
4. jQuery implements a high-level interface to do AJAX requests
5. jQuery is a fast and concise JavaScript Library that simplifies HTML document
traversing, event handling, animating, and AJAX interactions for rapid web
development
Asynchronous JavaScript XML (AJAX)
1. Asynchronous JavaScript XML (AJAX) is a method to dynamically update parts of
the UI without having to reload the page, to make the experience more similar to
a Desktop application.
2. AJAX is a technique to do an XMLHttpRequest (out of band Http request) from a
web page to the server and send/retrieve data to be used on the web page
3. It uses JavaScript to construct an XMLHttpRequest, typically using various
techniques on various browsers.
4. AJAX is a set of functions of the language JavaScript
5. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook
tabs.
Why AJAX?
This is probably one of the most asked questions about AJAX.

127

The main advantage of using AJAX enabled ASP.NET Web applications is improved
efficiency and a reduction of the page refresh time. AJAX enables us to refresh only parts
of a Web page that have been updated, rather refreshing the entire page.
For example, if you have four controls on a web page, say a DropDownList, a TextBox, a
ListBox, and a GridView. The GridView control shows some data based on the selection in
a DropDownList and other controls. Now let's say a GridView also has paging and sorting
options. So whenever you move to the next page or apply a sort, the entire page and all
four controls on the page will be refreshed and you will notice a page flicker because
ASP.NET must render the entire page on the client-side and it happens once.
In an AJAX-enabled web page, you will see only the GridView data is being refreshed and
rest of the page and controls do not. Doing so, we not only get better performance and
faster refresh, we also get a better (or should I say "smoother") user experience.
You may want to see a live example of an AJAX enabled GridView on
our www.mindcracker.com web site in the Jobs section
here: http://www.mindcracker.com/Jobs/ . On this page, if you click on the "Next" page
link then you will see only the GridView data is being refreshed. We are also
implementing AJAX on C# Corner and other sites as well.
What Browsers Does AJAX Support?
AJAX is JavaScript based and supports most of the browsers including Internet
Explorer, Mozilla Firefox, and Apple Safari.
What are ASP.NET AJAX Extensions?
ASP.NET AJAX is a combination of client-script libraries (JavaScript) and ASP.NET server
components that are integrated to provide a robust development framework.
What are ASP.NET AJAX Server Controls?
The ASP.NET AJAX server controls consist of server and client code that integrate to
produce AJAX-like behavior. The following controls are available in the AJAX 1.0 library:
1. ScriptManager: Manages script resources for client components, partial-page
rendering, localization, globalization, and custom user scripts. The ScriptManager
control is required for the use of the UpdatePanel, UpdateProgress, and Timer
controls.
2. UpdatePanel: Enables you to refresh selected parts of the page instead of
refreshing the entire page by using a synchronous postback.
3. UpdateProgress: Provides status information about partial-page updates in
UpdatePanel controls.
4. Timer: Performs postbacks at defined intervals. You can use the Timer control to
post the entire page, or use it together with the UpdatePanel control to perform
partial-page updates at a defined interval.
What is the ASP.NET AJAX Control Toolkit?
The ASP.NET AJAX Control Toolkit is a collection of samples and components that show
you some of the experiences you can create with rich client ASP.NET AJAX controls and
extenders. The Control Toolkit provides both samples and a powerful SDK to simplify
creation and reuse of your custom controls and extenders. You can download the ASP.NET
AJAX Control Toolkit from the ASP.NET AJAX Web site.

128

16. What is the differnce between WCF and web services?


Web Service in ASP.NET
A Web Service is programmable application logic accessible via standard Web protocols.
One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C
submitted note (as of May 2000) that uses standards based technologies (XML for data
description and HTTP for transport) to encode and transmit application data.
Consumers of a Web Service do not need to know anything about the platform, object
model, or programming language used to implement the service; they only need to
understand how to send and receive SOAP messages (HTTP and XML).
WCF Service
Windows Communication Foundation (WCF) is a framework for building service-oriented
applications. Using WCF, you can send data as asynchronous messages from one service
endpoint to another. A service endpoint can be a part of a continuously available service
hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client
of a service that requests data from a service endpoint. The messages can be as simple
as a single character or word sent as XML, or as complex as a stream of binary data.
The following are the scenarios that WCF must be used in:

A secure service to process business transactions.

A service that supplies current data to others, such as a traffic reports or


other monitoring service.

A chat service that allows two people to communicate or exchange data in real
time.

A dashboard application that polls one or more services for data and presents it in
a logical presentation.

Exposing a workflow implemented using Windows Workflow Foundation as a WCF


service.

A Silverlight application to poll a service for the latest data feeds.

Features of WCF

Service Orientation

Interoperability

Multiple Message Patterns

Service Metadata

Data Contracts

Security

129

Multiple Transports and Encoding

Reliable and Queued Messages

Durable Messages

Transactions

AJAX and REST Support

Extensibility

Difference between a Web Service in ASP.NET & WCF Service


WCF is a replacement for all earlier web service technologies from Microsoft. It also
does much more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication
enabled through WCF. You will get a much higher degree of flexibility and portability
doing things in WCF than through traditional ASMX because WCF is designed, from the
ground up, to summarize all of the various distributed programming infrastructures
offered by Microsoft. An endpoint in WCF can be communicated with just as easily over
SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration
file modification. In theory, this reduces the amount of new code needed when porting or
changing business needs, targets, and so on.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically
you can see WCF as trying to logically group together all the various ways of getting two
apps to communicate in the world of Microsoft; ASMX was just one of these many ways
and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in a stateless environment,
whereas WCF is flexible because its services can be hosted in various types of
applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting and
Managed Windows Service.
The major difference is that Web Services use XmlSerializer. But WCF
uses DataContractSerializer that is better in performance than XmlSerializer.
Key issues with XmlSerializer to serialize .NET types to XML are:

Only Public fields or Properties of .NET types can be translated into XML

Only the classes that implement IEnumerable interface

Classes that implement the IDictionary interface, such as Hash table cannot be
serialized

Some important differences between DataContractSerializer and XMLSerializer are:

A practical benefit of the design of the DataContractSerializer is better


performance overXmlserializer.

XML Serialization does not indicate which fields or properties of the type are
serialized into XML whereasDataCotractSerializer

130

Explicitly shows the which fields or properties are serialized into XML

The DataContractSerializer can translate the HashTable into XML

Using the Code


The development of a web service with ASP.NET relies on defining data and relies on the
XmlSerializer to transform data to or from a service.
Key issues with XmlSerializer to serialize .NET types to XML:

Only Public fields or Properties of .NET types can be translated into XML

Only the classes that implement IEnumerable interface

Classes that implement the IDictionary interface, such as Hash table cannot be
serialized

The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW


types into XML.
Collapse | Copy Code
[DataContract]
public class Item
{
[DataMember]
public string ItemID;
[DataMember]
public decimal ItemQuantity;
[DataMember]
public decimal ItemPrice;
}
The DataContractAttribute can be applied to the class or a
strcture. DataMemberAttribute can be applied to a field or a property and theses fields or
properties can be either public or private.
Some important differences between DataContractSerializer and XMLSerializer are:

A practical benefit of the design of the DataContractSerializer is better


performance over XML serialization.

XML Serialization does not indicate which fields or properties of the type are
serialized into XML whereas DataContractSerializer explicitly shows which fields or
properties are serialized into XML.

The DataContractSerializer can translate the HashTable into XML.

Developing Service
To develop a service using ASP.NET, we must add the WebService attribute to the class
and WebMethodAttribute to any of the class methods.
Example
[WebService]

131

public class Service : System.Web.Services.WebService


{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
To develop a service in WCF, we will write the following code:
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
The ServiceContractAttribute specifies that an interface defines a WCF service contract,
OperationContract attribute indicates which of the methods of the interface defines the
operations of the service contract.
A class that implements the service contract is referred to as a service type in WCF.
Hosting the Service
ASP.NET web services are compiled into a class library assembly and a service file with
an extension .asmx will have the code for the service. The service file is copied into the
root of the ASP.NET application and Assembly will be copied to the bin directory. The
application is accessible using URL of the service file.
WCF Service can be hosted within IIS or WindowsActivationService as in the following:

Compile the service type into a class library

Copy the service file with an extension .SVC into a virtual directory and assembly
into bin sub directory of the virtual directory.

Copy the web.config file into the virtual directory.

Client Development
Clients for the ASP.NET Web services are generated using the command-line
tool WSDL.EXE.
WCF uses the ServiceMetadata tool (svcutil.exe) to generate the client for the service.
Message Representation
The Header of the SOAP Message can be customized in ASP.NET Web service.

132

WCF provides
attributes MessageContractAttribute, MessageHeaderAttribute andMessageBodyMember
Attribute to describe the structure of the SOAP Message.
Service Description
Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to
describe the service. It returns the WSDL as a response to the request.
The generated WSDL can be customized by deriving the class
of ServiceDescriptionFormatExtension.
Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL
that generated by WCF can be customized by using ServiceMetadataBehavior class.
Exception Handling
In ASP.NET Web services, unhandled exceptions are returned to the client as SOAP faults.
In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A
configuration setting is provided to have the unhandled exceptions returned to clients for
the purpose of debugging.
16. SOAP, WSDL, UDDI overview.
XML: Describes only data. So, any application that understands XML, regardless of the
application's programming language or platform, has the ability to format XML in a
variety of ways (well-formed or valid).
SOAP: Provides a communication mechanism between services and applications.
WSDL: Offers a uniform method of describing web services to other programs.
UDDI: Enables the creation of searchable Web services registries

Top 10 ASP.Net MVC Interview Questions


and Answers
1. Explain MVC (Model-View-Controller) in general?
Model-View-Controller (MVC) is an architectural software pattern that basically decouples
various components of a web application. By using the MVC pattern, we can develop
applications that are more flexible to changes without affecting the other components of
our application.

"Model",is basically domain data.

"View" is the user interface to render the domain data.

"Controller" translates user actions into appropriate operations performed on the


model.

2. What is ASP.NET MVC?

133

ASP.NET MVC is a web development framework from Microsoft that is based on the
Model-View-Controller (MVC) architectural design pattern. Microsoft has streamlined the
development of MVC based applications using the ASP.NET MVC Framework.
3. What are the differences between ASP.NET MVC and ASP.NET WebForms?
ASP.NET Web Forms use the Page Controller Pattern for rendering layout, whereas
ASP.NET MVC uses the Front Controller approach. In the case of the Page Controller
Pattern, every page has its own Controller, in other words a code-behind file that
processes the request. On the other hand, in ASP.NET MVC, a common Controller for all
pages processes the requests.
Follow the link for the difference between the ASP.NET MVC and ASP.NET WebForms.
4. What are the Core features of ASP.NET MVC?
The core features of the ASP.NET MVC Framework are:

Clear separation of application concerns (Presentation and Business Logic)

An extensible and pluggable framework

Extensive support for ASP.NET Routing

Support for existing ASP.NET features

Follow for detailed understanding of above mentioned core features.


5. Can you please explain the request flow in the ASP.NET MVC framework?
The request flow for the ASP.NET MVC Framework is as follows.
The request hits the Controller coming from the client. The Controller plays its role and
decides which model to use to serve the request, further passing that model to the View
that then transforms the model and generates an appropriate response that is rendered
to the client.
6. What is Routing in ASP.NET MVC?
In the case of a typical ASP.NET application, incoming requests are mapped to physical
files such as an .aspx file. The ASP.NET MVC Framework uses friendly URLs that more
easily describe the user's action but are not mapped to physical files.
The ASP.NET MVC Framework uses a routing engine that maps URLs to Controller classes.
We can define routing rules for the engine, so that it can map incoming request URLs to
the appropriate Controller.
Practically, when a user types a URL in a browser window for an ASP.NET MVC application
and presses the "go" button, the routing engine uses routing rules defined in the
Global.asax file to parse the URL and determine the path of the corresponding Controller.
7. What is the difference among ViewData, ViewBag and TempData?
To pass data from a Controller to a View and in a subsequent request, The ASP.NET MVC
Framework provides various options, in other words ViewData, ViewBag and TempData.
Both ViewBag and ViewData are used to to communicate between Controller and
corresponding View. But this communication is only for the server call, it becomes null if

134

the redirect occurs. So, in short, it's a mechanism to maintain state between Controller
and corresponding View.
ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0
feature). Since viewData is a dictionary object it is accessible using strings as keys and
also requires typecasting for complex types. On the other hand, ViewBag doesn't have
typecasting and null checks.
TempData is also a dictionary object that persists for the life of a HTTP Request. So,
Tempdata can be used to maintain data between redirects, in other words from one
Controller to another Controller.
8. What are Action Methods in ASP.NET MVC?
As previously stated about request flows in the ASP.NET MVC Framework, a request
coming from a client hits the Controller first. Actually the MVC application determines the
corresponding Controller using routing rules defined in Global.asax. And Controllers have
specific methods for each user actions. Each request coming to the Controller is for a
specific Action Method. The following code example, "ShowBooks" is an example of an
Action Method.
public ViewResult ShowBooks(int id)
{
var computerBook = db.Books.Where(p => P.BookID == id).First();
return View(computerBook);
}
9. Explain the role of Model in ASP.NET MVC?
One of the core features of ASP.NET MVC is that it separates the input and UI logic from
business logic. The role of the Model in ASP.NET MVC is to contain all application logic
including validation, business and data access logic except View. In other words input and
Controller; in other words UI logic.
The Model is normally responsible for accessing data from some persistent medium such
as a database and manipulates it.
10. What are Action Filters in ASP.NET MVC?
If we need to apply some specific logic before or after action methods then we use action
filters. We can apply these action filters to a Controller or a specific Controller action.
Action filters are basically custom classes that provide a way for adding pre-action or
post-action behavior to Controller actions.
For example:

An Authorize filter can be used to restrict access to a specific user or a role.

An OutputCache filter can cache the output of a Controller action for a specific
duration.

MVC 3 Interview Questions and Answers


Introduction
This article provides some interview questions and answers of MVC, basically covering
most of MVC 2, MVC 3 and MVC 4 topics that are more likely to be asked in job

135

interviews/tests/exams.
The sole purpose of this article is to sum up important questions and answers that can be
used by developers to brush-up on MVC before they go to an interview including it.
What is MVC?
MVC is a framework pattern that splits an application's implementation logic into three
component roles: models, views, and controllers.

Model: The business entity on which the overall application operates. Many
applications use a persistent storage mechanism (such as a database) to store
data. MVC does not specifically mention the data access layer because it is
understood to be encapsulated by the Model.

View: The user interface that renders the Model into a form of interaction.

Controller: Handles a request from a View and updates the Model that results in
a change of the Model's state.

To implement MVC in .NET we need mainly three classes (View, Controller and the
Model).
Explain MVC Architecture?

The architecture is self-explanatory. The browser (as usual) sends a request to IIS, IIS
searches for the route defined in the MVC application and passes the request to the
controller as specified by the route, the controller communicates with the model and
passes the populated model (entity) to View (front end), Views are populated with model
properties, and are rendered on the browser, passing the response to the browser
through IIS via controllers that invoked the specified View.
What are the new features of MVC 2?
ASP.NET MVC 2 was released in March 2010. Its main features are:

Introduction of UI helpers with automatic scaffolding with customizable templates.

Attribute-based model validation on both client and server.

Strongly typed HTML helpers.

Improved Visual Studio tooling.

136

There were also many API enhancements and "pro" features, based on feedback
from developers building a variety of applications on ASP.NET MVC 1, such as:

Support for partitioning large applications into areas.

Asynchronous controllers support.

Support for rendering subsections of a page/site using Html.RenderAction.

Many new helper functions, utilities, and API enhancements.

What are the new features of MVC 3?


ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011. Some of the top features
in MVC 3 included:

The Razor view engine.

Support for .NET 4 Data Annotations.

Improved model validation

Greater control and flexibility with support for dependency resolution and global
action filters.

Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON
binding.

Use of NuGet to deliver software and manage dependencies throughout the


platform.

What are the new features of MVC 4?


The following are the top features of MVC 4:

ASP.NET Web API.

Enhancements to default project templates.

Mobile project template using jQuery Mobile.

Display Modes.

Task support for Asynchronous Controllers.

Bundling and minification.

Explain "page lifecycle" of ASP.NET MVC


The following processes are performed by ASP.NET MVC page::
1. App initialization

137

2. Routing
3. Instantiate and execute controller
4. Locate and invoke controller action
5. Instantiate and render view
Advantages of MVC Framework
1. Provides a clean separation of concerns among UI (Presentation layer), model
(Transfer objects/Domain Objects/Entities) and Business Logic (Controller).
2. Easy to UNIT Test.
3. Improved reusability of views/model. One can have multiple views that can point
to the same model and vice versa.
4. Improved structuring of the code.
What is meant by Separation of Concerns?
As per Wikipedia 'the process of breaking a computer program into distinct features that
overlap in functionality as little as possible'. The MVC design pattern aims to separate
content from presentation and data-processing from content.
Where do we see Separation of Concerns in MVC?
Between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separate. The
views are just the presentation form of an application, it does not need to know
specifically about the requests coming from the controller. The Model is independent of
View and Controllers, it only holds business entities that can be passed to any View by
the controller as required for exposing them to the end user. The controller is
independent of Views and Models, its sole purpose is to handle requests and pass it on as
per the routes defined and as per the need of rendering the views. Thus our business
entities (model), business logic (controllers) and presentation logic (views) lie in
logical/physical layers independent of each other.
What is Razor View Engine?
Razor is the first major update to render HTML in MVC 3. Razor was designed specifically
as a view engine syntax. It has one main focus: code-focused templating for HTML
generation. Here's how that same markup would be generated using Razor:
@model MvcMusicStore.Models.Genre
@{ViewBag.Title = "Browse Albums";}
<div class="genre">
<h3><em>@Model.Name</em> Albums</h3>
<ul id="album-list">
@foreach (var album in Model.Albums)
{
<li>
<a href="@Url.Action("Details", new { id = album.AlbumId })">
<img alt="@album.Title" src="@album.AlbumArtUrl" />
<span>@album.Title</span>
</a>

138

</li>
}
</ul>
</div>
The Razor syntax is easier to type, and easier to read. Razor doesn't have the XML-like
heavy syntax of the Web Forms view engine.
What is Unobtrusive JavaScript?
Unobtrusive JavaScript is a general term that conveys a general philosophy, similar to the
term REST (Representational State Transfer). The high-level description is that
unobtrusive JavaScript doesn't intermix JavaScript code in your page markup. For
example, rather than hooking in via event attributes like onclick and onsubmit, the
unobtrusive JavaScript attaches to elements by their ID or class, often based on the
presence of other attributes (such as HTML5 data-attributes).
It's got semantic meaning and all of it; the tag structure, element attributes and so on
should have a precise meaning. Strewing JavaScript gunk across the page to facilitate
interaction (I'm looking at you, -doPostBack!) harms the content of the document.
What is JSON Binding?
MVC 3 included JavaScript Object Notation (JSON) binding support via the new
JsonValueProviderFactory, enabling the action methods to accept and model-bind data in
JSON format. This is especially useful in advanced Ajax scenarios like client templates
and data binding that need to post data back to the server.
What is Dependency Resolution?
MVC 3 introduced a new concept called a dependency resolver, that greatly simplified
the use of dependency injection in your applications. This made it easier to decouple
application components, making them more configurable and easier to test.
Support was added for the following scenarios:

Controllers (registering and injecting controller factories, injecting controllers)

Views (registering and injecting view engines, injecting dependencies into view
pages)

Action filters (locating and injecting filters)

Model binders (registering and injecting)

Model validation providers (registering and injecting)

Model metadata providers (registering and injecting)

Value providers (registering and injecting)

What are Display Modes in MVC 4?


Display modes use a convention-based approach to allow selecting various views based
on the browser making the request. The default view engine first looks for views with
names ending with ".Mobile.cshtml" when the browser's user agent indicates a known
mobile device. For example, if we have a generic view titled "Index.cshtml" and a mobile

139

view titled "Index.Mobile.cshtml" then MVC 4 will automatically use the mobile view when
viewed in a mobile browser.
Additionally, we can register your own custom device modes that will be based on your
own custom criteria, all in just one code statement. For example, to register a WinPhone
device mode that would serve views ending with ".WinPhone.cshtml" to Windows Phone
devices, you'd use the following code in the Application_Start method of your
Global.asax:
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("WinPhone")
{
ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf
("Windows Phone OS", StringComparison.OrdinalIgnoreCase) >= 0)
});
What is AuthConfig.cs in MVC 4?
"AuthConfig.cs" configures security settings, including sites for OAuth login.
What is BundleConfig.cs in MVC 4?
"BundleConfig.cs" in MVC4 registers bundles used by the bundling and minification
system. Several bundles are added by default, including jQuery, jQueryUI, jQuery
validation, Modernizr, and default CSS references.
What is FilterConfig.cs in MVC 4?
This is used to register global MVC filters. The only filter registered by default is the
HandleErrorAttribute, but this is a great place to put other filter registrations.
What is RouteConfig.cs in MVC 4?
"RouteConfig.cs" holds the granddaddy of the MVC config statements and Route
configuration.
What is WebApiConfig.cs in MVC 4?
Used to register Web API routes, as well as set any additional Web API configuration
settings.
What's new for adding a controller in a MVC 4 application?
Previously (in MVC 3 and MVC 2), the Visual Studio Add Controller menu item only
displayed when we right-clicked on the Controllers folder. However, the use of the
Controllers folder was purely for organization. (MVC will recognize any class that
implements the IController interface as a Controller, regardless of its location in your
application.) The MVC 4 Visual Studio tooling has been modified to display the Add
Controller menu item for any folder in your MVC project. This allows us to organize
controllers however you would like, perhaps separating them into logical groups or
separating MVC and Web API controllers.
What are the software requirements of an ASP.NET MVC 4 application?
MVC 4 runs on the following Windows client operating systems:

Windows XP

Windows Vista

140

Windows 7

Windows 8

It runs on the following server operating systems:

Windows Server 2003

Windows Server 2008

Windows Server 2008 R2

MVC 4 development tooling is included with Visual Studio 2012 and can be installed on
Visual Studio 2010 SP1/Visual Web Developer 2010 Express SP1.
What are the various types of Application Templates used to create an MVC application?
The various templates are as follows:
1. The Internet Application template: This contains the beginnings of an MVC
web application, enough that you can run the application immediately after
creating it
and see a few pages. This template also includes some basic account
management functions that run against the ASP.NET Membership.

2. The Intranet Application template: The Intranet Application template was


added as part of the ASP.NET MVC 3 Tools Update. It is similar to the Internet
Application template, but the account management functions run against
Windows accounts rather than the ASP.NET Membership system.

3. The Basic template: This template is pretty minimal. It still has the basic
folders, CSS, and MVC application infrastructure in place, but no more. Running an
application created using the Empty template just gives you an error message.
Why use Basic template? The Basic template is intended for experienced MVC
developers who want to set up and configure things exactly how they want them.

4. The Empty template: The Basic Template was previously called the Empty
Template, but developers complained that it wasn't quite empty enough. With
MVC 4, the previous Empty
Template was renamed Basic, and the new Empty Template is about as empty as
possible.
It has the assemblies and basic folder structure in place, but that's about it.

5. The Mobile Application template: The Mobile Application template is


preconfigured with jQuery Mobile to jump-start creating a mobile only website. It
includes mobile visual themes, a touch-optimized UI, and support for Ajax
navigation.

141

6. The Web API template: The ASP.NET Web API is a framework for creating HTTP
services.
The Web API template is similar to the Internet Application template but is
streamlined for Web API development. For instance, there is no user account
management functionality, since Web API account management is often
significantly different from standard MVC account management. Web API
functionality is also available in the other MVC project templates, and even in nonMVC project types.
What are the default Top-level directories created when adding a MVC 4
application?
The default Top-level directories are:

/Controllers: For Controller classes that handle URL requests

/Models: For classes that represent and manipulate data and business objects

/Views: For UI template files that are responsible for rendering output like HTML

/Scripts: For JavaScript library files and scripts (.js)

/Images: For images used in your site

/Content: For CSS and other site content, other than scripts and images

/Filters: For code filters

/App_Data: To store data files you want to read/write

/App_Start: For configuration code of features like Routing, Bundling, Web API.

What is namespace of ASP.NET MVC?


ASP.NET MVC namespaces as well as classes are located in assembly System.Web.Mvc.
Note: Some of the content has been taken from various books/articles.
What is System.Web.Mvc namespace?
This namespace contains classes and interfaces that support the MVC pattern for
ASP.NET Web applications. This namespace includes classes that represent controllers,
controller
factories, action results, views, partial views, and model binders.
What is System.Web.Mvc.Ajax namespace?
The System.Web.Mvc.Ajax namespace contains classes that support Ajax scripting in an
ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax
option settings as well.
What is System.Web.Mvc.Async namespace?
The System.Web.Mvc.Async namespace contains classes and interfaces that support
asynchronous actions in an ASP.NET MVC application.

142

What is System.Web.Mvc.Html namespace?


The System.Web.Mvc.Html namespace contains classes that help render HTML controls in
an MVC application. This namespace includes classes that support forms, input controls,
links, partial views, and validation.
What is ViewData, ViewBag and TempData?
MVC provides ViewData, ViewBag and TempData for passing data from the controller,
view and in subsequent requests as well. ViewData and ViewBag are similar to some
extent but TempData performs additional roles.
What are the roles and similarities between ViewData and ViewBag?

Maintains data when moving from controller to view.

Passes data from the controller to the respective view.

Their value becomes null when any redirection occurs, because their role is to
provide a way to communicate between controllers and views. It's a
communication mechanism within the server call.

What are the differences between ViewData and ViewBag (taken from a blog)?

ViewData is a dictionary of objects derived from the ViewDataDictionary class and


accessible using strings as keys.

ViewBag is a dynamic property that takes advantage of the new dynamic features
in C# 4.0.

ViewData requires typecasting for complex data types and checks for null values
to avoid error.

ViewBag doesn't require typecasting for complex data types.

NOTE: Although there might not be a technical advantage to choosing one format over
the other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a
valid C# identifier. For example, if you place a value in ViewData["KeyWith Spaces"] then
you can't access that value using ViewBag because the code won't compile.
Another key issue to be aware of is that dynamic values cannot be passed in as
parameters to extension methods. The C# compiler must know the real type of every
parameter at compile time in order for it to choose the correct extension method.
If any parameter is dynamic then compilation will fail. For example, this code will always
fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use
ViewData["Name"] or cast the value to a specifi c type: (string) ViewBag.Name.
What is TempData?
TempData is a dictionary derived from the TempDataDictionary class and stored in a
short-lived session. It is a string key and object value.
It maintains the information for the duration of an HTTP Request. This means only from
one page to another. It helps to maintain data when we move from one controller to

143

another controller or from one action to another action. In other words, when we redirect
Tempdata, it helps to maintain the data between those redirects. It internally uses
session variables. Temp data used during the current and subsequent request only
means it is used when we are sure that the next request will be redirecting to the next
view. It requires typecasting for complex data types and checks for null values to avoid
errors. Generally it is used to store only one-time messages, like error messages and
validation messages.
How can you define a dynamic property using viewbag in ASP.NET MVC?
Assign a key name with the syntax "ViewBag.[Key]=[ Value]" and value using the equal
to operator.
For example, you need to assign a list of students to the dynamic Students property of
ViewBag as in the following:
List<string> students = new List<string>();
countries.Add("Akhil");
countries.Add("Ekta");
ViewBag.Students = students;
//Students is a dynamic property associated with ViewBag.
Note: Some of the content has been taken from various books/articles.
What is ViewModel (taken from stackoverflow)?
Accepted A view model represents data that you want to have displayed on your
view/page.
Let's say that you have an Employee class that represents your employee domain model
and it contains the following 4 properties:
public class Employee : IEntity
{
public int Id { get; set; } // Employee's unique identifier
public string FirstName { get; set; } // Employee's first name
public string LastName { get; set; } // Employee's last name
public DateTime DateCreated { get; set; } // Date when employee was created
}
View models differ from domain models in that view models only contain the data
(represented by properties) that you want to use on your view. For example, let's say that
you want to add a new employee record, your view model might look like this:
public class CreateEmployeeViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
As you can see it only contains 2 of the properties of the employee domain model. Why is
this you may ask? Id might not be set from the view and it might be auto-generated by
the Employee table. And DateCreated might also be set in the Stored Procedure or in the
service layer of your application. So Id and DateCreated is not needed in the view model.
When loading the view/page, the create action method in your employee controller will
create an instance of this view model, populate any fields if required, and then pass this
view model to the view:

144

public class EmployeeController : Controller


{
private readonly IEmployeeService employeeService;
public EmployeeController(IEmployeeService employeeService)
{
this.employeeService = employeeService;
}
public ActionResult Create()
{
CreateEmployeeViewModel viewModel = new CreateEmployeeViewModel();
return View(viewModel);
}
public ActionResult Create(CreateEmployeeViewModel viewModel)
{
// Do what ever needs to be done before adding the employee to the database
}
}
Your view might look like this (assuming you are using ASP.NET MVC3 and razor):
@model MyProject.Web.ViewModels.ProductCreateViewModel
<table>
<tr>
<td><b>First Name:</b></td>
<td>@Html.TextBoxFor(x => x.FirstName, new { maxlength = "50", size = "50" })
@Html.ValidationMessageFor(x => x.FirstName)
</td>
</tr>
<tr>
<td><b>Last Name:</b></td>
<td>@Html.TextBoxFor(x => x.LastName, new { maxlength = "50", size = "50" })
@Html.ValidationMessageFor(x => x.LastName)
</td>
</tr>
</table>
Validation would thus be done only on FirstName and LastName. Using Fluent Validation
you might have validation like this:
public class CreateEmployeeViewModelValidator :
AbstractValidator<CreateEmployeeViewModel>
{
public CreateEmployeeViewModelValidator()
{
RuleFor(x => x.FirstName)
.NotEmpty()
.WithMessage("First name required")
.Length(1, 50)
.WithMessage("First name must not be greater than 50 characters");
RuleFor(x => x.LastName)
.NotEmpty()
.WithMessage("Last name required")
.Length(1, 50)
.WithMessage("Last name must not be greater than 50 characters");
}
}
The key thing to remember is that the view model only represents the data that you want
to use. You can imagine all the unnecessary code and validation if you have a domain

145

model with 30 properties and you only want to update a single value. Given this scenario
you would only have this one value/property in the view model and not the entire domain
object.
How do you check for AJAX requests with C# in MVC.NET?
The solution is independed of the MVC.NET framework and is global across server side
technologies. Most modern AJAX applications utilize XmlHTTPRequest to send async
requests to the server. Such requests will have a distinct request header:
X-Requested-With = XMLHTTPREQUEST

MVC.NET provides helper functions to check for ajax requests that internally inspects the
"X-Requested-With" request header to set the "IsAjax" flag.
What are Scaffold templates?
These templates use the Visual Studio T4 templating system to generate a view based on
the model type selected. Scaffolding in ASP.NET MVC can generate the boilerplate code
we need to create, read, update, and delete (CRUD) functionality in an application. The
scaffolding templates can examine the type definition for it then generate a controller
and the controller's associated views. The scaffolding knows how to name controllers,
how to name views, what code needs to go to each component, and where to place all
these pieces in the project for the application to work.
What are the types of Scaffolding Templates?

Empty: Creates an empty view. Only the model type is specified using the model
syntax.

Create: Creates a view with a form for creating new instances of the model.
Generates a label and input field for each property of the model type.

Delete: Creates a view with a form for deleting existing instances of the model.
Displays a label and the current value for each property of the model.

Details: Creates a view that displays a label and the value for each property of
the model type.

Edit: Creates a view with a form for editing existing instances of the model.
Generates a label and input field for each property of the model type.

146

List: Creates a view with a table of model instances. Generates a column for
each property of the model type. Make sure to pass an
IEnumerable<YourModelType> to this view from your action method.

The view also contains links to actions for performing the create/edit/delete operations.
Show an example of the difference in syntax in Razor and WebForm Views
Razor <span>@model.Message</span>
Web Forms <span><%: model.Message %></span>
Code expressions in Razor are always HTML encoded. This Web Forms syntax also
automatically HTML encodes the value.
What are Code Blocks in Views?
Unlike code expressions that are evaluated and sent to the response, blocks of code are
simply sections of code that are executed. They are useful for declaring variables that we
may need to use later.
Razor
@{
int x = 123;
string y = because.;
}
Web Forms
<%
int x = 123;
string y = "because.";
%>
What is the "HelperPage.IsAjax" Property?
The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used
during the request of the Web page.
Namespace: System.Web.WebPages
Assembly: System.Web.WebPages.dll
However, the same can be done by checking request headers directly:
Request["X-Requested-With"] == "XmlHttpRequest".
Explain combining text and markup in Views using an example
This example shows what intermixing text and markup looks like using Razor as
compared to Web Forms:
Razor
@foreach (var item in items) {
<span>Item @item.Name.</span>
}
Web Forms

147

<% foreach (var item in items) { %>


<span>Item <%: item.Name %>.</span>
<% } %>
Explain Repository Pattern in ASP.NET MVC
In simple terms, a repository basically works as a mediator between our business logic
layer and our data access layer of the application. Sometimes it would be troublesome to
expose the data access mechanism directly to the business logic layer, it may result in
redundant code for accessing data for similar entities or it may result in code that is hard
to test or understand. To overcome these kinds of issues, and to write interface driven
and test driven code to access data, we use the Repository Pattern. The repository makes
queries to the data source for the data then maps the data from the data source to a
business entity/domain object and finally persists the changes in the business entity to
the data source. According to MSDN, a repository separates the business logic from the
interactions with the underlying data source or Web Service. The separation between the
data and business tiers has the following three benefits:

It centralizes the data logic or Web service access logic.

It provides a substitution point for the unit tests.

It provides a flexible architecture that can be adapted as the overall design of the
application evolves.

In a Repository we write our entire business logic of CRUD operations using Entity
Framework classes that will not only result in meaningful test driven code but will also
reduce our controller code of accessing data.
How can you call a JavaScript function/method on the change of a Dropdown
List in MVC?
Create a JavaScript method:
<script type="text/javascript">
function selectedIndexChanged() {
}
</script>
Invoke the method:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Users, "Value", "Text"),
"Please Select a User", new { id = "ddlUsers",
onchange="selectedIndexChanged()" })%>
Explain Routing in MVC
A route is a URL pattern that is mapped to a handler. The handler can be a physical file,
such as an .aspx file in a Web Forms application. A Routing module is responsible for
mapping incoming browser requests to specific MVC controller actions.
Routing within the ASP.NET MVC framework serves the following two main purposes:

It matches incoming requests that would not otherwise match a file on the file
system and maps the requests to a controller action.

148

It constructs outgoing URLs that correspond to controller actions.

How is a route table created in ASP.NET MVC?


When an MVC application first starts, the Application_Start() method in global.asax is
called. This method calls the RegisterRoutes() method. The RegisterRoutes() method
creates the route table for the MVC application.
What are Layouts in ASP.NET MVC Razor?
Layouts in Razor help maintain a consistent look and feel across multiple views within our
application. Compared to Web Forms Web Forms, layouts serve the same purpose as
master pages, but offer both a simpler syntax and greater flexibility.
We can use a layout to define a common template for your site (or just part of it). This
template contains one or more placeholders that the other views in your application
provide content for. In some ways, it's like an abstract base class for your views. For
example declared at the top of view as in the following:
@{
Layout = "~/Views/Shared/SiteLayout.cshtml";
}
What is ViewStart?
For group of views that all use the same layout, this can get a bit redundant and harder
to maintain.
The "_ViewStart.cshtml" page can be used to remove this redundancy. The code within
this file is executed before the code in any view placed in the same directory. This file is
also recursively applied to any view within a subdirectory.
When we create a default ASP.NET MVC project, we find there is already a "_ViewStart
.cshtml" file in the Views directory. It specifies a default layout as in the following:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Because this code runs before any view, a view can override the Layout property and
choose a different one. If a set of views shares common settings then the
"_ViewStart.cshtml" file is a useful place to consolidate these common view settings. If
any view needs to override any of the common settings then the view can set those
values to another value.
Note: Some of the content has been taken from various books/articles.
What are HTML Helpers?
HTML helpers are methods we can invoke on the Html property of a view. We also have
access to URL helpers (via the URL property) and AJAX helpers (via the Ajax property). All
these helpers have the same goal, to make views easy to author. The URL helper is also
available from within the controller.
Most of the helpers, particularly the HTML helpers, output HTML markup. For example,
the BeginForm helper is a helper we can use to build a robust form tag for our search
form, but without using lines and lines of code:
@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {

149

<input type="text" name="q" />


<input type="submit" value="Search" />
}
What is Html.ValidationSummary?
The ValidationSummary helper displays an unordered list of all validation errors in the
ModelState dictionary. The Boolean parameter you are using (with a value of true) is
telling the helper to exclude property-level errors. In other words, you are telling the
summary to display only the errors in ModelState associated with the model itself, and
exclude any errors associated with a specific model property. We will be displaying
property-level errors separately. Assume you have the following code somewhere in the
controller action rendering the edit view:
ModelState.AddModelError("", "This is all wrong!");
ModelState.AddModelError("Title", "What a terrible name!");
The first error is a model-level error, because you didn't provide a key (or provided an
empty key) to associate the error with a specific property. The second error you
associated with the Title property, so in your view it will not display in the validation
summary area (unless you remove the parameter to the helper method, or change the
value to false). In this scenario, the helper renders the following HTML:
<div class="validation-summary-errors">
<ul>
<li>This is all wrong!</li>
</ul>
</div>
Other overloads of the ValidationSummary helper enable you to provide header text and
set specific HTML attributes.
NOTE: By convention, the ValidationSummary helper renders the CSS class validationsummary-errors along with any specific CSS classes you provide. The default MVC project
template includes some styling to display these items in red, that you can change in
"styles.css".
What are Validation Annotations?
Data annotations are attributes you can find in the
"System.ComponentModel.DataAnnotations" namespace. These attributes provide
server-side validation, and the framework also supports client-side validation when you
use one of the attributes on a model property. You can use four attributes in the
DataAnnotations namespace to cover the common validation scenarios, Required, String
Length, Regular Expression and Range.
What is Html.Partial?
The Partial helper renders a partial view into a string. Typically, a partial view contains
reusable markup you want to render from inside multiple different views. Partial has four
overloads:
public void Partial(string partialViewName);
public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,
ViewDataDictionary viewData);
What is Html.RenderPartial?

150

The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the
response output stream instead of returning a string. For this reason, you must place
RenderPartial inside a code block instead of a code expression. To illustrate, the following
two lines of code render the same output to the output stream:
@{Html.RenderPartial("AlbumDisplay "); }
@Html.Partial("AlbumDisplay ")
If they are same then which one to use?
In general, you should prefer Partial to RenderPartial because Partial is more convenient
(you don't need to wrap the call in a code block with curly braces). However,
RenderPartial may result in better performance because it writes directly to the response
stream, although it would require a lot of use (either high site traffic or repeated calls in a
loop) before the difference would be noticeable.
How do you return a partial view from controller?
return PartialView(options); //options could be Model or View name

What are various ways of returning a View?

There are various ways for returning/rendering a view in MVC Razor. For example "return
View()", "return RedirectToAction()", "return Redirect()" and "return RedirectToRoute()".

Conclusion

I hope we covered many of questions to brush-up. Since MVC is very vast now, I know we
have missed a lot stuff too. The content in the question and answer form is also taken
from few renowned books like Professional ASP.NET MVC4 from Wrox and a few of the
content is taken from my MVC articles posted earlier. My future articles will provide
interview questions for EntityFramework too.

SQL Queries asked during Interviews


et me share share some of the Sql questions I have been asked during
interviews.
1. Random Record
Select Random Records From Table

151

Select top 1 * from Table order by newId()


2. Max Amount without Order by
Consider a table having a column say amount, write a query to get
maximum amount without using order by and max keyword.
1.Declare @MaxValue int
Select @MaxValue=(case when @MaxValue>Amount then
@MaxValue else Amount end) From T1 Select @Maxvalue
2.Declare @MaxValue int
Select @MaxValue=Amount From T1 Group by Amount
Select @MaxValue
3.SELECT T11.Id,T11.Amount as MaxAmount
FROM T1 AS T11 left outER JOIN
T1 AS T12 ON T11.Amount < T12.Amount
GROUP BY T11.Amount, T11.Id
having COUNT(T12.Amount)=0

3. Swap Column Values


Consider you have table Say TblEmployee with a column say
EmployeeName which contain Records as A,B,A,A,B,C,B,C,A your task is
to write a query which will change the EmployeeName A to B and B to A.

update TblEmployee
set EmpName = (CASE
WHEN EmpName='A' THEN 'B'
WHEN EmpName='B' THEN 'A'
ELSE EmpName
END)
4. Get the nth Largest
Consider you have a table TblEmployee with columns EmployeeName
and Salary. Find the third largest salary.

1. Select min(Salary) from


(Select top 3
Salary From TblEmployee order by Salary desc) TempEmployee
152

2. Select Top 1 EmployeeName,Salary from


(Select Top 3
EmployeeName,Salary From TblEmployee order by Salary desc) TblTempE
mployeeorder by Salary
5. Top N from Each Group
Consider a table Student with columns StudenId,Marks,Standard.
Find the Top 3 Students from Each Standard.
With MyTempView
(
StudentId varchar(40),
Standard varchar(max),
TotalMarks int,
RowIndex int
)
as
(
Select *,row_number () over (partition by Standard order by TotalMar
ks desc)
)
Select StudentId,Standard,TotalMarks From MyTEmpView where RowIn
dex<=3

6. Shadow copy using Sql


Write a query to create a clone of existing table without using Create
Command.
(Data will not be copied).

Select top 0 * into NewTable From ExistingTable.

7. Delete Duplicate Records


What will be the query to delete duplicate records in a table.

153

1. Delete b1
from BookIssue b1
join BookIssue b2
on b1.id>b2.id and b1.Book=b2.Book

2. Incase table deosnt have identity column


Select distinct Book into #Temp from BookIssue
Truncate Table BookIssue
Insert into BookIssue
Select Book From #Temp

Hope to see some good comments, some questions from seniors.


C#.NET Interview Questions And answers for Experienced

Question.1 What are implementation inheritance and interface


inheritance?
Answer: Implementation inheritance is achieved when a class is derived from
another class in such a way that it inherits all its members. Interface inheritance is
when a class inherits only the signatures of the functions from another class.
Question.2 What are generics in C#.NET?
Answer:
Generic types to maximize code reuse, type safety, and performance.
They can be used to create collection classes. Generic collection classes in the
System.Collections.Generic namespace should be used instead of classes such as
ArrayList in the System.Collections namespace.
Question.3 What is the use of GetCommandLineArgs() method in
C#.NET?
Answer:
With GetCommandLineArgs() method, the command line arguments
can be accessed. The value returned is an array of strings.
Question.4 What is the use of System.Environment class in
C#.NET?
Answer: The System.Environment class can be used to retrieve information like
command-line arguments, the exit code, environment variable settings, contents of
the call stack, time since last system boot, the version of the common language
runtime.
154

Question.5 What is an Exception in .NET?


Answer: Exceptions are errors that occur during the runtime of a program. The
advantage of using exceptions is that the program doesnt terminate due to the
occurrence of the exception. Whenever an exception is occurred the .NET runtime
throws an object of specified type of Exception. The class Exception is the base
class of all the exceptions..
Question.6 What are Custom Exceptions?
Answer: Custom Exceptions are user defined exceptions.
Question.7 What is a Constructor?
Answer: It is the first method that are called on instantiation of a type. It provides
way to set default values for data before the object is available for use. Performs
other necessary functions before the object is available for use.
Question.8 Can private virtual methods be overridden in C#.NET?
Answer: No, moreover, you cannot access private methods in inherited classes.
They have to be protected in the base class to allow any sort of access.
Question.9 Is is possible to force garbage collector to run?
Answer: Yes, we can force garbage collector to run using System.GC.Collect().
Question.10 What is an Event?
Answer: When an action is performed, this action is noticed by the computer
application based on which the output is displayed. These actions are called events.
Examples of events are pressing of the keys on the keyboard, clicking of the mouse.
Likewise, there are a number of events which capture your actions.
Question.11 What is Delegate?
Answer: Delegates are kind of similar to the function pointers. But they are
secure and type-safe. A delegate instance encapsulates a static or an instance
method. Declaring a delegate defines a reference type which can be used to
encapsulate a method having a specific signature.
Question.12 How does object pooling and connection pooling
differ?
Answer:
In Object pooling, you can control the number of connections. In
connection pooling, you can control the maximum number reached. When using
connection pooling, if there is nothing in the pool, a connection is created since the
creation is on the same thread. In object pooling, the pool decides the creation of an
object depending on whether the maximum is reached which in case if it is, the next
available object is returned. However, this could increase the time complexity if the
object is heavy.
Question.13 What is Language Integrated Query (LINQ)?
Answer: LINQ is a set of extensions to .NET Framework that encapsulate
language integrated query, set and other transformation operations. It extends VB,
C# with their language syntax for queries. It also provides class libraries which allow
a developer to take advantages of these features.

155

Question.14 Explain the purpose of CultureInfo class. What


namespace contains it?
Answer: System.Globalization namespace contains CultureInfo class. This class
provides information about a specific culture, i.e. datetime format, currency,
language etc.
Question.15 Which is the class from where everything is derived
in .NET?
Answer: System.Object. Object class is the ultimate base class of all classes in
the .NET Framework, it is the root of the type hierarchy. It is often used as a generic
argument in class methods all classes are treatable as Object classes.
Question.16 What is the use of assert() method?
Answer: Assert method is in debug compilation. It takes a boolean condition as a
parameter. It shows error dialog if the condition is false and if the condition is true,
the program proceeds without interruption.
Question.17 Difference between the System.Array.CopyTo() and
System.Array.Clone()?
Answer: System.Array.CopyTo() performs a deep copy of the array.
System.Array.Clone() performs a shallow copy of the array
Question.18 What is the purpose of Dispose method?
Answer: Dispose method is used to destroy the objects from the memory.
Question.19 What is the difference between shadow and
override?
Answer: In general when you extend a class you shadow fields with the same
name in the base class and override virtual methods with the same name and
parameter list in the base class. Overriding makes the base class method invisible.
Shadowing a field only hides the field from view. You can still explicitly touch the
hidden shadowed field if you wish. You cannot touch an invisible overridden method.

Interview Questions in ASP.NET,C#.NET,SQL


Server,.NET Framework
Here I am posting the interview questions whatever i have faced in my interviews
I have searched for so many websites and gathered information from my friends to
answer the questions perfectly.
i think these questions are very helpful for the people who are trying to get the job on
.NET
The most common question for experience persons is
Why would you like to change the company?
1) I am looking for a more challenging career in a firm with a larger employee base such
as yours.
2) Keeping in mind my career goals, the time has come for me to move onto the next
rung of
the ladder and make a mark for myself. This can be achieved in a company like this.

156

3) It is just a career move to enhance my knowledge in my own area of interest.


After completion of this question only interview will go for further questions
Difference between stored procedure and function
1) Procedure can return zero or n values whereas function can return one value which is
mandatory.
2) Procedures can have input, output parameters for it whereas functions can have only
input parameters.
3) Procedure allows select as well as DML statement in it whereas function allows only
select statement in it.
4) Functions can be called from procedure whereas procedures cannot be called from
function.
5) Exception can be handled by try-catch block in a procedure whereas try-catch block
cannot be used in a function.
6) We can go for transaction management in procedure whereas we can't go in function.
7) Procedures cannot be utilized in a select statement whereas function can be
embedded in a select statement.
Difference between Abstract and Interface
Abstract Class:
-Abstract class provides a set of rules to implement next class
-Rules will be provided through abstract methods
-Abstract method does not contain any definition
-While inheriting abstract class all abstract methods must be override
-If a class contains at least one abstract method then it must be declared as an Abstract
Class
-Abstract classes cannot be instantiated (i.e. we cannot create objects), but a reference
can be created
-Reference depends on child class objects memory
-Abstract classes are also called as Partial abstract classes
-Partial abstract class may contain functions with body and functions without body
-If a class contains all functions without body then it is called as Fully Abstract Class
(Interface)
Interface:
-If a class contains all abstract methods then that class is known as Interface
-Interfaces support like multiple inheritance
-In interface all methods r public abstract by default
-Interfaces r implementable
-Interfaces can be instantiated, but a reference cannot be created
Index types in SQL Server
Clustered

Index

Only 1 allowed per table physically rearranges the data in the table to confirm to the
index constraints for use on columns that are frequently searched for ranges of data for
use on columns with low selectivity.

157

Non-Clustered

Index

Up to 249 allowed per table creates a separate list of key values with pointers to the
location of the data in the data pages For use on columns that are searched for single
values
A clustered index is a special type of index that reorders the way records in the table are
physically stored. Therefore table can have only one clustered index. The leaf nodes of a
clustered index contain the data pages. A non-clustered index is a special type of index
in which the logical order of the index does not match the physical stored order of the
rows on disk. The leaf node of a non-clustered index does not consist of the data pages.
Instead, the leaf nodes contain index rows.
Included

Column

Index

(New

in

SQL

Server

2005)

In SQL Server 2005, the functionality of non-clustered indexes is extended by adding


non-key columns to the leaf level of the non-clustered index. Non-key columns can help
to create cover indexes. By including non-key columns, you can create non-clustered
indexes that cover more queries. The Database Engine does not consider non-key
columns when calculating the number of index key columns or index key size. Non-key
columns can be included in non-clustered index to avoid exceeding the current index size
limitations of a maximum of 16 key columns and a maximum index key size of 900
bytes. Another advantage is that using non-key column in index we can have index data
types
not
allowed
as
index
key
columns
generally.
In following example column Filename is varchar(400), which will increase the size of the
index key bigger than it is allowed. If we still want to include in our cover index to gain
performance
we
can
do
it
by
using
the
Keyword
INCLUDE.
USE AdventureWorks
GO
CREATE INDEX IX_Document_Title
ON Production.Document (Title, Revision)
INCLUDE (FileName)
Non-key columns can be included only in non-clustered indexes. Columns cant be
defined in both the key column and they INCLUDE list. Column names cant be repeated
in the INCLUDE list. Non-key columns can be dropped from a table only after the nonkey index is dropped first. For Included Column Index to exist there must be at least one
key column defined with a maximum of 16 key columns and 1023 included columns.
Avoid adding unnecessary columns. Adding too many index columns, key or non-key as
they will affect negatively on performance. Fewer index rows will fit on a page. This could
create I/O increases and reduced cache efficiency. More disk space will be required to
store the index. Index maintenance may increase the time that it takes to perform
modifications, inserts, updates, or deletes, to the underlying table or indexed view.
Another example to test:

158

Create following Index on Database AdventureWorks in SQL SERVER 2005


USE AdventureWorks
GO
CREATE NONCLUSTERED INDEX IX_Address_PostalCode
ON Person.Address (PostalCode)
INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID)
GO
Test the performance of following query before and after creating Index. The
performance improvement is significant.
SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCode
FROM Person.Address
WHERE PostalCode BETWEEN '98000'
AND '99999';
GO
Interview questions
What are differences between Array list and Hash table?
Ans: 1) Hash table store data as name, value pair. While in array only value is store.
2) To access value from hash table, you need to pass name. While in array, to access
value, you need to pass index number.
3) you can store different type of data in hash table, say int, string etc. while in array
you can store only similar type of data.
What are differences between system.stringbuilder and system.string?
The main difference is system.string is immutable and system.stringbuilder is a mutable.
Append keyword is used in string builder but not in system.string.
Immutable means once we created we cannot modified. Suppose if we want give new
value to old value simply it will discarded the old value and it will create new instance in
memory to hold the new value.
What are the differences between Application object and session object?
Ans: The session object is used to maintain the session of each user. If one user enter in
to the application then they get session id if he leaves from the application then the
session id is deleted. If they again enter in to the application they get different session
id.
But for application object the id is maintained for whole application.
What are the different types of indexes?
Ans: Two types of indexes are there one is clustered index and non-clustered index
How many types of memories are there in .net?
Ans: Two types of memories are there in .net stack memory and heap memory

159

Is it possible to set the session out time manually?


Ans: Yes we can set the session out time manually in web.config.
What are differences between function and stored procedure?
Ans:
1) Function returns only one value but procedure returns one or more than one value.
2) Function can be utilized in select statements but that is not possible in procedure.
3) Procedure can have an input and output parameters but function has only input
parameters only.
4) Exceptions can be handled by try catch block in procedures but that is not possible in
function.
What are the differences between Abstract and interface?
Ans: 1) Abstract cannot be instantiated but we can inherit. Interface it cannot be inherit
it can be instantiate
2) Interface contain only declarations no definitions. Abstract contain declarations and
definitions.
3) The class which contains only abstract methods is interface class. A class which
contains abstract method is called abstract class
4) Public is default access specifier for interface we dont have a chance to declare other
specifiers. In abstract we have chance to declare with any access specifier
Can you Explain Page lifecycle in .net?
Can you Explain .NET architecture in .net?
What is the difference between primary key and unique key with not null?
Ans: There is no difference between primary key and unique key with not null.
What is boxing and unboxing concepts in .net?
Ans: Boxing is a process of converting value type into reference type
Unboxing is a process of converting reference type to value type.
What are the differences between value type and reference type?
Ans: Value type contain variable and reference type are not containing value directly in
its memory.
Memory is allocated in managed heap in reference type and in value type memory
allocated in stack. Reference type ex-class value type-struct, enumeration
Is it possible to host the website from desktop?
Ans: Yes

160

Why we go for page rendering in Asp.Net Page life cycle?


Ans: Browser understands an only html control thats why in page rendering we will
convert the aspx controls into html controls.
Write a sample query for self join?
Ans: Select e1.ename, e2.empid from emp e1, emp e2 where e1.empid=e2.mgrid;
Can we change the index of primary key on table?
Ans: No
How to change the name of the table or stored procedure in sql?
Ans: sp_rename oldtablename newtablename
For changing the column name
Sp_rename tablename.[Oldcolumnname],newcolumnname,Column
Ex:sp_rename tblemp.first,namechange,Column
How to find out which index is defined on table?
Ans: sp_helpindex tablename
Can you write the program to find the length of string without using library
function?
Ans: for (int i=0; str[i]!=\n; i++)
{
Count++;
}
What is the difference between scope_identity() and current_identity()?
Ans: Scope_identity and current _identity both are similar and it will return the last
identity value generated in the table.
Scope_Identity will return the identity value in table that is currently in scope
What are difference between GET and POST Methods?
Ans:
GET Method ():
1)
2)
3)
4)
5)
6)

Data is appended to the URL.


Data is not secret.
It is a single call system
Maximum data that can be sent is 256.
Data transmission is faster
this is the default method for many browsers

161

POST Method ():


1) Data is not appended to the URL.
2) Data is Secret
3) it is a two call system.
4) There is no Limit on the amount of data. That is characters any amount of data can be
sent.
5) Data transmission is comparatively slow.
6) No default and should be explicitly specified.
What are difference between truncate and delete?
Ans: 1) Delete keep the lock over each row where Truncate keeps the lock on table not
on all the row.
2) Counter of the Identity column is reset in Truncate where it is not reset in Delete.
3) Trigger is not fired in Truncate where as trigger is fired in Delete.
4) In TRUNCATE we cannot rollback.
5) In DELETE we can rollback
What is the difference Grid View and between Data Grid (Windows)?
Ans:
1) GridView Control Enables you to add sorting, paging and editing capabilities without
writing any code.
2)GridView Control Automatically Supports paging by setting the PagerSetting
Property.The Page Setting Property supports four Modles
a. Numeric(by default)
b. Next Previous
c. NumericFirstLast
d. Next PreviousLast
3)It is Used in asp.net
4)GridView Supports RowUpdating and RowUpdated Events.
5)GidView is Capable of Pre-Operations and Post-Operations.
6)GridView Has EditTemplates for this control
7)It has AutoFormat
DataGrid(Windows)
1)DataGid Control raises single Event for operations
2)DataGird Supports the SortCommand Events that occur when a column is Soted.
3)DataGrid Supports UpdataCommand Event that occurs when the UpdateButton is
clicked for an item in the grid.
4)DataGrid is used in Windows GUI Application.
5)It doesnot have EditTemplates for this control
6)It doesnot have AutoFormat
If I write System.exit (0); at the end of the try block, will the finally block still
execute?

162

Ans: No in this case the finally block will not execute because when you say
system.exit(0),the control immediately goes out of the program, and thus finally never
executes.
What are the different levels of State management in ASP.NET?
Ans:
State management is the process by which you maintain state and page information
over multiple requests for the same or different pages.
There are 2 types State Management:
1. Client Side State Management
This stores information on the client's computer by embedding the information into a
Web page, a uniform resource locator (url), or a cookie. The techniques available to
store the state information at the client end are listed down below:
a. View State Asp.Net uses View State to track the values in the Controls. You can add
custom values to the view state. It is used by the Asp.net page framework to
automatically save the values of the page and of each control just prior to rendering to
the page. When the page is posted, one of the first tasks performed by page processing
is to restore view state.
b. Control State If you create a custom control that requires view state to work
properly, you should use control state to ensure other developers dont break your
control by disabling view state.
c. Hidden fields Like view state, hidden fields store data in an HTML form without
displaying it in the user's browser. The data is available only when the form is
processed.
d. Cookies Cookies store a value in the user's browser that the browser sends with
every page request to the same server. Cookies are the best way to store state data that
must be available for multiple Web pages on a web site.
e. Query Strings - Query strings store values in the URL that are visible to the user. Use
query strings when you want a user to be able to e-mail or instant message state data
with a URL.
2. Server Side State Management
a. Application State - Application State information is available to all pages, regardless of
which user requests a page.
b. Session State Session State information is available to all pages opened by a user
during a single visit.
Both application state and session state information is lost when the application restarts.
To persist user data between application restarts, you can store it using profile
properties.
Abstract Class:
Abstract class is a class which cant be instantiate. Class should have Abstract key word
with the name. In any one of the method of class having abstract method with in it,
then it should be define as abstract class. The class which derived the abstract class
should have definition of the abstract method. These classes which derived the abstract

163

class and implement the abstract methods call concrete class.


Abstract class may have the definition of function or may not. Below is the simple
example of an abstract class
public abstract alass AbstractStudent
{
String Roll
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
Public String GetStudentDetails()
{
// Implementation of Method
}
public String SaveStudentDetails ()
{
// Implementation of Method
}
public abstract String CalculateWage();
}
So, the class having one abstract method so we need to mention the class as "abstract" .
Difference between Abstract Class and Interface?
Abstract class is a class which cant be instantiated and which can have methods with
definition as well as declaration also. This can be inherited.
As for Example:
public abstract class AbstractStudent
{
String Roll
{
get;
set;
}
String FirstName
{

164

get;
set;
}
String LastName
{
get;
set;
}
Public String GetStudentDetails()
{
// Implementation of Method
}
public String SaveStudentDetails ()
{
// Implementation of Method
}
public abstract String CalculateWage();
}
Interface can only contain the methods declaration and can be implemented in the class.
As for Example:
Public interface IStudnet
{
String Roll
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
String GetStudentDetails();
String SaveStudentDetails ();
}
Below are the few main difference between Abstract Class and Interface
a. In abstract class method can have definition as well as declaration also. But
Interface should have only definition.
b. All the Methods are Public as default and dont have any access Modifier Controls in

165

interface, whereas for abstract class we can have access modifier for methods.
c. Abstract class can have constructor or destructor, whereas interface not.
d. Abstract class cant be part of multiple inheritance and we can implement
multiple interface.
What do you mean by String objects are immutable?
String objects are immutable as its state cannot be modified once created. Every time
when we perform any operation like add, copy, replace, and case conversion or when we
pass a string object as a parameter to a method a new object will be created.
Example:
String str = "ABC";
str.Replace("A","X");
Here Replace() method will not change data that "str" contains, instead a new string
object is created to hold data "XBC" and the reference to this object is returned by
Replace() method.
So in order to point str to this object we need to write below line.
str = str.Replace("A","X");
Now the new object is assigned to the variable str. earlier object that was assigned to str
will take care by garbage collector as this one is no longer in used.
What is dll hell problem in .NET and how it will solve?
Ans: Dll hell, is kind of conflict that occurred previously, due to the lack of version
supportability of dll for (within) an application
.NET Framework provides operating system with a global assembly cache. This cache is a
repository for all the .net components that are shared globally on a particular machine.
When a .net component installed onto the machine, the global assembly cache looks at
its version, its public key and its language information and creates a strong name for the
component. The component is then registered in the repository and indexed by its strong
name, so there is no confusion between the different versions of same component, or
DLL
What is a Partial class?
Ans: Instead of defining an entire class, you can split the definition into multiple classes
by using partial class keyword. When the application compiled, c# compiler will group all
the partial classes together and treat them as a single class. There are a couple of good
reasons to use partial classes. Programmers can work on different parts of classes
without needing to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()

166

{
}
}
What is difference between constants, read-only and, static?
Constants: The value cant be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
What is the cross page post backing?

Asp.Net 2.0 fixed this with built-in features that allowed us to easily send information
from one page to another.
Button control has property PostBackUrl that can be set to URL of any page in our
ASP.Net WebSite where we want to transfer all form values to.
Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows us to
get reference to the Page object that initiated the postback (in other words to get the
actual reference to the Page object of the aspx page on which user clicked the Submit
button on a HTML form).
So for example lets create two sample pages in our Web Application:

SourcePage.aspx

DestinationPage.aspx
In SoucePage in Html form we will put two TextBox controls (one for First Name and one
for Last Name) and one Button component and set its PostBackUrl property to
"~/DestinationPage.aspx".
SourcePage.aspx:
<form id="form1" runat="server">
<div>
First
Name:&nbsp;<asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
Last
Name:&nbsp;<asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /><br
/>
<asp:Button ID="Button1" runat="server" Text="Submit To Destination
Page"PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />
</div>
</form>
When our user clicks the Submit button, all the values from the HTML Form on
SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able
to get reference to the SourcePage.aspx in our DestinationPage with
the PreviousPage property like this:
So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox
controls on SourcePage.aspx and show them in two label controls like this:
protected void Page_Load(object sender, EventArgs e)
{
// first check if we had a cross page postback
if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )

167

Page previousPage = PreviousPage;


TextBox firstName = (TextBox)previousPage.FindControl("FirstName");
TextBox lastName = (TextBox)previousPage.FindControl("LastName");
// we can now use the values from TextBoxes and display them in two Label
controls..
labelFirstName.Text = firstName.Text;
labelLastName.Text = lastName.Text;
}
}
You probably noticed that we first checked if PreviousPage property of current page
(DestinationPage.aspx) is NOT NULL, this is done to avoid running our code in case that
user opens our DestinationPage.aspx directly, without running a cross page postback.
Also here we checked the another PreviousPage property
called IsCrossPagePostBack to see if we really had a CrossPagePostback.
(If Server.Transfer is used to redirect to this page, IsCrossPagePostBack property will
be set to FALSE.
TIP: We can be completely sure that we have a real CrossPagePostback ONLY IF:
1.
Page.PreviousPage is NOT NULL,
2.
PreviousPage.IsCrossPagePostback is true
This important to check to avoid errors in code.
Now this is very useful and i'm sure you are eager to use this in your next project. But
wait, we are not over yet!
Finding the controls on PreviousPage with FindControl method and type-casting them
from object to their real type is a little messy.
It feels like there must be a better solution for this!
And here it is: We can use the <%@ PreviousPageType %> directive in the header of
our DestinationPage.aspx like this
<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>
to declare our previous page type, and then we can access Public properties of the
PreviousPage without typecasting.
Now all we need to do is to create some public properties on our SourcePage.aspx.cs to
expose data/Controls we want to the destionation page:
public partial class SourcePage : System.Web.UI.Page
{
public string FormFirstName
{
get { return FirstName.Text; }
}
public string FormLastName
{
get { return LastName.Text; }
}
}
And then we can change the Page_Load code in our DestinationPage.aspx to much
cleaner code like this:
protected void Page_Load(object sender, EventArgs e)
{

168

// first check if we had a cross page postback


if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
{
SourcePage prevPage = PreviousPage;
// we can now use the values from textboxes and display them in two Label
controls..
labelFirstName.Text = prevPage.FormFirstName;
labelLastName.Text = prevPage.FormLastName;
}
}
SourcePage type used in the code is offcourse name of the partial class defined is
SourcePage.aspx.cs that inherits System.Web.UI.Page that is automatically created for
us when we created new WebForm in VisualStudio.
This code is much cleaner and easier to follow, there is no ugly typecasting, just simple
property values to use to retrieve the data from previous page.

When should you use Abstract Class vs Interface while programming?


Ans: When we want that sub class must implement all the methods of base class. In
such a situation we will implement the interface. In the other hand when we want only
some method of base class in our sub class then use base class as abstract class.
What is the difference between application exception and system exception?

Ans: The difference between application exception and system exception is that system
exceptions are thrown by CLR and application exceptions are thrown by applications.
What is the difference between authorization and authentication?
Ans: Authorization is a process of allowing or denying resources to particular user or
record
Declaration of authorization is
<authorization>
<allow users=Suresh, Sanjay/>
<deny users=Ramana, Rakesh>
</authorization>
Sometimes authorization allows the unauthorized persons at that time we will use
<deny users=?/>
Authentication means

169

Authentication is a process where we identify the credentials of user i.e. username,


password and create an identity to mention user as an authenticated.
What is the use of n-tier architecture and 3-tier architecture?
Check this article for 3-tier architecture 3 tier architecture example in asp.net
How to get the version of the assembly?
Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();
What is the location of Global Assembly Cache on the system?
Ans: c:\Windows\assembly
What is the serialization?
Ans: Serialization is a process of converting object into a stream of bites.
What is synchronization?
Ans: The mechanism needed to block one thread access to the data. If the data is being
accessed by another thread.
Synchronization can be accessed by using system.monitor class
A monitor class methods are enter, exit, pulse for this lock statement is also used
Suppose if we need to synchronize some data at that time we need to place that data in
this block
Lock
{
}
Whatever the data has been placed into the lock block that data has been blocked
What are the thread priority levels?
Ans: Thread priority levels are five types
0 - Zero level
1 - Below Normal
2 - Normal
3 - Above Normal
4 - Highest
By Default priority level is 2
What is the difference between .tostring(), Convert.tostring()?
Ans: The basic difference between them is Convert function handles NULLS while
.ToString() does not it will throw a NULL reference exception error. So as a good coding
practice using convert is always safe.

170

What is Collation?
Ans: Collation refers to a set of rules that determine how the data is sorted and
compared.
What is the difference between Primary key and unique key?
Ans: Primary key does not allow the null values but unique key allows one null value.
Primary key will create clustered index on column but unique key will create nonclustered index by default.
How many web.config files are there in 1 project?
Ans: There might be multiple web.config files for a single project depending on the
hierarchy of folders inside the root folder of the project, so for each folder we can use
one web.config file
What is the difference between throw and throw ex?
What is the difference between view state and hidden field?
Ans: viewstate is secured hidden field is insecure
Viewstate will store large amount of data but hidden filed will store small amount of
data.
What is the difference between binary serialization and xml serialization?
What is the Difference between read only and constant variables?
Ans: Read only can assign the values at runtime only.
Constant will assign the values at compile time only.
We cannot modify the both variable values.
What is static keyword in .Net?
Ans: Static is same as constant variable but we can change the value of static variable
and we can access the variables without creating any instances
What is the use of business logic layer in 3-tier architecture in .net?
Ans: Though a web site could talk to the data access layer directly, it usually goes
through another layer called the business layer. The business layer is vital in that it
validates the input conditions before calling a method from the data layer. This ensures
the data input is correct before proceeding, and can often ensure that the outputs are
correct as well. This validation of input is called business rules, meaning the rules that
the business layer uses to make judgments about the data.
However, business rules dont only apply to data validation; these rules apply to any
calculations or any other action that takes place in the business layer. Normally, its best
to put as much logic as possible in the business layer, which makes this logic reusable
across applications.

171

One of the best reasons for reusing logic is that applications that start off small usually
grow in functionality. For instance, a company begins to develop a web site, and as they
realize their business needs, they later decide to add a smart client application and
windows service to supplement the web site. The business layer helps move logic to a
central layer for maximum reusability.

3-6 Year Interview Question in .Net Technologies- Part I


Hai Friends,
Below I am posting the questions and answers for the short questions for 3-6
years guys. These questions will be helpful for those who are preparing for the
interview or attending the interviews. This will be helpful for the last minute
preparation in quickest way.
If anyone has better answer, please reply to this post as that will beclas useful
for all of us.
CLR and C#
1. Types of Authentication and Authorization in IIS.
A. Types of Authentication: Anonymous Authentication, Windows Authentication,
Digest Authentication
Types of Authorization:- Anonymous
2. Types of Authentication and Authorization in ASP.Net.
A. Types of Authentication: Windows Authentication, Forms Authentication
Types of Authorization:- File Authorization and URL Authorization
3. ASP.Net Life cycle.
A. The request starts with the client and processed through IIS. In IIS, there
are 2 utilities- INetInfo.exe and ASPNet_ISAPI.dll the InetInfo.exe checks for the
syntax and semantics of the request and then the request goes to the
ASPNet_ISAPI.dll which is the filter to filter the .aspx files. Here the URL request
split in to 2 parts- virtual directory and webpage. Now worker process which is
nothing but the application factory basically contains all the virtual directories
and checks for the current virtual directory. If this is first request, then there will
be no Virtual directory available. Now the worker process (W3wp.exe) creates a
memory area called as AppDomain to check for the current page. As AppDomain
is the Page Handler factory so it contains all the processes pages. If this is the
new page then it will not find here. The request further move to the HttpPipeline
where the actual execution of the page happened by using the ProcessRequest
method and creates the events of the page. After creation of event and
execution of all the event, the HTML page gets back to the user.
4. ASP.Net Page Life Cycle.
A. There are few events which gets generated during the page execution like:
Page_BeginRequest, Page_Init, Page_Load, Page_Prerender, Page_Render,
Page_Unload etc
For the details of the page life cycle, you can follow the previous question.
5. What are types: Value Type and Reference Type?
A. Value type holds data directly, Value type stored in the stack memory, we can
get the direct value of the value types. Value type data type cant be null.
172

Reference types: This type doesnt hold the data directly. They hold the address
on which the actual data present. They stored in heap memory, Can have default
values.
We can make and work with null reference type.
6. Boxing and Unboxing: Terminology, Advantages and Disadvantages.
A. Converting the value type data type in to the Reference type is called as
Boxing. Converting the Reference type data type and keep its value to stack is
called as the reference type.
byte b= 45;
Object o = b.Tostring();

The Advantage of boxing and unboxing is that we can convert the type of the
object in to another type. The disadvantage is that it requires lot of memory and
CPU cycles to convert from one type to another type.
Object o=10;
Int i= Convert.ToInt32(o.ToString());

7. What is Type Safety?


A. TypeSafe is a way through which the application or framework that the
memory will not be leaked to outside environment. E.g. C# is the type safe
language where you must have to assign any object before using it. In VB.Net it
will take the default value. So C# is the type safe language while VB.Net is not.
8. What is Strong Name?
A. Strong Name (SN) is used to make the dll as the unique as:
SN -k fileName.dll

Now it will have the unique name. This assembly when placed in the GAC, it will
treat as the unique with its version number and other details. 2 assemblies with
the same name can exist in the GAC but both will have different version. The
CLR takes the latest version assembly while running the application.
9. What are Extensions, modules and handlers?
A. HttpModule and HttpHandler are the utilities which are used in the
HttpPipeline under the ASP.Net page life cycle. When the request received to
HttpPipeline, the HttpModule checks for the Authentication of the request and
then it route the request to the respective handler. After that HttpHandler takes
that request and process it. After Processing the request again the HttpModule
takes the response and send it back to the worker process and finally to the
user.
10. What is worker process?
A. Worker process (w3wp.exe) is an executable which is also called as the
Application Factory. This is used for the execution of the request and handling of
the request for the current web page.
11. CLR and DLR?
A. CLR (Common Language Runtime) is the utility in the .Net framework to run
the application. It is the run-time engine which actually executes the application
with many responsibilities like taking care of memory management, versioning,
CasPol etc.
DLR is new with .Net 4.0 which is the Dynamic Language Runtime and used to
run the application on the fly wherever required. CLR runs as statically while DLR
runs dynamically.
173

12. In case more than one version of an installable is installed, which version is
invoked by default?
A. By default the CLR will take and invoke the latest version of the dll and
execute it accordingly. There could be the same name assemblies exists in the
GAC but they will have different versions altogether for their uniqueness.
So while running the application, CLR takes the latest version assembly and use
in the application.
13. What are Globalization and localization? How to implement them?
A. Globalization is the concept of developing the application in more than one
language while the Localization is used for a particular language. Like if we
develop the application in more than one language we need to create the
resource files (.resx) by using System. Globalization and when we open the
application in a particular language, then the localizations used to convert that
application to the selected language.
14. What is assembly, GAC? Where they are physically located?
A. Assembly is the collection of classes, namespaces, methods, properties which
may be developed in different language but packed as a dll. So we can say that
dll is the assembly.
There are 3 types of assemblies- Private Assembly, Shared Assembly, and
Satellite Assembly.
GAC (Global Assembly Cache)- When the assembly is required for more than
one project or application, we need to make the assembly with strong name and
keep it in GAC or in Assembly folder by installing the assembly with the GACUtil
command.
To make the assembly with strong name:
SN -k MyDll.dll

And to install it in GAC:


GacUtil -i MyDll.dll

GAC assemblies are physically stored in Assembly folder in the system.


15. How to configure HTTPS for a web application?
A. To configure the HTTPS (HTTP with Secure) for the web application, we need
to have a client certificate. We can purchase the client certificate from the
trusted providers and then we need to install that provider for our site. By
implementing the HTTPS, all the data which is passing will be in encrypted
format and will be more secure.
16. What are in-proc and out-proc? Where are data stored in these cases?
A. In-Proc and Out-Proc is the types of Sessions where the session data can be
stored in the process memory of the server and in the separate state server.
When the session data is stored in the process memory of the server, the session
is called as the In-Proc server. In this case when the server is restarted, the
session data will be lost.
When the session data is stored in the separate server like in state server or in
Sql Server, the type of session is called as the Out-Proc session. In this case, if
the server where the application is running is restarted, the session will be still
remain in the separate servers.
So in the in-Proc session state, the session data is stored in the Process
memory of the Server where the application is running.
174

In the Out-proc session state, the session data is stored in the separate servermay be state server or in sql server.
17. When the View state is saved, and when is it loaded? How to enable/ disable
View states?
A. View State data is stored in the current page in base64 encoded format. It
gets loaded with the page and displays the values to the controls after the
decoded. Internally it actually saves the check-sum of all the control data where
the view state is enabled.so that when the page gets loaded due to any post
back, it again finds the check-sum and then decodes the Base64 encoded string
and gets back the same data to the controls. We can see the view state base 64
encoded string in View Source of the page. It will be
like _VIEWETATE="DSDSDF8DGDGDFGFD5FDGGDJFF23BNN457M9UJOG" this.
View state won't take the client or server memory to keep the view state data.
18. Difference between GET and POST. Which one is more secure?
A. GET and POST methods are used for the data transfer between the web
pages. GET mainly used for small data which is not secure because in case of
GET method, the data which we are passing will be visible in the url so we can't
keep the secure data which will be visible in the url. There is also limited data
which can be passed in case of GET method (max 255 character).
POST is used for transferring the huge data between the pages where we can
keep the secure data and can transfer it. In case of using the POST method, the
data which is transferring between the pages will not be visible so it is more
secure than the GET method. Also there is no limit for POST method to post the
data to the next page.
POST is more secure.
19. What are Razor engines? How is it diff from ASP Engines?
A. RAZOR engine is the new concept in the MVC 3 which is mainly used to create
the views in the MVC applications. It created the cshtml pages for the MVC
application and cshtml pages can be generated automatically by using the Razor
engine.ASP engine create the aspx pages while Razor engine creates the pages.
20. Pros and cons of JavaScript and AJAX.
A. JavaScript is a scripting language and mainly used for client side validation.
We can validate the client side data before sending to the server. So by this we
can improve the performance of the application.
Ajax is Synchronous JavaScript and XML which is used for the Asynchronous
calls from the server. It uses internally the JavaScript for making the call and use
XML for the Data Transfer. It basically uses the XmlHttpRequest for the
asynchronous calls to the server and communicates with the XML data which is
platform independent. So Ajax can be used with any technology.
21. In how many different ways can JavaScript be used/called in an application?
A. JavaScript can be used for Client Side validation, can also be used for calling
of server side methods and functions, can be used for calling the web services
etc.
22. What needs to be done to call a JavaScript function from code behind?
A. If we want to call the JavaScript function from the code behind, we need to
attach the JavaScript to the events in the page_load event as:
175

protected void btnSave_cliekc9object sender, EventArgs e)


{
btnSave.Attributes.Add("onclick,"JavaScript: retrun Validatedata();");
}

Here ValidateData is the JavaScript function which can be used to validate the
page data and if validation fails, it will return and will not execute the server side
btnSave_click event.
23. Difference between Server Controls and User controls?
A. User controls are used for the re-usability for the controls in the application.
By using the user control, we can use the same control in the various pages.
User controls can be created by combining more than one control. To use the
user controls, first we need to register them in the web page where we want to
use that control. A separate copy is need in each page where we want to use the
user control. User controls can't be included in to the toolbox.
Server controls are those controls which can be found in the toolbox and can be
directly drag to the application like textbox, button etc. For the server control,
only 1 copy of the control is needed irrespective of the number of web pages. If
we want 10 text-boxes to be added in our web page, we need only 1 copy of the
textbox in the toolbox and can be dragged 10 times.
24. Difference between Var, object and Dynamic types.
A. var is the keyword introduced with .net 3.5 and used to store any kind of data
like data-set, data table, int, float, char etc. We can keep any kind of data in the
var variable.
var myVar = new String[] {"hello", "world!!"} ;

Here the myVar is the var type variable which is used to store the string array.
Like this we can store any type of data into the var.
Object is the type which is used to store the objects of any kind. These objects
need to be type caste when required.
Like object mybject = "Hello"
Here the myObject variable of object type is used to keep the string variable.
Now when we want this variable value, we need to typecast it like
string strvar= (string) myobject;

Dynamic- Its a keyword introduces with the .net 4.0 and used to keep the data
similar to the var keyword. The difference between the var and dynamic is that
the dynamic variable uses the same memory location to store the object and not
changes throughout the application.
25. Difference between Functions and methods.
A. in.Net terminology, both are same. in general, we use method in .net but in
scripting language we use function like JavaScript function.
Here the difference can be Function always returns a value which method may or
may not. It depends upon the return type of the method.
26. Difference between Abstract classes and Interface. Explain with scenario
where to implement one?
A. Collection of the Abstract (Incomplete) and Concrete (complete) methods is
called as the Abstract class. If there is at least one abstract method in a class,
the class must be abstract class.
When there is the similar behavior, we can use the abstract class.
e.g. We want to calculate the area of few component. As this is not generic to
the application. We have only few component- like Circle, Ellipse, parabola,
176

Hyperbola, Triangle etc.


So we can create an abstract class and implement it like below:
public abstract class MyAbstractClass
{
// some other concrete members
public abstract void Area();// abstract member
}

Now in the child class, lets say i have a circle class and want to calculate the
area of the circle:
public class Cicle: MyAbstractClass
{
public override void Area()
{
// calculate the area of the circle
}
}

In the similar fashion, we can calcite the area of other shapes.


Collection of abstract members is called as the Interface. When the behavior is
not similar, we need to use the interface. All the members of the interface
must be overrides in the child class.
e.g. Print functionality of the application can have an interface like:
interface Inf
{
void Print();
}

Now as this is the generic functionality and can be implemented in any of the
page so we have taken it as interface. Now we can implement this functionality
in to any page like:
class MyClass:Inf
{
public void print
{
// write details about the print
}
// Here we can implement any kind of print-like print to excel, xml, word all depends on
the our decision.
}

27. Different forms of Polymorphism. Differences between Abstraction and


Polymorphism.
A. Polymorphism is to use the same function in many forms. The polymorphism
is of 2 typesa. Classical polymorphism (Overloading)
b. AdHoc polymorphism (Overriding)
When the runtime (CLR) find the behavior of class members at the runtime of
the program, it is called as the AdHoc polymorphism or Overriding.in this the
method name is same but they are implemented in the different class. We use
virtual keyword in the base class method to be overrides in the child class using
the override keyword.
e.g.
Public class MyBaseClass
{
Public virtual void Show(string message)
{
Console.WriteLine(Your message is : + message);

177

}
}
Public class MyChildClass: MyBaseClass
{
public override void Show(string message)
{
Console.WriteLine(Your new message is : + message);
}
}

When the run-time (CLR) find the behavior of class members at the compilation
of the program, it is called as the Classical polymorphism or Overloading.in this
the method name is same but there prototypes (parameters) are different and it
is implemented in the same class.
e.g.
public class MyClass
{
Public int Add(int a, int b)
{
Return a+b;
}
Public int Add(int a, int b, int c)
{
Return a+b+c;
}
}

Abstraction is the behavior to get the required functionality in the child class. So
we dont matter whatever is written in the base class. We only need to force the
child class to implement my required functionality.
Abstract keyword is used to get the abstraction behavior.
28. What are Delegates and Events?
A. A Delegate is an object, which points to another method in the application.
Delegate holds, name of the method, arguments of the method (if any) and the
return type of the method.
See the below points regarding the Delegate:
delegate keyword is sealed type in System. Multicast namespace.

Delegate works like a function pointer in C language.

Delegate holds the address of the function.

Delegate hides the actual information which is written inside the method
definition.

A delegate can hold address of a single function as well as the address of


multiple functions.

There are 2 types of delegate- Single-cast delegate (hold single function)


and Multicast delegate(hold multiple functions).

Addition and subtraction are allowed for the delegates but NOT
multiplication and division. It means, we can add delegates, subtract delegates
etc.
e.g. To create a single cast delegate, first we can create a class with a method
as:
public class DelegateDemo
{
public void Show(string msg)
{

178

Console.WriteLine(msg);
}
}

Now we can call the method Show using the delegate as:
public delegate void MyDelegate(string message); //declare delegate

now we need to create the object of the delegate with the address of the method
as:
DelegateDemo obj = new DelegateDemo();//class object
MyDelegate md= new MyDelegate(obj.Show(Hello World!!));
md(); // call the delegate

We can create the events and event handler by using delegate with the below
syntax:
public delegate void textChangedEventHandler(Object sender, TextEventArgs e);
This event handler will be used to handle the textbox text changed event.
We can get more details about the delegate and events from the below link:
http://msdn.microsoft.com/en-in/library/orm-9780596521066-01-17.aspx

29. Covariance and Contra-variance.


A. covariance and contravariance are the new features added with the .net 4.0.
They are basically used for the implicit reference conversion for different .net
types like array, delegate, and generic etc
You can go to the below link for more details with the examples that how we can
use the covariance and contrvariance to implicate reference conversion:
http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariancefaq.aspx

30. What are Extension methods?


A. Extension methods are special types of methods which are static methods but
called as the instance methods. The extension methods are added with the .Net
framework 3.5 and with the Visual Studio 2008.
These methods wont affect the existing class and the label. These methods are
used for the extra behavior which the calls can provide. There is no need to build
the class again if we add any extension method to the class.
There are various inbuilt methods added in .Net 3.5 with the introduction of
LINQ. We can see the extension methods like Order By when we use the Linq as:
e.g.
int[] numbers = { 10, 45, 15, 39, 21, 26 };
var orderedNumbers = numbers.OrderBy(a => a);

31. What are Anonymous methods and Lambda Expression?


A. Anonymous methods are those methods which does not have the name. As
they dont have the name, so there is no way to call these methods. These
methods are created by using the work delegate as below:
button1.Click += delegate{listBox1.Items.Add(textBox1.Text)};
Lambda Expression: Its an easy way to create anonymous functions. It is also
an anonymous function which has the capability to contain expressions and
statements. We can create the delegate and expression tree types using the
lambda expression.
For more details regarding the anonymous method and lambda express, you can
go through the below link:
http://www.codeproject.com/Articles/47887/C-Delegates-Anonymous-Methods-andLambda-Expression

179

32. Multithreading. How to implement Multithreading?


A. Executing more than one process simultaneously called as multithreading. To
implement the multithreading concept, we need to use the System. Threading
.dll assembly and the System. Threading namespace.
To write the thread program, we need to create a class with the method. Now we
can create the thread object and then pass the method by using the class object
to the method.
After that we need to create the ThreadStart delegate which will call the actual
method of the class.
You can go through below link for more explanation and other details regarding
the implementation and the code snippet:
http://www.codeproject.com/Articles/1083/Multithreaded-Programming-Using-C

33. Which interface is used toa.


Convert Boolean values to Visibility values?
b.
Compare two integer values?
c.
Compare String values?
A. Check the below interfaces which are used in these scenarios:
a.
Convert Boolean values to Visibility values?
b.
Compare two integer values?- IComparable interface
c.
Compare String values? IComparer interface
SQL Server
34. What is the difference between a View and a Cursor?
A. View: It is one of the database object which is also called as virtual table. We
can also say that it is a window through which we can see some part of
database. View is also called as stored query because we are going to fetch
some data using View.
View doesnt contain any data. Its just a virtual table which is used to get the
records from the base table for which the view is created. View is faster than ad
hoc queries because when we create the view and execute it once. Next time
onwards it will be available as the compiled format. So whenever the view is
called, it will just execute rather than compiling.
Cursor: Cursor is a database object which is also the buffer area which is created
as a result of any sql statement to hold the intermediate values.
Views are used to format the rows individually. By using the cursor, we can
process the individual rows. There are 4 types of cursors in Sql Servera.
Static Cursor
b.
Dynamic Cursor
c.
Key set cursor
d.
Read-only cursor
35. How to execute multiple update on different conditions in a single query?
A. To execute multiple update using a single Sql update statement is the new
feature available with the SQL Server 2008. In this, we can update multiple rows
using a single update command.
36. Left outer joins and Right Outer joins
A. Joins are used to join 2 or more tables using some conditions. There are 3
types of Joins in SQL Server databasea. Left Outer Join
180

b. Right Outer Join


c. Full Join
In order to extract the matched row from both the tables and unmatched row
from the first table, left Outer join is used. The syntax for left outer join
condition is:
T.Col1* = T2.Col1

In order to extract the matched row from both the tables and unmatched row
from the second table, right Outer join is used. The syntax for right outer join
condition is:
T.Col1 = *T2.Col1

In order to extract the matched row from both the tables and unmatched row
from the first table and then unmatched row from the second table, full join is
used. The syntax for full join condition is:
T.Col1* = *T2.Col1

37. Exception handling.


A. Exception Handling is the way to handle the unexpected error. From the SQL
Server 2005 version, trycatch block is also supported to catch the exceptions in
SQL Server database. There is various other ways to catch the error like
@@Error which is the global variable and used to get the error. RaiseError is
another inbuilt method which is used to display the error.
38. What is Performance Tuning? How do you implement it.
A. Performance Tuning is the process through which we can optimize the SQL
Server objects like functions, triggers, stored procedure so that we can achieve
high response time to the front end. In the performance tuning process we
generally check for the below point and optimize the objects processing:
a. Through Query Execution plan, check for the processing time of the query
execution.
b. Check the join conditions and break all the condition for executions of the
queries individually
c. Check for the error prone process, conditions in the queries.
d. Check for the loops whether they are terminated if any error occurs
e. Check for the processes which are taking more time in execution and how to
reduce the response time.
39. Difference between Having and Where clauses.
A. When the where clause is not able to evaluate the condition which consists of
group functions, Having clause is used. Having clause is always followed by the
Group By clause.
Where clause is used to filter the records based on the conditions. If there is the
requirement to get the group data in the select statement and where clause is
not able to get it, we can use the Having clause.
e.g. Display DeptNo, No.of Employees in the department for all the departments
where more than 3 employees are working
SELECT DEPTNO, COUNT(*) AS TOTAL_EMPLOYEE
FROM EMP
GROUP BY DEPTNO HAVING COUNT(*) >3

40. Difference between Temp tables and Tables variables?


A. Temp Table in SQL Server:
a. Temp table is the special type of tables which are used to store the
intermediate data of the actual table.
181

b. Temp tables are only visible to the current sessions of the sql server instance.
When the session end, these table data automatically drops.
c. We cant join the temp tables as they dont allow the foreign key constraints.
d. Temp tables are created in TempDB database.
e. We can use the same temp table name for the different user sessions.
f. Mostly used in stored procedure to handle the intermediate data.
41. What does @ and @@ suffixed by property names specify?
A. @- This is used for the variable declaration
e.g. @name varchar2(50)
@@- This is used for the Global variable declaration
e.g. @@Error=0
42. Self-join queries.
A. Self-Join is a type of join which is used to join the same table by creating the
second instance of the same table. So we join 2 instances of the same table in
case of self-join. This type of join is used when there is the requirement to get
the referenced data which is available in the same table.
e.g. A table contains EmpId, Ename and ManagerId
As the manager id is also an employee id. Now if we want that who is the
manager of which employee. In this situation, we need to create the instance of
the same table and get the required data as:
SELECT EMPID, ENAME, ENAME AS [MANAGER NAME]
FROM EMP E1, EMP E2
WHERE E1.EMPID= E2.MANAGERID

43. Types of Index.


A. Indexes are one the database objects which is used to improve the
performance of the database queries. it reduces the table scan while retrieving
the data from the database and the search gets fastThere are 2 types of indexes used in the SQL server:
a. Clustered index
b. Non clustered index
There are 3 more types of index but those comes under the above twoa. unique index
b. Composite Index
c. XML Index-added in SQL Server 2005
The index basically works on searching like binary tree where the root value is
the finding value and it will be compared with the partitioned value of the tree.
44. Difference between Primary key, Unique key and Candidate key?
A. Primary Key- It is a key to make the unique identification of the row in a
table. It doesnt allow null values in the primary key column. We can create the
lookup columns based on the primary key. One table allows maximum of 1
primary key and in 1 table, we can create the primary key column by using 16
columns. Due to one of the normalization rule, we have to create primary key for
the table to make the rows unique.
Unique Key:- Primary Key+ Not null is called as unique key. Unique key is also
used to make the rows as unique in a table. The only difference between primary
key and unique key is that primary key doesnt allow null value while the unique
key allow. The limitation of the null in unique key is that it allows only one Null
so in only one row; we can make the key as null for the unique key.
182

Candidate key- the key other than primary key to make the rows as unique is
called as candidate key. In candidate key, we take the columns which are not in
the primary key and make the key for uniqueness of the row.
45. What is the default value for Date type. What are Min and Max values for
Date in 2008.
A. The default value of Date is CURRENT_TIMESTAMP
Below are the new date and time values in Sql Server 2008:
In SQL Server 2008:
1. DateTime2
Min Value: 0001-01-01 00:00:00.0000000
Max Value: 9999-12-31 23:59:59.9999999
2. Date
Min Value: 0001-01-01
Max Value: 9999-12-31
You can go through the below link for couple of work around:
http://dhaneenja.blogspot.in/2008/06/minimum-year-value-in-sql-server.html

WCF
46. What is WCF also known as?
A. WCF (Windows Communication Foundation) is also know an Indigo by its
code name.
47. Difference between WCF and Web Services?
A. Below are the main differences between the WCF and Web Service:
Web Service:
a. Can be hosted in IIS only
b. Only two types of operations affects- One-Way, Request-Response
c.
To serialize the data use System.Xml.Serialization
d. To encode the data use- XML 1.0, MTOM, DIME, Custom
WCF service:
a. Can be hosted in IIS, Self Hosting, WAS, Windows Services etc
b. Three types of operations affects- One-Way, Request-Response and Duplex
c.
To serialize the data use System.Runtimel.Serialization
d. To encode the data use- XML 1.0, MTOM,Binary, Custom
e. WCF Service can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P
etc.
48. What are Endpoints?
A. The collection of Address, Binding and Contract is called as End Point. In Sort,
EndPoint = A+B+C
Address (Where)- it means where the service is hosted. URL of the service
shows the address.
Binding (How)- How to connect to the service, is defined by the Binding. It
basically has the definition of the communication channel to communicate to the
WCF service
Contract (what)- It means what the service contains for the client. What all the
methods are implemented in the WCF service is implemented in the Contract.
49. What are Behavior and Bindings?
A. Binding mainly describes about the communication of the client and service.
183

For this, there are protocols corresponding to the binding behavior which will
take care of the communication channel. There are different protocols which we
use for the different types of bindings. E.g. HTTP, TCP, MSMQ, Named Pipes etc.
Behavior is used for the common configurations that could be for endpoints.
When we use the common behavior, they affect to all the end points. Adding the
service behavior affect the service related stuff while the endpoint related
behavior affects the end points. Also operations level behavior affects the
operations.
50. What are different types of Contracts supported?
A. There are mainly 5 type of contracts used in WCF service:
a. Service Contract
b. Operation Contract
c. Data Contract
d. Message Contract
e. Fault Contract
51. What is the difference between Transport and Message Security mode?
A. WCF supports 2 types of security- Transport Level Security and Message Level
Security
Transport Level Security- In this type of security, we make the transport channel
as secure so that the data flows in that channel will be automatically secured.
For HTTP channel, we use the client certificate for the security of the web
address. SSL is used for the HTTP channel security. As we dont need to secure
each of the messages which are floating between the client and the service, the
speed is faster as direct message is going to the client from the service.
Message level security- This type of security in WCF is used where we dont have
the fixed transport medium and we need to secure each message which is
floating between the server and the client. In this type of security we use certain
algorithms for making the message as secure message. We use some extra bits
and send with the message. We also use some encryption techniques like SHA1
or MD5 which make the proper security for our message. As each message
needs to be secured, this type of security makes some delay in the process of
sending and receiving the messages.
52. How to configure WCF security to support Windows authentication?
A. To support the WCF security in Windows Authentication, we need to add the
ClientCredetialType attribute to Windows under the security tab element:
transport clientCredentialType="Windows"
53. How to use Fault Contract?
A. Fault Contract is mainly used for viewing and displaying the errors which
occurred in the service. So it basically documents the error and the error
message can be shown to the user in the understandable way. We cant use here
the try.catch block for the error handling because the trycatch is the
technology specific (.Net Technology). So we use the Fault contract for the error
handling.
e.g. To use the Fault contract, we can simply write like the below:
public int Add(int number1,int number2)
{
// write some implementation
throw new FaultException (Error while adding data..);
}

184

Here the fault Exception method is the inbuilt method which will throw the
exception and display the message . We can use the custom class so that the
message can be customized and the customized message can be sent to the
client.
So we can creeat a clss like:
Public Class CustomException()
{
public int ID{get;set;}
public string Message{get;set;}
public string Type{get;set;}
}

Now this custom type we ca use with the Operation Contract as:
[ServiceContract]
Public interface IMyInterface
{
[OperationContract]
[FaultContract(typeOf(CustomException))]
Int Add(int num1,int num2);
}

Now while implementation of the Add method, we can assign the class
properties.
WPF
54. Diff between XML and XAML.
A. XAML is the declarative XML based language which is used to define the
objects and properties. XAML document is loaded by XAML parser. So XAML
Parser initiates the objects and set those properties. XAML is mainly used in
creating the objects in WPF and Silverlight applications.
For more detailed explanation, you can go through the below link:
http://www.differencebetween.net/technology/software-technology/differencebetween-xml-and-xaml/
55. Stack Panel and Wrap Panel.
A. StackPanel is one of layout control in WPF. We can place the child controls
inside the stack panel either horizontally or vertically. So it provides two types of
orientations- Horizontal Orientation and Vertical orientation.
You can go through the below link for more detailed explanation and the code
snippet:
http://wpftutorial.net/StackPanel.html

Wrap panel is another layout control which is similar to the StackPanel. Wrap
panel not only keep the control in horizontal and vertical orientation but also
wrap them in to new line if there is no space. Here also the orientation can be
set as Horizontal or Vertical. Its main use is to arrange the tabs in the tab
control, menu control or in toolbar items.
You can go through the below link for more details:
http://wpftutorial.net/WrapPanel.html

56. Hierarchical Data Template.


A. Hierarchical Data Template is a type of data template which is used to bind
the controls which supports HeaderedItemsControl, like TreeViewItem or MenuItem
We can bind those controls items using the Hierarchical Data Template. It
185

displayed the data in to Hierarchical structure in the tree structure. It could be in


the left to right or top to bottom.
You can go through the below link for more details:
http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx

57. Virtualization.
A. This is the feature in WPF which increases the efficiency of the programs
when there are the large data objects. If the WPF ItemsControl is bound with the
large collection data source object and we enabled the virtualization, then the
controls will show only the data which is in the visual container for those items
which are visible currently. This visual data is only the small part of the large
data object. Now when the user will scroll down or up, the rest of the data will
be visible and previous data will be hidden again. So this is increase the
efficiency of the program from the UI prospective.
58. Events and Routed Events.
A. Routed event is special type of event which can invoke and handle multiple
events from different objects rather than the event which is coming from one
object. So it generally handles the object from the element tree. So whatever
the elements inside the element tree and if they generate the event-may be
multiple events, the routed event is capable of handling those events.
The routed event can be invoked in both the directions but in general it comes
from the source element and then bubbled up in the element tree until the root
element.
59. Bubbling and Tunneling.
A. Bubbling: When the events are raised form the innermost element in the
visual tree and comes up towards the root element, is called as bubbling.
Tunneling: It is the opposite process of Bubbling where the events fired by the
root element goes down towards the last child element control.
Please go through the below link for more details:
http://www.dotnetspider.com/forum/130497-event-bubbling-event-tunneling.aspx

60. Resource Dictionary, Static Resources and Dynamic Resources.


A. Static and Dynamic resources are used for binding the resources to the
control objects.
The main difference between StaticResource and DynamicResource is that how
the resource is retrieved elements. If the resource is StaticResource, it will be
retrieved only once by the element whoe is referencing it and it will be used for
all the resources. While the DynamicResource gets its value each time they
reference to the objects. So StaticResource is faster than the DynamicResource ,
because StaticResource needs to get the value only once while the
DynamicResource needs each time to get it.
61. What is Prism?
A. Prism is the framework or the set of guidelines which is used to develop the
WPF desktop application as well as the Silverlight Rich Internet applications. So
its a kind of Design pattern to Develop the XMAL based application. It also used
to develop the Windows 7 applications. Prism mainly helps to design the loosely
coupled components which can be easily integrated with the other components
of the overall application. Prism mainly used to build the composite applications
which need various other components to be integrated.
186

Prism mainly guides of creating the applications using the Model-View-ViewModel


(MVVM) model, Managed Extensibility Framework (MEF), and navigation in the
application.
To use the Prism framework, we need to use their library called as Prism Library.
So prism Library is the inbuilt set of components which can be used in
developing the WPF and Silverlight applications.
You can go through the below link for more details and the use of the
components of the Prism framework:
http://msdn.microsoft.com/en-us/library/ff648465.aspx

62. Dependency Injection, Event Aggregator.


A. For the details about the dependency injection, you can follow the below link:
http://wpftutorial.net/ReferenceArchitecture.html

EventAggregator : It is the utility service which contains the events and allows
the decouple the publisher and subscriber so that they can be buildup
independently. Decouple is primarily useful when a new module needs to be
added or removed or modified. The new module can be added as per the event
fired and defined in the shell.
For more details about the Event Aggregator, you can follow the below link:
http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.20).aspx

63. Shell, Bootstrapper and Region Managers


A. Bootstrapper:- An utility in WPF engine which is mainly responsible for the
initialization of the application by using the composite application library. By
using the bootstrapper we can find out how the components of the application
are wired up in the composite application library. The bootstrapper responsibility
to create the Shell or main window. Composite application library has the default
abstract class UnityBootstrapper which actually handles the initialization.
You can go through the below link for more details about the bootstrapper:

http://msdn.microsoft.com/en-us/library/ff921139(v=pandp.20).aspx

Region and Region Managers: This is concept of Prism framework. We define the
region through XAML code and once a region is defined, automatically it will be
registered with the RegionManager. Actually the Bootstrapper registers a service
called the RegionManager at run time. RegionManager is a dictionary where the
key is name of the region. The value of the key is the reference of the IRegion
interface. RegionAdapter is used to create the instance reference of the IRegion
interface.
You can go through the below link for more details about the Region and Region
Manager:
http://msdn.microsoft.com/en-us/magazine/cc785479.aspx#id0090091

64. What are MEF and Unity?


A. The MEF (Managed Extensibility Framework) is the new concept in .net 4.0. It
is used to create the lightweight and extensible applications to create Managed
Extensibility Framework. It is not only allows the extension but also reused
within the application. Extension can be easily encapsulating the code using the
MEF.
For more details, you can go through the below link:

http://msdn.microsoft.com/en-us/library/dd460648.aspx
65. How to navigate to another page?
A. There is a class NavigationService which can be used for navigation of the
187

WPF window:
this.NavigationService.GoForward();
//or
this.NavigationService.Navigate("MysecondPage.xaml")

ASP.Net Interview Question and Answer for 2+ or 3+ years


experience
1.) What is asp.net life cycle ?
Life Cycle Events
PreInit
The properties like IsPostBack have been set at this time.
This event will be used when we want to:

1.

Set master page dynamically.

2.

Set theme dynamically.

3.

Read or set profile property values.

4.

This event is also preferred if want to create any dynamic controls.

Init
Raised after all the controls have been initialized with their default values
and any skin settings have been applied.
1.

Fired for individual controls first and then for page.


LoadViewState
2.

1.

Fires only if IsPostBack is true.

Values stored in HiddenField with id as _ViewState decoded and stored


into corresponding controls.
LoadPostData
2.

Some controls like:


1.

Fires only if IsPostBack is true.

Some controls like Textbox are implemented from IPostBackDataHandler


and this fires only for such controls.
2.

In this event page processes postback data included in the request object
pass it to the respective controls.
PreLoad
3.

188

Used only if want to inject logic before actual page load starts.

Load

Used normally to perform tasks which are common to all requests, such
as setting up a database query.
Control events
1.

This event is fired when IsPostBack is true.

Use these events to handle specific control events, such as a Button


control's Click event or a TextBox control's TextChanged event.
PreRenderRaised after the page object has created all the controls that are
required for rendering which includes child controls and composite controls.
2.

Use the event to make final changes to the contents of the page or its
controls before the values are stored into the viewstate and the rendering stage
begins.
1.

Mainly used when we want to inject custom JavaScript logic.


SaveViewState
2.

All the control values that support viewstate are encoded and stored into
the viewstate.
RenderGenerates output (HTML) to be rendered at the client side.
We can add custom HTML to the output if we want here.

Unload
Fired for individual controls first and then for page.
2. Used to perform cleanup work like closing open files and database
connections.
1.

2.) How the request is handled by IIS ?


We give an URL to an aspx page in the browser address bar and press enter.
What happens next? We get the response in terms of rendered HTML but how?
We are requesting something from the browser, which means indirectly we
are requesting something from the Web Server, that means IIS. IIS, based on
the file extension, decides which ISAPI extension can serve the request.
1.

And in case of ASP.Net (.aspx) it will be aspnet_isapi_dll so the request is passed


to it for processing.

189

2.

When the first request comes to the website,

an application domain is created by the ApplicationManager class where exactly


the website runs, and which creates an isolation between 2 web applications.
Within the application domain an instance of the HostingEnvironment class is
created which provides access information about the application such as the
name of the folder where the application is stored.
Next ASP.Net creates core objects like HttpContext,
HttpRequest,HttpResponse.
3.

Finally the application starts by creating an instance of the HttpApplication


Class (which can be reused for multiple requests to maximize performance).
3.) What is Difference between Session and Cookies ?
4.

The basic and main difference between cookie and session is that cookies are
stored in the user's browser but sessions can't store in user's browser. This
specifies which is best used for.
A cookie can keep all the information in the client's browser until deleted. If a
person has a login and password, this can be set as a cookie in their browser so
they do not have to re-login to your website every time they visit. You can store
almost anything in a browser cookie.
Sessions are not reliant on the user allowing a cookie. They work like a token
in the browser which allowing access and passing information while the user has
opened his browser. The problem in sessions is when you close the browser the
session will automatically lost. So, if you had a site requiring a login, this
couldn't be saved as a session but it can be saved as a cookie, and the user has
to re-login every time they visit.
cookies are nothing but a small piece of information on the client machine.
before we create a cookies we should check whether the cookies are allowed at
the browser side. They are limited in a size 4k.(they are 2 types of cookies
peristant cookie , and session cookies)
Sessions cookies are stored in a server memory during the client browser
session.When the browser is closed the session cookies are lost.
4.) Advantages and disadvantages of Session?
Following are the basic advantages and disadvantages of using session. I have
describe in details with each type of session at later point of time.
Advantages:

It helps maintain user state and data all over the application.

It is easy to implement and we can store any kind of object.


190

Stores client data separately.

Session is secure and transparent from the user.

Disadvantages:

Performance overhead in case of large volumes of data/user, because


session data is stored in server memory.
Overhead involved in serializing and de-serializing session data, because
in the case of StateServerand SQLServer session modes, we need to serialize the
objects before storing them.
Besides these, there are many advantages and disadvantages of session that are
based on the session type. I have discussed all of them in the respective
sections below.
5). What is state management?
Ans: State management is the process by which you maintain state and page
information over multiple requests for the same or different pages.
6). Http is stateless, What does this mean?
Ans: Stateless protocol is a communications protocol that treats each request as
an independent transaction that is unrelated to any previous request so that the
communication consists of independent pairs of requests and responses.
7). What is Session?
Ans: We know that Http is stateless, means when we open a webpage and fill
some information and then move to next page then the data which we have
entered will lost.
It happed do to Http protocol stateless nature. So here session come into
existence, Session provide us the way of storing data in server memory. So you
can store your page data into server
memory and retrieve it back during page postbacks.
8). What are the Advantage and disadvantage of Session?
Ans: Advantages:
Session provide us the way of maintain user state/data.
It is very easy to implement.
One big advantage of session is that we can store any kind of object in it. :eg,
datatabe, dataset.. etc
By using session we don't need to worry about data collesp, because it store
every client data separately.
Session is secure and transparent from the user.
Disadvantages:
Performance overhead in case of large volumes of data/user, because session
data is stored in server memory.
Overhead involved in serializing and de-serializing session data, because in the
case of StateServer and SQLServer session modes, we need to serialize the
191

objects before storing them.


9). What is Session ID in Asp.net?
Ans: Asp.Net use 120 bit identifier to track each session. This is secure enough
and can't be reverse engineered. When client communicate with server, only
session id is transmitted, between them. When client request for data, ASP.NET
looks on to session ID and retrieves corresponding data.
10). By default where the sessions ID's are stored ?
Ans: By default, the unique identifier for a session is stored in a non-expiring
session cookie in the browser. You can specify that session identifiers not be
stored in a cookie by setting the cookieless attribute to true in the sessionState
configuration element.
We can also configure our application to store it in the url by specifying a
"cookieless" session
The ASP Session cookie has this format:ASPSESSIONIDACSSDCCC=APHELKLDMNKNIOJONJACDHFN

11). Where does session stored if cookie is disabled on clients machine?


Ans: If you want to disable the use of cookies in your ASP.NET application and
still make use of session state, you can configure your application to store the
session identifier in the URL instead of a cookie by setting the cookieless
attribute of the sessionState configuration element to true, or to UseUri, in the
Web.config file for your application.
The following code example shows a Web.config file that configures session state
to use cookieless session identifiers.
Code:
<configuration>
<system.web>
<sessionState
cookieless="true"
regenerateExpiredSessionId="true"
timeout="30" />
</system.web>
</configuration>

12). Can you describe all the property set in web.config under session
state?
Ans:
Code:
<configuration>
<sessionstate
mode="inproc"
cookieless="false"
timeout="20"

192

sqlconnectionstring="data source=127.0.0.1;user id=<user


id>;password=<password>"
server="127.0.0.1"
port="42424"
/>
</configuration>

Mode: The mode setting supports three options: inproc, sqlserver, and
stateserver. As stated earlier, ASP.NET supports two modes: in process and out
of process. There are also two options for out-of-process state management:
memory based (stateserver), and SQL Server based (sqlserver). We'll discuss
implementing these options shortly.
Cookieless: The cookieless option for ASP.NET is configured with this simple
Boolean setting.
Timeout: This option controls the length of time a session is considered valid.
The session timeout is a sliding value; on each request the timeout period is set
to the current time plus the timeout value
Sqlconnectionstring: The sqlconnectionstring identifies the database connection
string that names the database used for mode sqlserver.
Server: In the out-of-process mode stateserver, it names the server that is
running the required Windows NT service: ASPState.
Port: The port setting, which accompanies the server setting, identifies the port
number that corresponds to the server setting for mode stateserver.
13). What are Session Events?
Ans: There are two types of session events available in ASP.NET:
Session_Start
Session_End
You can handle both these events in the global.asax file of your web application.
When a new session initiates, the session_start event is raised, and the
Session_End event raised when a session is abandoned or expires.
14). How you can disable session?
Ans: If we set session Mode="off" in web.config, session will be disabled in the
application. For this, we need to configure web.config the following way:
Code:
<configuration>
<sessionstate Mode="off"/>
</configuration>

15). If I have more than one version of one assemblies, then how will I
use old version (how/where to specify version number?) in my
application?
Ans.The version number is stored in the following format: . The assembly
manifest can then contain a reference to which version number we want to use.

193

16). How do you create threading in.NET? What is the namespace for
that?
Ans.
System.Threading;
//create new thread using the thread classs constructor
Thread myThread = new Thread(new ThreadStart (someFunction));
17). What do you mean by Serialize and MarshalByRef?
Serialization is the act of saving the state of an object so that it can be recreated
(i.e deserialized) at a later date.
The MarshalByRef class is part of the System.Runtime.Remoting namespace and
enables us to access and use objects that reside in different application
domains. It is the base class for objects that need to communicate across
application domains. MarshalByRef objects are accessed directly within their
own
application domain by using a proxy to communicate. With MarshalByValue the a
copy of the entire object is passed across the application domain
18). What is the difference between Array and LinkedList?
An array is a collection of the same type. The size of the array is fixed in
its declaration.
A linked list is similar to an array but it doesnt have a limited size.
19). What is Asynchronous call and how it can be implemented using
delegates?
A synchronous call will wait for a method to complete before program flow is
resumed. With an asynchronous call the program flow continues whilst the
method executes.
//create object
SomeFunction objFunc = new SomeFunction();
//create delegate
SomeDelegate objDel = new SomeDelegate(objFunc.FunctionA);
//invoke the method asynchronously (use interface IAsyncResult)
IAsyncResult asynchCall = SomeDelegate.Invoke();
20). How to create events for a control? What is custom events? How to
create it?
Ans.
An event is a mechanism used in a class that can be used to provide a
notification when something interesting happens. (typical evens in a windows
application
include: change text in textbox, double click or click a button, select an item in
dropdown box).
194

A custom event is an event created by the user that other developers can use.
For example assuming that we have a CashTransaction class and we have a
bank
balance property in that class. We may want to set-up an event that provides a
notification when the bank balance drops below a certain amount. In order to
produce an event the process would be roughly as follows:
Create the class for the event derived from EventArgs.
Create a delegate with a return type of void.
Create a class containing the method that will activate the event.
Create a class with methods to handle the event.
21). If you want to write your own dot net language, what steps you
will you take care?
We will need to ensure that the high level code is compiled to MSIL (Microsoft
intermediate language) so that it can be interpreted by the CLR.
22). Describe the diffeerence between inline and code behind - which is
best in a loosely coupled solution?
The term code behind refers to application code that is not embedded within
the ASPX page and is separated out into a separate file which is then referenced
from the ASPX page. Inline code is the traditional ASP architectural model where
business logic code was embedded within the ASP page. Separating the
business
logic code from the presentation layer offers several advantages:
1) It allows graphic designers and web developers to work on the presentation
layer whilst the application developers concentrate on the business logic.
2) The codebehind file is compiled as a single dll increasing the efficiency of the
application,
3) The codebehind model offers a true OO development platform,
4) It speeds up development time as it allows developers to fully maximise the
features of the .NET framework such as Cahing, ViewState, Session, Smart
Navigation etc.
5) Code is much easier to maintain and susceptible for change.
6) The compiler and VS.NET provides much better support for error checking,
intellisense and debugging when using the code behind model.
23). How dot net compiled code will become platform independent?
The raison detre for .NET was to cater for multiples languages on a single
windows platform whereas the aim of Java was to be a single language on
multiple
platforms. The only way that .NET can be platform independent is if there is a
version of the .NET framework installed on the target machine.
24). Without modifying source code if we compile again, will it be
generated MSIL again?
Ans.No.
195

25). How does you handle this COM components developed in other
programming languages in.NET?
Ans.
use TlbImp.exe to import the COM types into your .NET project. If no type
library for the COM component then use System.Runtime.InteropServices
use RegAsm.exe to call a .NET developed component in a COM application.
26). How CCW (Com Callable Wrapper) and RCW (Runtime Callable
Wrappers) works?
CCW:
proxy
RCW:
proxy

When a COM application calls a NET object the CLR creates the CCW as a
since the COM application is unable to directly access the .NET object.
When a .NET application calls a COM object the CLR creates the RCW as a
since the .NET application is unable to directly access the .COM object.

27). What are the new thee features of COM+ services, which are not
there in COM (MTS)?
Role based security.
Neutral apartment threading.
New environment called context which defines the execution environment
28). What are the differences between COM architecture and.NET
architecture?
.Net architecture has superseded the old COM architecture providing a flexible
rapid application development environment which can be used to create
windows,
web and console applications and web services. .NET provides a powerful
development environment that can be used to create objects in any .NET
compliant language.
.NET addresses the previous problems of dll hell with COM by providing strongly
named assemblies and side-by-side execution where two assemblies with the
same name can run on the same box.
29). Can we copy a COM dll to GAC folder?
Ans.
No. It only stores .NET assemblies.
30). What is Shared and Repeatable Inheritance?
Shared Inheritance-: Shared Inheritance-: ITt is multiple times using same
class. The mechanism of deriving a new class from an existing class is called
inheritance. Shared inheritance introduces a new opportunity of ambiguity and
additional implementation complexity. Assume D inherits from B and C, both of
which inherits from A. Here A in shared. Single copy made from both derived
classes is called shared inheritance.
196

31). Can you explain what inheritance is and an example of when you
might use it?
Ans.
Inheritance is a fundamental feature of any OO language. It allows us to inherit
the members and attributes from a base class to a new derived class. This
leads to increased code reusability and also makes applications easier to
develop, maintain and extend as the new derived class can contain new features
not
available in the base class whilst at the same time preserving the attributes
inherited from the base class.
32). How can you write a class to restrict that only one object of this
class can be created (Singleton class)?
Ans.
Use the singleton design pattern.
public sealed class Singleton
{
static readonly Singleton Instance=new Singleton();
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return Instance;
}
}
}
33). What are virtual destructures?

A constructor can not be virtual but a destructor may. Use virtual destructors
when you want to implement polymorphic tearing down of an object.
34). What is close method? How its different from Finalize and
Dispose?
finalise is the process that allows the garbage collector to clean up any
unmanaged resources before it is destroyed.
The finalise method can not be called directly; it is automatically called by the
CLR. In order to allow more control over the release of unmanaged resources
197

the .NET framework provides a dispose method which unlike finalise can be
called directly by code.
Close method is same as dispose. It was added as a convenience.
35). What is Boxing and UnBoxing?
Ans.
Boxing is the process of converting a value type to a reference type. More
specifically it involves encapsulating a copy of the object and moving it from
stack to heap. Unboxing is the reverse process.
36). What is check/uncheck?
Ans.
checked: used to enable overflow checking for arithmetic and conversion
functions.
unchecked: used to disable overflow checking for arithmetic and conversion
functions
37). What is the use of base keyword? Tell me a practical example for
base keywords usage?
Ans.
The base keyword is used to access members of the base class from within a
derived class:
* Call a method on the base class that has been overridden by another method.
* Specify which base-class constructor should be called when creating instances
of the derived class.
A base class access is permitted only in a constructor, an instance method, or an
instance property accessor.
It is an error to use the base keyword from within a static method.
Example:In this example, both the base class, Person, and the derived class,
Employee, have a method named Getinfo. By using the base keyword,
it is possible to call the Getinfo method on the base class, from within the
derived class.
// keywords_base.cs
// Accessing base class members

using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
198

}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass {
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}

38). Difference Between Query String and Session


Querystring

Session

Querystring is client side state


management technique.

Session is server side state


management technique.

Querystring data is page specific i.e. can


be accessed in that page only.

Session data can be accessed


throughout the session.

Querystring data is visible to user and can


be seen in browser url.

Session data is not visible to user.

Data is not secured and can be altered


hence insensitive data is stored in
querystring.

Data is secured hence sensitive


data such as user information is
stored.

Querystring has constraint of Maxlength.

Session does not have such


constraint.

39). Difference between Query string and Cookies


199

cookies is a text file stored on client machine when we surf ant thing on
internet by the server automatically we dont have to create it
query string is used to transfer data from 1 page to anothe but this is not safe
s it shows in url what data we r sending
pen any site and see url after question mark tht is url
Cookies: - Cookies are little pieces of information that a server stores on a
browser. They are of two types
1. Temporary cookie
2. Persistent cookie
Temporary cookie: - They are also known as session cookies. These are volatile
in nature. When the browser is shutdown they are erased.
Persistent cookie:- These may be called as permanent cookies. These are
especially saved in files. It may remain for a month or year.
Properties of cookies
Some properties of cookie
Name: - represent the name of cookie.
Name value: - represent a collection of key values of cookie
Domain: - represent the domain associated with a specific cookie.
Path: - the path associated with a cookie.
Expires: - expired time of cookie.
Hashkey: - identifies whether the cookie is a cookie dictionary.
Secure: - specifies whether the cookie is to be sent in an encrypted connection
or not
Query string is the limited way to pass information to the web server while
Transferring from one page to another page. This information is passed in url of
the request. see below the code sample

Code Sample
//Retrieving values from query string
String name;
//Retrieving from query string
name = Request.Param["umar"].ToString();
But remember that many browsers impose a limit of 255 characters in query
strings. You need to use HTTP-Get method to post a page to server otherwise
query string values will not be available.

40). How can we identify that the Page is Post Back?


Page object has an "IsPostBack" property, which can be checked to know that is
the page posted back.
200

41). What is the lifespan for items stored in ViewState?


PThe items stored in ViewState live until the lifetime of the current page expires
including the postbacks to the same page

42). What is AutoPostBack?


If you want a control to postback automatically when an event is raised, you
need to set the AutoPostBack property of the control to True

43). Why do you use the App_Code folder in ASP.NET?


The App_Code folder is automatically present in the project. It stores the files,
such as classes, typed data set, text files, and reports. If this folder is not
available in the application, you can add this folder. One of the important
features of the App_Code folder is that only one dll is created for the complete
folder, irrespective of how many files it contains.

44). In which event of page cycle is the ViewState available?


After the Init() and before the Page_Load().

45). How long the items in ViewState exists?


They exist for the life of the current page.

46). Where the viewstate is stored after the page postback?


ViewState is stored in a hidden field on the page at client side. ViewState is
transported to the client and back to the server, and is not stored on the server
or any other external source.

47). What are the different Session state management options


available in ASP.NET?
1.

In-Process

2.

Out-of-Process.

In-Process stores the session in memory on the web server.


Out-of-Process Session state management stores data in an external server.
The external server may be either a SQL Server or a State Server. All objects
stored in session are required to be serializable for Out-of-Process state
management.

201

48). What is the difference between web config and machine


config?
Web config file is specific to a web application where as machine config is
specific to a machine or server. There can be multiple web config files into an
application where as we can have only one machine config file on a server.

49). What are the different types of cookies in ASP.NET?


Session Cookie Resides on the client machine for a single session until the
user does not log out.
Persistent Cookie Resides on a users machine for a period specified for its
expiry, such as 10 days, one month, and never.

50). What is the difference between ExecuteScalar and


ExecuteNonQuery?
ExecuteScalar returns output value where as ExecuteNonQuery does not return
any value but the number of rows affected by the query. ExecuteScalar used for
fetching a single value and ExecuteNonQuery used to execute Insert and Update
statements.

2 yr experinced interview
i would like to share my experience of interview conducted on last week.It may
help others who are looking for job change.
The interview was technical face to face interview.
Duration:45 mins
Here are the questions.
* what are the technologies you have used ?
* what is grid view?
* write a code to bind dropdownlist in grid view?
* Are you good in writing stored procedures in sql server?
* what are the differences b/w stored procedures and function?
* what are the data types available in sql server?
* what are the differences b/w char,var char and nvarchar?
* Explain transaction management in sql ?
* Can u write an example for commiting an transaction and rollback of a
transaction.?
* How to generate reports?
* How to generate reports in c#?
* Explain rdlc?
* Explain Master Page?
* Explain the Projects u have worked?

202

Dot net 3.6 Years of Experience Interview


Questions
Hai Friends,
Recently i have attended one interview and i have share my interview
experience very happily with you.
This experience will use you for your future for many interviews.
These are first two questions in technical round
1. What are the technologies you are used ?
2 .How many projects you have worked on with client names on which
technology?
after that the interviewer asked on these questions.
total Duration 1:40 mins. (Technical round only)
in Asp.Net
1. What is the use of session state and application state and
difference between them?
2. ASP Page life cycle events ?
3. Use of gloabl.asax file ?
4. How to handle sessions ?
5. How to handle application level errors?
6. How to handle method level errors?
7. Can i use more than one web.config file in solution?
8. Can i use more than one web.config file in project?
9. What is view state?
10.What is cookies ? use of cookiless session ?
11.Session modes ?
12.What is the use of rendering event ?
13.Diff between datagrid and gridview in asp.net ?
14.How to get values using javascript and jquery?
15.How to call client side functions using javascript and jquery
16.How to stop/ kill the session?
17.How to write ajax calling using jquery ?
18.Use of globalization and localization ?
19.Difference between user control and custom control ?
20.How to call Master Page methods in our web page ?
21.Diff between .ascx and .asmx ?
22.Diff types of validations ?
23.What is update panel ?
24.How to register user control in web page ?
in C#
1. Assembly types and how to create assembly and how to create strong
name ?
203

2. Diff between interface and abstract and virtual?


3. static polymorphism and dynamic polymorphism?
4. Late binding and early binding ?
5. What is inheritance and types of inheritance?
6. When you used interface in your application ?
7. How t use abstract class in your application ?
8. What is function overloading and function overriding?
9. What is the use of new key word ?
10.Use of const, readonly ?
11.What is GAC ?
12.Diff between finalize and dispose ?
13.Use of stack and heap ?
14.How to create object to abstract class ?
15.How to write multiple inheritance ? \
16.Difference between string and stringBuilder ?
17.What is Delegate ?
18.What is anonymus Functions ?
in SQL Server
1.
2.
3.
4.
5.
6.
7.
8.

What is procedure and function . What is the difference ?


What is DDL and DML ?
Can we write nested procedures if yes how to write and execute?
How to write transactions?
What is the trigger and types? How to Write Triggers?
Use of triggers
What is the Courser and use?
What is the CTE ?

in WCF
1. How to consume WCFservice in our application?
2. How to get json data using WCF service ?
3. Different contracts in wcf
4. What is ABC?
5. What is mexhttp bindng?
6. Binding types in WCF?
7. Modes in WCF?
8. How many types of Hosting in WCF service ?
9. What is SOAP ?
10.Which namespace is used for XML Serialization ?
then next Round is Project Manager Round. in this round the interviewer
focused not only on projects but also some real time questions . it took nearly
(1:20 min Manager round only)
These are first two questions in project manager round
1. What are the technologies you are used ?
204

2 .How many projects you have worked on with client names on which
technology and explain any two projects briefly ?
in Manager Round the interview asked these questions..
1. I have one WCF service with 5 methods ? how to give 2 methods to client
1 and remaining three to client 2 . How to restrict access the remaining 3
methods to client 1 and same as client 2 the remaining 2 methods ?
2. When we use Message Contract ?
3. How to use Shared assembly ?
4. How to show second 100 records to client ?
5. How to get data from web.config
6. Diff between web.confing and app.config ?
7. I have wrote one method with try catch block. in try block i have write int
a = 100 / 0 ; , but there is no "dividebyzero exception" in catch block. how
to throw that exception to catch block ?
8. what is Collections ? diff between List and IEnumarable ?
MICROSOFT INTERVIEW QUESTIONS .NET 3+ YEARS EXPERIENCED
Hi friends,
I attened interview(06/09/2014) recently to microsoft in Bangalore,India. It was so good to
shortlist my resume why because they shortlisted only 10-15 members on that day but only
few pepole came for interview..I'm happly gone for the interview..About my experience in that
interview i'm sharing some of the questions as what they asked me. Most of the they are
asking logically(how internally working) and practical things.
In First round of interview has prescreening test and it's around 30Mins.
Second Round Of interview has Technical discussion and it's around 2 Hr 30 Mins..

1)
2)
A)
3)

Tel me about yourself briefly and what your have done in between 3 years of your carrier?
Which domain will you prefer if we give business opportunity? Why should we take about it?
Windows Azure.
Why you prefer windows azure and there are so many languages and is there any special
about it?
4) Have you worked any design pattern ?
A) MVC Design pattern I worked
5) Do you know the types of design patterns?
A) Yes I know and I told about Abstract and Singleton and MVC and so on
6) What is singleton pattern ?
7) Have you worked on Azile methodologies ? No
8) What is the CLR ? How it works ?
9) What is CLR and Base Class Libraries?
10) What is IL ?
11) What is Managed Code and unmanaged code?
12) Suppose if develop one application in .net and after compilation which format is coming?
A) .exe
13) .exe how it produces any techniques are there?
14) Once building the application in mean time JIT or CLR unexpectedly stopped whether its
MSIL or Binary format?
205

15)
16)
17)
18)
19)
20)
21)
22)
23)
24)
25)
26)

What will happen in JIT and how it works?


I write a code on console application and what is that code?
MSIL will understand the all languages?
What is inheritance and with example?
What is method overloading and method overriding with example ?
What is virtual method and how describe it?
What is boxing and unboxing?
Which memory object will be stored?
Can we allocate a size for a object of class?
Can we create dynamic object in C# and what is the DynamicObject ?
He drawn Rectangle diagram and its machine where is stack and heap will be there?
What is use of new keyword? And not only for creating object is there other way to use new
keyword?
27) What is destructor? And example?
28) What is garbage collector and how it will work internally?
29) What is finalize and dispose?
30) What is Idisposable? As i answerd : Interface(then he asked me about with in a dispose
method can we write the interface like Idisposable as of you told to clean a object?
31) What is assembly?
32) What is difference between dll and exe?
33) For dll and .exe which library templates will be needed ?
34) .exe will understand the CLR?
35) With out creating an object for class and no need to call via classname.methodname ?how
its possible ?
36) What is checked statements in C# ?
37) What is using in c# ? why its necessary ?
38) What is the username of anonymous login ?
39) What is anonymous method in C# ?
40) What is extension method in C#?
41) What is authorization and authentication?
42) How you will protect your web site from hackers?
43) C# purily object oriented ?
44) Can we override the Web config file and how ?
45) How to encrypt and decrypt the web config file ?
46) How to update the web.config programmatically?
47) What is difference between entity framework and linq?
48) When you are writing linq query while select which binding will occur like early or late or
eager?
49) Some list of items in Departmental Store having ProductId, Date, Price and write a query for
who is latest price in each departmental store ?
50) What is MVC ?
51) What is MVC life cycle and request flow of MVC ?
52) What is MapRoute method in MVC ?
53) Different types of view engines ?
206

54)
55)
56)
57)
58)
59)
60)
61)
62)
63)

What is Noramalization and Describe briefly ?


What is Indexseek and Indexscan?
How many type of index and with example ?
How many cluster index we can create for one table?
How many non cluster index we can create for one table ?
How many types of constraints ?
ACID Properties in transaction ?
Difference between join and sub query?
Take a Relationship for a School and draw a relationship for each?
What is testing and how you will do particular method? Can you write test case template ?

64) What is Unit Testing and System Testing and who will do both testing ?

207