Friday, March 27, 2009

.Net Framework Questions (Set 2)



Note: Please naviagate to the other set of questions by clicking the links in the "Other Questions" section on the right hand side
What is CODE Access security?
.Net Framework provides sceurity at the code level also which is known as code access security (CAS). CAS is part of .NET security model that determines whether or not a piece of code is allowed to run and what resources it can use while running. Example CAS will allow an application to read but not to write and delete a file or a resource from a folder. CAS settings can be done using Caspol.exe tool.
What is a satellite assembly?
When we use the same application for different languages we use resources files (.resx files) to show the same application in different languages. These resources when formed as an assembly are called as satellite assembly.

How to prevent my .NET DLL to be decompiled?
When we compile any .net code it gets compiled in to MSIL. This MSIL code can easily be reverse engineered by using ILDASM tool. However we can prevent the .net dlls to be decompiled by using "obfuscation". For obfuscation we can either use any third part tool or dotfuscator tool provided by Microsoft.
What is the difference between Convert.ToString and .ToString() method ?
The Convert.ToString("") will handle NULL values where as .ToString() will not.
What is Native Image Generator (Ngen.exe)?
The Native Image Generator utility (Ngen.exe) allows you to run the JIT compiler on your assembly's MSIL and generate native machine code which is cached to disk. After the image is created .NET runtime will use the image to run the code rather than from the hard disk. Running Ngen.exe on an assembly potentially allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically.

If we have two version of same assembly in GAC how do we make a choice ?
The choice of version can be made in the config file. Below code shows an example

What is AL (Assembly Linker)?
As you are aware assembly can be of either single file type or it can contain multiple file type. When you want to add a file to assembly you can use assebmly linker.
What are the key elements of an assembly?
Portable Executable header , Metadata, MSIL
How many manifest an assembly can have?
One
What are Generations in Garbage collection.
Garbage collection has 3 generations. Generation 0, Generation 1 and Generation 2. When the object is first created it is created in the Generatin 0. When the garbage collector runs it clears the unused memories and pushes the objects that are in use to Generation 1. This way Garbage collector makes more space for the new objects in Generation 0. When the Generation 1 is full again it runs and moves the unused items to generation 2. The objects in Generation 0 are newly created and the one in Generation 1 are the oldest.
Other ASP.Net related interview questions are available at
Set 1 of ASP.Net Interview questions or Asp.Net FAQs

Tuesday, March 24, 2009

.Net Framework Questions (Set 1)



Note: Every set is having 20 questions each. Please naviagate to the other set of questions by clicking the links in the "Other Questions" section on the right hand side

What is IL or MSIL?
Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. This 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 is a CLR?
Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Following are the responsibilities of CLR
* Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management.
* Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.
* Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
* IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.


What is a CTS?
In order that two language communicate smoothly CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.
What is a CLS(Common Language Specification)?
This is a subset of the CTS which all .NET languages are expected to support. It was always a dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

What is a Managed Code?
Managed code runs inside the environment of CLR i.e. .NET runtime. In short all IL are managed code. But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.
What is an Assembly?
* Assembly is unit of deployment like EXE or a DLL.
* An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.
* An assembly is completely self-describing. An assembly contains metadata information, which is used by the CLR for everything from type checking and security to actually invoking the components methods. As all information is in the assembly itself, it is independent of registry. This is the basic advantage as compared to COM where the version was stored in registry.
* Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other. Assemblies can be private or shared. For private assembly deployment, the assembly is copied to the same directory as the client program that references it. No registration is needed, and no fancy installation program is required.70 When the component is removed, no registry cleanup is needed, and no uninstall program is required. Just delete it from the hard drive.
* In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.
What are the different types of Assembly?
There are two types of assembly Private and Public assembly. A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. Crystal report classes which will be used by all application for Reports.

What is Namespace?
Namespace has two basic functionalities:-
1. Namespace Logically group types, example System.Web.UI logically groups our UI related features.
2. In Object Oriented world many times it is possible that programmers will use the same class name. By qualifying Namespace with classname this collision can be avoided.
What is Difference between Namespace and Assembly?
Following are the differences between namespace and assembly:
1. Assembly is physical grouping of logical units. Namespace logically groups classes.
2. Namespace can span multiple assemblies.
What is Manifest?
Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things (See Figure Manifest View for more details):
· Version of assembly
· Security identity
· Scope of the assembly
· Resolve references to resources and classes.
· The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a stand-alone PE file that contains only assembly manifest information.
Where is versionBold information stored of an assembly?
Version information is stored in assembly in manifest.

Is versioning applicable to private assemblies?
Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in their individual folders.

What is GAC?
GAC (Global Assembly Cache) is used where shared .NET assembly reside. GAC is used in the following situations :-
· If the application has to be shared among several application.
· If the assembly has some special security requirements like only administrators can remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly.
What is garbage collection?
Garbage collection is a CLR feature which automatically manages memory. Programmers forget to release the objects while coding ..... Laziness (Remember in VB6 where one of the good practices is to set object to nothing). CLR automatically releases objects when they are no longer in use and referenced. CLR runs on non-deterministic to see the unused objects and cleans them. One side effect of this non-deterministic feature is that we cannot assume an object is destroyed when it goes out of the scope of a function. we should avoid using destructors because before GC destroys the object it first executes destructor in that case it will have to wait for code to release the unmanaged resource. Result in additional delays in GC. So it is recommended to implement IDisposable interface and write cleaup code in Dispose method and call GC.SuppressFinalize method so instructing GC not to call your constructor.
Can we force garbage collector to run ?
System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arises.

What is reflection?
All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as “Reflection”.System. Reflection can be used to browse through the metadata information.
What are different types of JIT?
JIT compiler is a part of the runtime execution environment. In Microsoft .NET there are three types of JIT compilers:
· Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
· Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.
· Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution.
What are Value types and Reference types ?
Value types directly contain their data which are either allocated on the stack or allocated in-line in a structure. Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same.
What is concept of Boxing and Unboxing ?
Boxing permits any value type to be implicitly converted to type object or to any interface type implemented by value type. Boxing is a process in which object instances are created and copy values in to that instance. Unboxing is vice versa of boxing operation where the value is copied from the instance in to appropriate storage location. Below is sample code of boxing and unboxing where integer data type is converted in to object and then vice versa.
Dim x As Integer
Dim y As Object
x = 10
‘ boxing process
y = x
‘ unboxing process
x = y
New features of C# 4.0 is available at C# 4.0 FAQs or C# 4.0
Basic .Net questions are available at .Net Frame works FAQ or .Net interview question

Sunday, March 22, 2009

C# 4.0 Interview questions



What are the key new features in C# 4.0

The new features in C# 4.0 fall into four groups:
Dynamic lookup
Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime.
Named and optional parameters
Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.
COM specific interop features
Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience.

What is Named and optional argumnent.

C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead any argument can be passed by name. Thus if you want to omit only y from a call of M you can write:
M(1, z: 3); // passing z by name
or
M(x: 1, z: 3); // passing both x and z by name
or even
M(z: 3, x: 1); // reversing the order of arguments
All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1.
Optional and named arguments can be used not only with methods but also with indexers and constructors.

Other ASP.Net related interview questions are available at

Set 1 of ASP.Net Interview questions or Asp.Net FAQs
Set 2 of ASP.Net Interview questions or Asp.Net FAQs

Set 3 of ASP.Net Interview questions or ASP.Net FAQs

Basic .Net questions are available at .Net Frame works FAQ or .Net interview question

ASP.Net interview questions, ASP.Net FAQs (Set 2)





Note: Every set is having 20 questions each. Please naviagate to the other set of questions by clicking the links in the "Other Questions" section on the right hand side

Can a user browsing my Web site read my Web.config or Global.asax files?

No. The 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 an section in a local Web.config file

Is it necessary to lock application state before accessing it?

Only if you're performing a multistep 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, 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, 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, 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 element in 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.



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.

Which two properties are on every validation control?

We have two common properties for every validation controls 1. Control to Validate,2. Error Message.

What property do you have to set to tell the grid which page to go to when using the Pager object?

CurrentPageIndex

What tag do you use to add a hyperlink column to the DataGrid?

Which method do you use to redirect the user to another page without performing a round trip to the client?

Server.transfer

Explain role based security ?

Role Based Security lets you identify groups of users to allow or deny based on their role in the organization. For example 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 element to the authorization list in your Web application's Web.config file. e.g.

<>

< roles="Domain Name\Administrators">

< !-- Allow Administrators in domain. -- >

< users="*">

< !-- Deny anyone else. -- >

< /authorization >

How do you register JavaScript for webcontrols ?

You can register javascript for controls using

What is web.config file ?

Web.config file is the configuration file for the Asp.net web application. There is one web.config file for one asp.net application which configuresthe particular application. Web.config file is written in XML with specific tags having specific meanings.It includes databa which includesconnections,Session States,Error Handling,Security etc.For example :

<>

<>

< key="ConnectionString" value="server=localhost;uid=sa;pwd=;database=MyDB">

< /appSettings >

< /configuration >

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 make sure the values in two different controls matched?

CompareValidator is used to ensure that two fields are identical.

What is validationsummary server control?where it is 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, 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.

Difference between asp and asp.net?."

ASP (Active Server Pages) 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 webapplications."

What are the various ways of securing a web site that could prevent from hacking etc .. ?

1) Authentication/Authorization

2) Encryption/Decryption

3) Maintaining web servers outside the corporate firewall. etc.,

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

An inproc is one which runs in the same process area as that of the client giving tha advantage of speed but the disadvantage of stability becoz if it crashes it takes the client application also with it.Outproc is one which works outside the clients memory thus giving stability to the client, but we have 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 which 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.


Other ASP.Net related interview questions are available at
Set 1 of ASP.Net Interview questions or Asp.Net FAQs
Set 3 of ASP.Net Interview questions or ASP.Net FAQs
New features of C# 4.0 is available at C# 4.0 FAQs or C# 4.0
Basic .Net questions are available at .Net Frame works FAQ or .Net interview question

ASP.Net interview questions, ASP.Net FAQs (Set 1)



Note: Every set is having 20 questions each. Please naviagate to the other set of questions by clicking the links in the "Other Questions" section on the right hand side

What do you mean by authentication and authorization?

Authentication is the process of validating a user on the credentials (username and password) . After Authentication a user will be verified for performing the various tasks, It access is limited it is known as authorization.

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-script 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 are loaded before the script runs.<%@ Reference Control="MyControl.ascx" %>

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.

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.

How do you set a button say "btnSubmit" button to fire a java script function?

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;

How do I send e-mail from an ASP.NET application?

Using the below code mail can be triggered from a .Net application

MailMessage message = new MailMessage ();

message.From = abc@abc.com;

message.To = xyz@aboc.com;

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.

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, etc. For these you have to make a 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, etc. 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 a possible security hazards for the client computer.

Should validation (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 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, 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 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 any value greater than DataTime.MinValue with respect to the current datetime. If u want the cookie which never expires set its Expires property equal to DateTime.maxValue.

What does the "EnableViewState" property do? Why would I want it on or off?

EnableViewState 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 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,Session_End.

You can optionally include "On" in any of 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.

Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?

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 (same 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 still has to be transferred to the back end using some form of data object.

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 section of the web.config file. The default is 20 minutes.


How do you turn off cookies for one page in your site?

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


Other ASP.Net related interview questions are available at

Set 2 of ASP.Net Interview questions or Asp.Net FAQs

Set 3 of ASP.Net Interview questions or ASP.Net FAQs

New features of C# 4.0 is available at C# 4.0 FAQs or C# 4.0

Basic .Net questions are available at .Net Frame works FAQ or .Net interview question

ASP.Net interview questions, ASP.Net FAQs (Set 3)



Note: Every set is having 20 questions each. Please naviagate to the other set of questions by clicking the links in the "Other Questions" section on the right hand side

What tags do you need to add within the asp:datagrid tags to bind columns manually?
Set AutoGenerateColumns Property to false on the datagrid tag and then use Column tag and an ASP:databound tag
< runat="server" id="ManualColumnBinding" autogeneratecolumns="False"> <>

< headertext="Column1" datafield="Column1">
< headertext="Column2" datafield="Column2"> < /Columns >< /asp:DataGrid >



What does aspnet_regiis -i do ?
Aspnet_regiis.exe is The ASP.NET IIS Registration tool 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 keep track of 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" & setting the machineKey validation type to 3DES. If you want to NOT maintain the ViewState, 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 <> 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.There fore 2 ASP.Net technique in which it is used are Encryption/Decryption & 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 modeLimitations: * 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 <> element of the application's Web.config file, 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 a 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 particular 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 exists.
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, 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, 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 <>, and the DataList wraps the contents in either an HTML <> or <> 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 Repeater control, If we wanted to display the employee names in a bold font we'd have 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 stylistic 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 particular font-face with a particular 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 more noticeably better than that of the DataGrid's. 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:

< mode="RemoteOnly" defaultredirect="Customerror.aspx">
< statuscode="404" redirect="Notfound.aspx">
< /customErrors >
If mode is set to Off, custom error messages will be disabled. Users will receive detailed exception error messages.If mode is set to On, custom error messages will be enabled. If mode is set to RemoteOnly, then users will receive custom errors, but users accessing the site locally will receive detailed error messages.Add an <> 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 hereDim str As System.Text.StringBuilderstr.Append("hi") ' Error Line as str is not instantiatedResponse.Write(str.ToString)End Sub
[Web.Config]
< mode="On" defaultredirect="Error.aspx">' a simple redirect will take the user to Error.aspx [user defined] error file.< mode="RemoteOnly" defaultredirect="Customerror.aspx"> < 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 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.1.Using DataAdapter.fill method give the value of 'Maxrecords' parameter (Note: - Don't use it because query will return all records but fill the dataset based on value of 'maxrecords' parameter).2.For SQL server database, combines a WHERE clause and a ORDER BY clause with TOP predicate.3.If Data does not change often just cache records locally in DataSet and just take some records from the DataSet to display.


Can you create an app domain?
Yes, We can create user app domain by calling on of the following overload static methods of the System.AppDomain class1. 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 which IIS Provides apart from .NET ?
The various security methods which IIS provides are
a) Authentication Modes

b) IP Address and Domain Name Restriction
c) DNS Lookups DNS Lookups
d) The Network ID and Subnet Mask
e) SSL

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

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
· A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
· A DataSet is designed to work without any continuing connection to the original data source.
· Data in a DataSet is bulk-loaded, rather than being loaded on demand.
· There's no concept of cursor types in a DataSet.
· DataSets have no current record pointer You can use For Each loops to move through the data.
· You can store many edits in a DataSet, and write them to the original data source in a single operation.
· Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

Other ASP.Net related interview questions are available at

Set 1 of ASP.Net Interview questions or Asp.Net FAQs
Set 2 of ASP.Net Interview questions or Asp.Net FAQs

New features of C# 4.0 is available at C# 4.0 FAQs or C# 4.0

Basic .Net questions are available at .Net Frame works FAQ or .Net interview question