You are on page 1of 72

ASP.

NET Page Life Cycle Overview


When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls,
restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the
appropriate life-cycle stage for the effect you intend.
Common Life-cycle Events
Page Event Typical Use
PreInit Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
·         Check the IsPostBack property to determine whether this is the first time the page is being processed.
The IsCallback and IsCrossPagePostBack properties have also been set at this time.
·         Create or re-create dynamic controls.
·         Set a master page dynamically.
·         Set the Theme property dynamically.
·         Read or set profile property values.
Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before
the Init event of the page.
Use this event to read or initialize control properties.
InitComplete Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state
changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until
view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking
immediately after they raise their Init event.
Use this event to make changes to view state that you want to make sure are persisted after the next postback.
PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the  Request instance.
Load The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all
controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Use the OnLoad event method to set properties in controls and to establish database connections.
Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
LoadComplete Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be loaded.
PreRender Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls.
(To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of
individual controls occurs after the PreRender event of the page.
Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
PreRenderComplet Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events
e for Data-Bound Controls later in this topic.
SaveStateComplete Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect
rendering, but the changes will not be retrieved on the next postback.
Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have
a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates
only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information,
see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload Raised 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.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other
request-specific tasks.
 
Constructor And Destructor in C#
Constructor
A constructor looks like a special method having no return type and its name is same with the class name.
If we do not declare constructor explicitly for a class, compiler will create a default constructor at run time.
Access modifiers of constructor can be public, private, protected, internal and extern.
1. A public constructor is called when the class is instantiated.
2.  A private constructor prevents the creation of the object of the class. It is used in classes having only static members.
3. A class having internal constructor cannot be instantiated outside of the assembly.
4. A protected constructor of base class can only be called from the derived class within derived class constructor.
5. When a constructor having an extern modifier, the constructor is said to be an external constructor, because the same does not provide any actual
implementation.
Types of Constructor
1. Static Constructor and
2. Instance Constructor
Static Constructor

Static constructors are called before the first instance of the class is created or any static members are accessed or used whichever is earlier.
Features of static constructor:
 A Static constructor cannot be overloaded.
 There is no access modifier in Static constructor and they don't take any arguments also.
 The static constructor for a class executes only once throughout the life time of the program.
 Static constructor does not support Constructor Channing.
 Static constructor can call only static members.
 Static constructor is getting called before instance constructor
//The static constructor for a class executes only once throughout the life time of the program
class CherukuriClass
{
    public CherukuriClass()
    {
        Console.WriteLine("Instance Constructor called");
    }
    static CherukuriClass()
    {
        Console.WriteLine("Static Constructor called");
    }
}
class Program
{
    static void Main(string[] args)
    {
        CherukuriClass objClass1 = new CherukuriClass();
        CherukuriClass objClass2 = new CherukuriClass();
    }
}
//Static constructor is getting called before instance constructor
class CherukuriClass
{
    public CherukuriClass()
    {
        Console.WriteLine("CherukuriClass Default Constructor");
    }
    static CherukuriClass()
    {
        Console.WriteLine("CherukuriClass Static Constructor");
    }
}
class CherukuriChildClass : CherukuriClass
{
    public CherukuriChildClass()
    {
        Console.WriteLine("CherukuriClass Child Constructor");
    }
}
class Program
{
    static void Main(string[] args)
    {
        CherukuriChildClass objChild = new CherukuriChildClass();
    }
}
 
Instance Constructor

Instance constructor is used to create and initialize instance and it is invoked when we create a new object of the class.
 

Features of Constructor
 

1. Constructor cannot be virtual. When constructor is invoked the virtual table would not be available in the memory.
2. Constructor Chaining
Constructor chaining means call one constructor from another constructor. In order to call one constructor from another, we use base (parameters) or: this
(parameters)
We use base (parameters) to call a constructor in the base class and we use this (parameters) to call a constructor in the current class.
 
3.    Inheritance
A constructor of a base class cannot be inherited to its derived class. But base class constructor or parent class constructor can be invoked from derived class or
child class.
 
class CherukuriClass
{
    public CherukuriClass()
    {
        Console.WriteLine("CherukuriClass with Default Constructor");
    }
    public CherukuriClass(int x)
    {
        Console.WriteLine("CherukuriClass Constructor With Single Parameter");
    }
}
class CherukuriChildClass : CherukuriClass
{
    public CherukuriChildClass(): base(10)
    {
        Console.WriteLine("CherukuriChildClass Constructor");
    }
}
class Program
{
    static void Main(string[] args)
    {
        CherukuriChildClass objChild = new CherukuriChildClass();
    }
}
 
 
4.    Overloading
Constructor can be overloaded. In the following code snippet, there are four overloaded constructor:
 
public CherukuriClass() //Default constructor without parameter.
{
 
}
public CherukuriClass(int UserID) //Constructor overloading.
{
 
}
Destructor
Destructors are used to destruct instances of classes. Following are features of destructor:
 A class can have one destructor only.
 Destructors cannot be inherited or overloaded.
 Destructors are invoked automatically.
 Destructor can not have modifiers or parameters.
 When destructor is called, Finalize is called from destructor implicitly.
 
When derived class destructor is called, the base class destructor is also getting called.
class CherukuriClass
{
    ~CherukuriClass()  // Destructor
    {
        //  Here we can write code for cleanup resources
    }
}
 
 
Note
 Base constructor is getting called first. In general, destructors are called in the reverse order of the constructor calls.
 For example, if class A is the base class and class B inherit class A and class C inherit class B. Constructor will be fired for class A first, class B second and at last for
class C.
 But destructor will be fired in reverse order: class C first, class B second and at last for class A.
How to redirect to the login page automatically when session timeout in asp.net using C#

MasterPage.master
MasterPage.master.cs

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    this.HeadContent.Controls.Add(new LiteralControl(
        String.Format("<meta http-equiv='refresh' content='{0};url={1}'>",
        YourSessionTimeoutValue * 60, "Login.aspx")));
}
web.config

<sessionState mode="InProc" cookieless="true" timeout="1"></sessionState>
State Management in ASP.NET
 
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
 
 
Types of State Management
 
There are 2 types State Management:
 
1. Client Side State Management
 
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to
store the state information at the client end are listed down below:
 
View State

Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save
the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore
view state.
 
Sample Code
 
//To Save Information in View State
ViewState.Add("Cherukuri", "Venkateswarlu");
//Retrieving View state
Label1.Text = (string)ViewState["Cherukuri"];
 
 
Control State

If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling
view state.
 
Hidden fields  

Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.
 
Sample Code
 
//Declaring a hidden variable
HtmlInputHidden hidCherukuri = null;
//Populating hidden variable
hidCherukuri.Value = "Venkateswarlu";
//Retrieving value stored in hidden field.
Label1.Text = hidCherukuri.Value;
 
 
Cookies

Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be
available for multiple Web pages on a web site.
 
Sample Code
 
//Storing value in cookie
HttpCookie cookie = new HttpCookie("Cherukuri");
cookie.Value = "Venkateswarlu";
Request.Cookies.Add(cookie);
//Retrieving value in cookie
if (Request.Cookies.Count > 0 && Request.Cookies["Cherukuri"] != null)
    Label1.Text = "Welcome" + Request.Cookies["Cherukuri"].ToString();
else
    Label1.Text = "Welcome Guest";
 
 
Query Strings
Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.
 
Sample Code
 
//Storing value in query(url)
Response.Redirect("Default.aspx?Cherukuri=Venkateswarlu");
//Retrieving from query string
Label1.Text = Request.Params["Cherukuri"].ToString();
 
 
 
2. Server Side State Management
 
ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client.
 
Application State

Application State information is available to all pages, regardless of which user requests a page.
 
Sample Code
 
//Stroing information in application state
lock (this)
{
    Application["Cherukuri"] = "Venkateswarlu";
}
//Retrieving value from application state
lock (this)
{
    string str = Application["Cherukuri"].ToString();
}
 
 
Session State

Session State information is available to all pages opened by a user during a single visit.
 
Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile
properties.
 
Sample Code
 
//Storing informaton in session state
Session["Cherukuri"] = "Venkateswarlu";
//Retrieving information from session state
Label1.Text = Session["Cherukuri"].ToString();
 
 
Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not
lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The
ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database.
 
 
Advantages
 
 
Advantages of Client Side State Management:
 
1. Better Scalability:

With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of
simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that
potential bottleneck.
 
2. Supports multiple Web servers:

With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all
the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server
does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent
load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web
servers access).
 
Advantages of Server Side State Management:
 
1. Better security:
Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use
client-side state management to store confidential information, such as a password, authorization level, or authentication status.
 
2. Reduced bandwidth:

If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times,
potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections.
Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.
Encrypt and Decrypt strings in Dot Net for Sensitive Data Like Passwords
Encryption Method

public string Encrypt(string secureUserData , bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(secureUserData );
    string key = string.Empty;
    byte[] resultArray;
 
    key = ConfigurationManager.AppSettings.Get("SecurityKey");
 
    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        hashmd5.Clear();
    }
    else
    {
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }
    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    tdes.Key = keyArray;
    tdes.Mode = CipherMode.ECB;
    tdes.Padding = PaddingMode.PKCS7;
 
    ICryptoTransform cTransform = tdes.CreateEncryptor();
    resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    tdes.Clear();
 
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
Decryption Method

 
public string Decrypt(string cipherString, bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = Convert.FromBase64String(cipherString);
    byte[] resultArray;
    string key = string.Empty;
 
    key = ConfigurationManager.AppSettings.Get("SecurityKey");  // Get the key from Web.Config file
 
    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        hashmd5.Clear();
    }
    else
    {
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }
    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    tdes.Key = keyArray;
    tdes.Mode = CipherMode.ECB;
    tdes.Padding = PaddingMode.PKCS7;
 
    ICryptoTransform cTransform = tdes.CreateDecryptor();
    resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
 
    tdes.Clear();
 
    return UTF8Encoding.UTF8.GetString(resultArray);
}
What is the difference between RegisterStartupScript() method and RegisterClientScriptBlock() method?

Both, RegisterStartupScript() method and RegisterClientScriptBlock() method will inject Javascript code that will fire during start up of subsequent postback.

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object's element. The code cannot access any of the
form's elements because, at that time, the elements haven't been instantiated yet.
The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object's element. The code can access any of the form's
elements because, at that time, the elements have been instantiated.

RegisterClientScriptBlock is meant for functions that should be "available" to the page. For this they are rendered at the start of the HTML file. In this case the page
content will be blocked.

RegisterStartupScript is meant for commands that should execute on page load (at the client), so that page needs to be available for the script. This script is rendered at
the end of the HTML file. In this case the content of the page will diplayed first and then script will run.

The choice of which method to use really depends on the "order" in which you want your script to be run by the browser when rendering the page.

C#  CODE

if (!Page.IsStartupScriptRegistered("CH"))
    Page.RegisterStartupScript("CH", "<script>alert('Hello Friend');</script>");
  
if (!Page.IsClientScriptBlockRegistered("CH"))
    Page.RegisterClientScriptBlock("CH", "<script>alert('Hello Friend');</script>");
A potentially dangerous Request
Error:
A potentially dangerous Request.Form value was detected from the client (TextBox2="<html></html>").

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an
attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the
Page directive or in the

configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (TextBox2="<html></html>").

Generally this type of error encountered when we trying request the form by entering html tags into the input fileds.

To resolve this problem


In page directive add the following attribute.

ValidateRequest="false"

Implementing the Singleton Pattern in .NET


The intent of the Singleton pattern as defined in Design Patterns is to "ensure a class has only one instance, and provide a global point of access to it".
What problem does this solve, or put another way, what is our motivation to use it? In nearly every application, there is a need to have an area from which to globally
access and maintain some type of data. There are also cases in object-oriented (OO) systems where there should be only one class, or a predefined number of instances of
a class, running at any given time. For example, when a class is being used to maintain an incremental counter, the simple counter class needs to keep track of an integer
value that is being used in multiple areas of an application. The class needs to be able to increment this counter as well as return the current value. For this situation, the
desired class behavior would be to have exactly one instance of a class that maintains the integer and nothing more.
At first glance, one might be tempted to create an instance of a counter class as a just a static global variable. This is a common technique but really only solves part of the
problem; it solves the problem of global accessibility, but does nothing to ensure that there is only one instance of the class running at any given time. The responsibility
of having only one instance of the class should fall on the class itself and not on the user of the class. The users of the class should always be free from having to monitor
and control the number of running instances of the class.
What is needed is a way to control how class instances are created and then ensure that only one gets created at any given time. This would give us exactly the behavior
we require and free a client from having to know any class details.
Logical Model
The model for a singleton is very straightforward. There is (usually) only one singleton instance. Clients access the singleton instance through one well-known access point.
The client in this case is an object that needs access to a sole instance of a singleton. Figure 1 shows this relationship graphically.

Figure 1. Singleton pattern logical model


First version - not thread-safe
// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance = null;
 
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}
As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create
instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model
doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed
Second version - simple thread-safety
public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }
    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}
This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the
instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes
occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time
the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is
acquired every time the instance is requested.
Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking
on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever
possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing
a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.
Third version - attempted thread-safety using double-check locking
// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance = null;
    static readonly object padlock = new object();

    Singleton()
    {
    }
    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}
This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:
 It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well
also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The
Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
 Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec)
it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as
would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts
don't agree what's right and what's wrong!
 It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
 It still doesn't perform as well as the later implementations
Fourth version - not quite as lazy, but thread-safe without using locks
public sealed class Singleton
{
    static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler


    // not to mark type as beforefieldinit
    static Singleton()
    {
    }
    Singleton()
    {
    }
    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}
As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance
of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be
executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:
 It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the
instance. This is corrected in the next implementation.
 There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for
more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to
each other in a cycle.
 The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided
in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as  beforefieldinit.
One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This
makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make
the performance identical. (Note that the static constructor itself is still required if you require laziness.)
Fifth version - fully lazy instantiation
public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }
    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }
        internal static readonly Singleton instance = new Singleton();
    }
}
Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy,
but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true,
hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to
make the instantiation lazy.

Serialization and Types of Serialization in .Net


Serialization:
1. Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent
storage location.  This storage location can be a physical file, database or ASP.NET Cache.
2. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines.
This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed
easily.
Advantage:
Using serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage
medium in a non-proprietary format.
Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client.  The Remoting technology of .NET makes use of serialization to
pass objects by value from one application domain to another.
De-serialization is the reverse; it is the process of reconstructing the same object later.
Figure 1

Advantages and Disadvantages of Serialization


The following are the basic advantages of serialization:
1. Facilitate the transportation of an object through a network
2. Create a clone of an object 
The primary disadvantage of serialization can be attributed to the resource overhead (both the CPU and the IO devices) that is involved in serializing and de-serializing the
data and the latency issues that are involved for transmitting the data over the network.  Further, serialization is quite slow. Moreover, XML serialization is insecure,
consumes a lot of space on the disk and it works on public members and public classes and not on the private or internal classes.  Therefore, it compels the developer to
allow the class to be accessed to the outside world.
The Serializable Attribute
In order for a class to be serializable, it must have the attribute SerializableAttribute set and all its members must also be serializable, except if they are ignored with the
attribute NonSerializedAttribute.  However, the private and public members of a class are always serialized by default.  The SerializationAttribute is only used for the
binary serialization.  The code snippet below shows the usage of SerializableAttribute.
Listing 1:
[Serializable]
public class Employee
{
   public int empCode;
   public string empName;

Note the Serializable attribute that is specified at the beginning of the class in the code listing above.  The SerializableAttribute is useful for situations where the object has
to be transported to other application domains.  It needs to be applied even irrespective of whether the class implements the ISerializable interface.  If this attribute is not
set in that case, then when we try to serialize an object the CLR throws a SerializationException.
Types of Serialization
Serialization can be of the following types:
1. Binary Serialization
2. SOAP Serialization
3. XML Serialization
4. Custom Serialization
Binary Serialization
 Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically.  The term binary in its
name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.
 Difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not.  In other words, in
Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved.  
 Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object
Public void BinarySerialize(string filename, Employee emp)
{
  FileStream fileStreamObject;
  try
  {
    fileStreamObject =new FileStream(filename, FileMode.Create);
    BinaryFormatter binaryFormatter =new BinaryFormatter();
    binaryFormatter.Serialize(fileStreamObject, emp);
  }
  finally
  {
    fileStreamObject.Close();
  }
}
The following code listing shows how we can implement binary de-serialization.
publicstaticobject BinaryDeserialize(string filename)
{
  FileStream fileStreamObject; 
  try
  {
    fileStreamObject =new FileStream(filename, FileMode.Open);
    BinaryFormatter binaryFormatter =new BinaryFormatter();
    return (binaryFormatter.Deserialize(fileStreamObject));
  }
  finally
  {
    fileStreamObject.Close();
  }
}
ADVANTAGES AND DISADVANTAGES OF BINARY SERIALIZATION
One of the major advantages of using Binary Serialization in the managed environment is that the object can be de-serialized from the same data you serialized it to.
Besides, the other advantage of Binary Serialization is enhanced performance as it is faster and even more powerful in the sense that it provides support for complex
objects, read only properties and even circular references. However, the downside to this is that it is not easily portable to another platform.
SOAP Serialization
The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures.  In order to use SOAP serialization in .NET we have to add a
reference to System.Runtime.Serialization.Formatters.Soap in the application.  The basic advantage of SOAP serialization is portability.  The SoapFormatter serializes
objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message.  
publicvoid SOAPSerialize(string filename,Employee employeeObject)
{
  FileStream fileStreamObject =new FileStream(filename, FileMode.Create);
  SoapFormatter soapFormatter =new SoapFormatter();
  soapFormatter.Serialize(fileStreamObject, employeeObject);
  fileStreamObject.Close();

The following code listing shows how we can implement de-serialization using the SOAP protocol.
publicstaticobject SOAPDeserialize(string filename)
{
  FileStream fileStreamObject =new FileStream(filename, FileMode.Open);
  SoapFormatter soapFormatter =new SoapFormatter();
  object obj = (object)soapFormatter.Deserialize(fileStreamObject);
  fileStreamObject.Close();
  return obj;
}
XML Serialization
·         According to MSDN, "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an
XML stream that conforms to a specific XML Schema definition language (XSD) document.
·         XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport.
Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform."  Implementing XML Serialization in .Net is
quite simple.
·         The basic class that we need to use is the XmlSerializer for both serialization and de-serialization.  The Web Services use the SOAP protocol for communication and
the return types and the parameters are all serialized using the XmlSerializer class.  XML Serialization is however, much slower compared to Binary serialization.  We can
set a property as an XML attribute as shown in the code listing below.
[XmlAttribute("empName")]
publicstring EmpName
{
  get
  {
    return empName;
  }
  set
  {
    empName = value;
  }
}
The following code listing shows how we can implement XML serialization.
publicvoid XMLSerialize(Employee emp, String filename)
{
  XmlSerializer serializer =null;
  FileStream stream =null;
  try
  {
    serializer =new XmlSerializer(typeof(Employee));
    stream =new FileStream(filename, FileMode.Create, FileAccess.Write);
    serializer.Serialize(stream, emp);
  }
  finally
  {
    if (stream !=null)
      stream.Close();
  }
}

The following code listing shows how we can implement XML de-serialization.
public static Employee XMLDeserialize(String filename)
{
  XmlSerializer serializer =null;
  FileStream stream =null;
  Employee emp =new Employee();
  try
  {
    serializer =new XmlSerializer(typeof(Employee));
    stream =new FileStream(filename, FileMode.Open);
    emp = (Employee)serializer.Deserialize(stream);
  }
  finally
  {
    if (stream !=null)
      stream.Close();
  }
  return emp;
}

ADVANTAGES OF XML SERIALIZATION


The advantages of XML Serialization are as follows:
1. XML based
2. Support for cross platforms
3. Easily readable and editable 
Working with Formatters
formatter is used to determine the serialization format for objects.  In other words, it is used to control the serialization of an object to and from a stream.  They are the
objects that are used to encode and serialize data into an appropriate format before they are transmitted over the network.  They expose an interface called the
IFormatter interface.  IFormatter's significant methods are Serialize and De-serialize which perform the actual serialization and de-serialization. There are two formatter
classes provided within .NET, the BinaryFormatter and the SoapFormatter.  Both these classes extend the IFormatter interface.
The Binary Formatter
The Binary formatter provides support for serialization using binary encoding.  The BinaryFormater class is responsible for binary serialization and is used commonly
in .NET's Remoting technology.  This class is not appropriate when the data is supposed to be transmitted through a firewall.
The SOAP Formatter
The SOAP formatter provides formatting that can be used to serialize objects using the SOAP protocol.  It is used to create a Soap envelop and it uses an object graph to
generate the result.  It is responsible for serializing objects into SOAP messages or parsing the SOAP messages and extracting these serialized objects from the SOAP
messages.  SOAP formatters in .NET are widely used by the Web Services.
Custom Serialization
In some cases, the default serialization techniques provided by .NET may not be sufficient in real life.  This is when we require implementing custom serialization.  It is
possible to implement custom serialization in .NET by implementing the ISerializable interface..  This interface allows an object to take control of its own serialization and
de-serialization process.  It gives us a great deal of flexibility in the way we can save and restore objects.  The ISerializable interface consists of a single method,
GetObjectData, which accepts two parameters.
The SerializationInfo class serves as the container for all the data we want to serialize.  The AddValue method is called to add the objects we want to serialize to this
container.  The implementing class needs to have the GetObjectData method and a special constructor which is used by the common language runtime during the process
of de-serialization.  The following code listing shows how we can implement Custom Serialization.
public class Employee: ISerializable
{
  private int empCode;
  private string empName;
  protected Employee(SerializationInfo serializationInfo, StreamingContext
    streamingContext)
  {
    this.empCode = serializationInfo.GetInt32("empCode");
    this.empName = serializationInfo.GetString("empName");
  }

  public void ISerializable.GetObjectData(SerializationInfo serializationInfo,
  StreamingContext streamingContext)
  {
    serializationInfo.AddValue("empCode", this.empCode);
    serializationInfo.AddValue("empName", this.empName);
  }
}
The following listing shows how we can implement Custom Serialization on a Custom Collection class that extends the CollectionBase class of the System.Collections
namespace. 
[Serializable]
public class EmployeeCollection: System.Collections.CollectionBase,  ISerializable
{
  privateint empCode; 
  public EmployeeCollection()
  {
    empCode = 1;
  }
  protected EmployeeCollection(SerializationInfo info, StreamingContext context)
  : base(info, context)
  {
    empCode = info.GetInt32("empCode");
  }
  public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    base.GetObjectData(info, context);
    info.AddValue("empCode", empCode);
  }
}
Points to remember
This section deals with some of the points that we have already covered in this article and some others that we have not, but are still very important and relate to the
serialization and de-serialization concepts of .NET.
When you apply the Serializable custom attribute to a type, all instance fields of the class (public, private, protected, etc.) are serialized automatically.
XmlSerializer does not use the ISerializable interface; rather, it uses the IXmlSerializable interface.  The XmlSerializer class can only serialize the public properties of the
class, whereas the BinaryFormatter class can serialize private fields using the ISerializable interface.
The Serializable attribute is a must for making a class serializable irrespective of whether we have implemented the ISerializable interface in this class.  When we serialize a
class, the objects of the references to other classes that are contained in this class are also serialized if they are marked as serializable.  All members are serialized,
including public, private or protected members. Furthermore, even circular references are supported by binary serialization.  Note that read only properties are not
serialized except the collection class objects.  However, the read only properties can be serialized using binary serialization.
If we do not require serializing a particular property of a class when using an XmlSerializer, we have to mark the property with the custom attribute XmlIgnoreAttribute.
When using a SoapFormatter we have to use the SoapIgnoreAttribute instead.  The XmlSerializer generates an in-memory assembly optimized for each type since the
initial invocation to a Web Service always takes so much time.  To combat this, we can use the sgen.exe tool to pre-generate the serialization assembly.
Conclusion
Serialization is the process of storing an object, including all of its members, to a persistent or a non-persistent storage media by converting the object into a linear stream
of data.  De-serialization is the process of restoring an object's values from the said stream.  The advantage of serialization is to save the state of an object in order to have
the ability to recreate the same object at a later point of time if and when it is required.  The .NET Framework provides a strong support for serialization of objects.
The .NET Framework provides a unified standard for serializing and de-serializing objects for building distributed heterogeneous systems.  This article has explored
Serialization and De-serialization and the various types of Serialization concepts with code examples wherever necessary.  It has discussed what Custom Serialization is
and how to implement it. However, I would recommend not using serialization unless it is absolutely necessary due to the drawbacks that I have already explained in this
article
What are Master Pages in .NET? Why we need Master Pages and how do we use Master Pages in our applications?

Life before Master Pages

For a given website, there are multiple web pages with common layout. How we can achieve this?
 Write the layout of the code in each page. But this leads to code redundancy which is not correct.
 We can achieve the common layout, by using User controls.
Advantage of User Controls:
 Turning an existing ASP.NET page into a user control requires only a few minor changes. User controls can be easily linked to any page that needs their services.
 Furthermore, changes to a user control's implementation do not affect the referencing page and only require recompiling of the user control into an assembly.
Disadvantage of User Controls:
 Any alteration to the control's public interface (such as the class name, properties, methods, or events) leads to the pages that reference the control must be updated.
 Those pages must be re-compiled and needs deployment.
 In addition, the next time a user views each page, the ASP.NET runtime will take a while to respond because the dynamic assembly for the page must be re-created.
Apart from the above two options, the other options is to use Master pages. A Master page is a file that contains the static layout of the file. It consists of the layout that is
common throughout application (i.e. Application Level) or a folder level and dynamic parts will be customized by the pages that are derived from the Master page.
What is a Master Page?
One of the cool new things introduced in ASP.NET 2.0 is Master Pages. Master Pages give you the ability to define a master page layout and look that is used throughout a
site to give a consistent look & feel to all pages. Any updates or changes to the look & feel of the site is done in only one place - the Master Page.
A master page is similar to an ordinary ASP.NET page except for the top @Master directive and the presence of one or more ContentPlaceHolder server controls. A
ContentPlaceHolder
control defines a region in the master page that can be customized in a derived page. ContentPlaceHolder acts as container which holds controls/items defined in the
derived pages.
<asp:contentplaceholder runat="server" ID="PageBody" />
In the derived pages, server control <asp:Content> is used to provide actual content to ContentPlaceHolders of Master Page. The link between placeholders and content is
established through the Content place holder ID.
<asp:Content runat="server" contentplaceholderID="PageBody">
...
</asp:Content>
Note:
1. In a master page, there can be multiple content place holders.
2. Content page acts as bridge to fill the content in their master pages and it should only contains <asp:Content> server control. Everything (like different content) should
be defined in that only.
3. For a given Content place holder, default content can be defined in the master page itself. If it has not been overridden in Content page, the content defined in the
master will be displayed.
4. A placeholder can't be bound to more than one content region in a single content page. If you have multiple <asp:Content> server tags in a content page, each must
point to a distinct placeholder in the master.
5. A ContentPlaceHolder control can be used only in a master page. Content placeholders are not valid on regular ASP.NET pages. If such a control is found in an ordinary
Web page, a parser error occurs.
6. The MasterPage class, in turn, inherits UserControl. So, at the end of the day, a master page is treated as a special kind of ASP.NET user control.
Can we have a Master Page without Content Place Holders?
Yes.  We can have and ASP.Net runtime will compile the page, but the primary goal of the master page will not get satisfied.
Main Attributes of @Master Directive.
Attribute Description
ClassName Specifies the name for the class that will be created
to render the master page. This value can be any
valid class name but should not include a namespace.
By default, the class name for simple.master is
ASP.simple_master.
Inherits Specifies a code-behind class for the master page to
inherit. This can be any class derived
from MasterPage.
MasterPageFile Specifies the name of the master page file that this
master refers to. A master can refer to another
master through the same mechanisms a page uses to
attach to a master.
If this attribute is set, you will have nested masters.
Note:
The @Master directive doesn't override attributes set at the @Page directive level. Master Page can be built using one language (let say C#), derived page can be used
another language like VB.Net.
What are the different ways to attach Pages to a Master?
Content page can be attached to Master in different ways
1. Page Level: By using “MasterPageFile” attribute of @Page directive.
2. Folder Level: Linking of the same Master Page to all the pages residing in the same folder. This can be achieved by defining in the web.config of the corresponding
folder by using below tag.
3. Application Level: Linking of the same Master Page to all the pages throughout the application. This can be achieved by defining in the web.config of the corresponding
folder by using below tag.
<configuration>
<system.web>
<pages master="MyApp.master" />
</system.web>
</configuration>
There is an exception for Application Level binding, i.e. if we have application level binding, then all the pages in the application should map to one or more content place
holders. In other words application level binding prevents from having (or later adding) a page to the site that is not configured as a content page. If there is any general
asp.net page, that will throw exception. Make sure while using application level binding.
Can we have Master pages which are specific to environments?
Yes. We can have Master pages specific to device like browser (IE, netscape) specific. Master pages have the capability to identify the underlying browser and accordingly
chooses master page.
Below is the syntax to achieve that feature
<%@ Page masterpagefile="Base.master" ie:masterpagefile="ieBase.master" netscape6to9:masterpagefile="nsBase.master" %>
When the page runs, the ASP.NET runtime automatically determines which browser or device the user is using and selects the corresponding master page. Here
ieBase,master will be loaded when the site is accessed in the IE browser, nsBase.master will be loaded if it is Netscape browser, of the rest base.master will be utilised.
How the Master and Content Page will be processed internally?
Since Master and Content pages are interdependent, either of the page changes, dynamic assembly needs to be re-created.
When the user requests a page, first it checks whether master page exists or not. If there is any master page, then first master page will be compiled. If the folder consists
of multiple master pages, all of them will be compiled at the same time. So when the user access any page for the first, page loading may take a little bit time for compiled,
from the next time onwards, it won’t take much time, as master pages are already compiled and cached. When compared to User controls, this is an advantage for master
pages as User Controls need compilation every time.
Can we have nested Master pages?
Yes. If a master page is nested from another master page, the derived master must consist of Content place holder along with Content and “MasterPageFile” of @Master
directive will set to base Master page. There is no architectural limitation about the level of nesting a given master page.
Warning
Visual Studio 2008 is currently the only Microsoft tool capable of fully supporting nested master pages. If you're using older versions, you have to create an intermediate
master page as a content page and then change the top directive to @Master, remove the Title attribute and, last but not least, change the base class of the code file to
MasterPage.
Can we set Master page dynamically at runtime?
Yes. Set the MasterPageFile property only during the PreInit page event—that is, before the runtime begins working on the request (since the rendering of the page with
the master page occurs prior to the Init event)
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPageFile = "simple2.master";
}
If you try to set the MasterPageFile property in Init or Load event handlers, an exception is raised.
Note:
The Master property represents the current instance of the master page object, is a read-only property, and can't be set programmatically. The Master property is set by
the runtime after loading the content of the file referenced by the MasterPageFile property.
The above code needs to add in every page of the site. Instead, it is easy enough to add that code to a base page class that you can inherit from for you pages in the site.  
In case if you do not already have the base page, you can use the following web.config settings to have a base class without having to modify the existing aspx pages.
<system.web>
    <!-- ... -->
    <pages pageBaseType="MyWeb.UI.MyPageBase" />
    <!-- ... -->
</system.web>
Can we access Master Page Controls from Content Page?
Yes.  We can access master page controls from the content pages.  Below are the 2 examples towards the same.
Example1:
TextBox tb = (TextBox)Master.FindControl("txtMaster");
tb.Text = "Something";
Example2:
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder =
    (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
    mpTextBox = (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
    if(mpTextBox != null)
    {
        mpTextBox.Text = "TextBox found!";
    }
}
// Gets a reference to a Label control that is not in a
// ContentPlaceHolder control
Label mpLabel = (Label) Master.FindControl("masterPageLabel");
if(mpLabel != null)
{
    Label1.Text = "Master page label = " + mpLabel.Text;
}

1. What is the sequence of execution of the ASP.NET page life cycle?


 
The simple way is to remember SILVER.
 S (It is not counted)
 I (Init)
 L (Load)
 V (Validate)
 E (Event)
 R (Render)
Read more here.
 
2. What is the difference between a Hash Table and a Dictionary?
 
The main differences are listed below.
 
Dictionary,
 Returns an error if the key does not exist
 No boxing and unboxing
 Faster than a Hash table
Hashtable,
 Returns NULL even if the key does not exist
 Requires boxing and unboxing
 Slower than a Dictionary
3. How to use View state?
1. string str = "Sibeesh Passion";  
2. if(ViewState["SampleText"]==null)  
3. {  
4.    ViewState["SampleText"] = str;  
5. }  
4. What are the state management techniques used in .NET?
 
Client-side
 Hidden Field
 View State
 Cookies
 Control State
 Query Strings
Server-side
 Session

1. In Proc mode
2. State Server mode
3. SQL Server mode
4. Custom mode

 Application.
Read here.
 
5. How can we create a new table in SQL with only the structure?
 
Here is the query to do that.
 
Select * Into<B>From<A>Where1 = 2
 
Points to be noted:
 A is the source table.
 B is the destination table.
 The condition 1=2 is to prevent the data from being copyied.
6. How to add a button dynamically to a grid view?
1. Button myButton = newButton();  
2. myButton.Text = "Hai";  
3. myGrid.Controls.Add(myButton);   
7. How to find a control inside a GridView?
1. Button btnTest = (Button) myGrid.Rows[0].Cells[1].Controls[1].FindControl("myButton ");  
Here we are finding the control myButton from the 0th row first cell.
 
8. What are abstract and interface? Provide actual examples.
 
Please read here.
 
9. What is partial class?
 
There are the following situations of when splitting a class definition is desirable: 
 To work with large projects.
 To split the class definitions as we needed with the keyword partial.
10. How to use a partial class?
1. public partial class DailyExpenses  
2. {  
3.     To make it more real, let us consider this class is used by the Husband .   
4.     He will add his expenses (in programming life , his codes )  
5.     public void AddExpensesByHus()  
6.     {  
7.     }  
8. }  
9. public partial class DailyExpenses  
10. {  
11.    To make it more real, let us consider this class is used by the Wife.   
12.    She will add his expenses (in programming life , her codes )  
13.    public void AddExpensesByWife()  
14.     {  
15.     }  
16. }   
11. How to remove a constraint from a table in SQL Server? 
1. ALTER TABLE MyTab DROP CONSTRAINT myConstraint   
12. How to create Table Variables In T-SQL?
 
Normally the syntax to create a table variable is the same as to create a table statement. 
1. DECLARE@tabVar TABLE  
2. (  
3.    Your fields here  
4. )   
13. How can you delete a duplicate record from a table in SQL?
 
There are so many ways to do this. Here I am sharing what I use when I get that kind of situation.
 
I will create a temp table.
 
Copy the distinct data from the existing table to the temp table.
 
Empty the data in the existing table.
 
Insert the data from the temp table to the source table.
 
Here is the query to do that:
1. select distinct * into #tempTab From Address_Tab
2. delete from Address_Tab
3. insert into Address_Tab
4. select * from # tempTab
5. drop table # tempTab
14. When to use an override and new in C#?
 We can use override when there is virtual/abstract/override type of method in base class.
 We can use New when there is no virtual/abstract/override type of method in base class.
That is all for today. I will see you soon with another set of questions and answers.
 
Please provide your comments and suggestions thanks in advance.
 
Question 1: What is meant by CLR?

Answer: CLR is a runtime provided by .NET. It allows us to execute the program on the .Net platform. The CLR provides "Simple Application Performance, Safety, Multiple
Language Support, Good Performance, etc".

Question 2: What is meant by ASP.NET?

Answer: ASP.NET is open source server-side web application framework designed for web development to produce dynamic web pages.

Question 3: What is the difference between STORED PROCEDURES and FUNCTIONS?

Answer

Function Stored Procedures


It supports both Input and Output
It supports only Input Parameters.
Parameters.
We can write any T-SQL statements which will not modify the existing Data-Base. We can write any T-Sql statements.ex: .dml,.dql,.ddl
We can call Functions using Select statement. using Select Statement. We can not call Stored Procedures
Functions can be called from Stored Procedures. Stored Procedures can not call from Functions.
Question 4: What is the difference between ABSTRACT CLASS and INTERFACE?

Answer
 
Abstract Class Interface
It has only Constants without
It has Constants, Members without Method Body.
Method Body.
We can use any Access Modifiers for Visibility [Public, Private, Internal, Protected]. The methods of an Interface must be Public only.
Abstract contains Constructors. Interface does not contain Constructors.
Question 5: What is the difference between AS and IS keywords?

Answer
 
IS AS
Is Operator is used to Check the Compatibility of an Object with a given Type and it returns the result as a Boolean As Operator is used for Casting Object to a given type
(True Or False). Or Class.
Question 6: What is the difference between QUEUE and STACK?

Answer
 
Stack Queue
A Queue is a First-In First-Out (FIFO)
A Stack is a Last-In First-Out (LIFO) container.
container.
Queue is an ordered collection of
Stack is a collection of items.
items.
Question 7: What is the difference between a STRUCT and a CLASS?

Answer
 
Struct Class
Structs are value types. Classes are reference types.
Structs cannot support inheritance. Classes can support inheritance
Structs are passed by value (like integers). Classes are reference (pointer) types.
Question 8: What do you mean by AUTHENTICATION and AUTHORIZATION?

Answer: 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, access is limited and it is known as Authorization.

Question 9: What is the global assembly cache (GAC)?

Answer: GAC is a machine-wide cache of assemblies that allows .NET applications to share libraries. GAC solves some of the problems associated with dll’s (DLL Hell).

Question 10: What is Boxing/Unboxing?

Answer: Boxing is used to convert value types to object.


1. int x = 1;   
2. object obj = x ;   
Unboxing is used to convert the object back to the value type.

1. int y = (int)obj;  
Note: Conversion of Boxing and UnBoxing reduces Application Performance.

Question 11: What is garbage collection?

Answer: Garbage collection is the process of managing the allocation and release of memory in your applications.

NOTE: We can also call Garbage Collection explicitly.

Question 12: What is meant by overloading and overriding?

Answer: Overloading is when you have multiple methods, with the same name but different signatures. Overriding is a principle that allows you to change the
functionality of a method in a child class.

Question 13: How to find the 2nd Highest salary using Query?

Answer

Method 1
1. select * from employees emp1 where 1 = (select count(DISTINCT(emp2.salary)) from employees emp2 where emp2.salary > emp1.salary)  
Method 2
1. select top 2 salary from employees emp order by sal desc  
Question 14: Write a program to print * ?

**
***
****

Answer

1. Static void main(string[] Args)  
2. {  
3.     int num = 1;  
4.     for (int i = 0; i < 4; i++)  
5.     {  
6.         for (int j = 0; j < num; j++)  
7.         {  
8.             console.write("*");  
9.         }  
10.         num++;  
11.         console.writeline();  
12.     }  
13.     console.readline();  
14. }  
Question 15: Explain ViewState?

Answer: It is a .NET mechanism to store the posted data among postbacks. It allows the state of objects to be stored in a hidden field on the page, saved on client side and
transported back to server whenever required.

Question 16: Difference between Response.Redirect and Server.Transfer?

Answer

Response.Redirect

A new request is generated from client-side for redirected page. It's a kind of additional round trip. As new request is generated from client, so the new URL is visible to
user in browser after redirection.

Server.Transfer

A request is transferred from one page to another without making a round trip from client. For the end user, URL remains the same in browser even after transferring to
another page.
Question 17: What are value types and reference types?

Answer: Value types are stored in the Stack whereas Reference types stored on heap.

Value Types: int,enum,byte,decimal,float,long.
Reference Types:String,class,interface,object.

Question 18: What is the difference between application exception and system exception?

Answer: The difference between application exception and system exception is that system exceptions are thrown by CLR and application exceptions are thrown by
applications.

Question 19: What is the difference between Primary key and unique key?

Answer: Primary key does not allow the null values but unique key allows one null value. Primary key will create clustered index on column but unique key will create non-
clustered index by default.

Question 20: What is the difference between constants, read-only and, static?

Answer

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.

Question 21: What is the default timeout for a Cookie?

Answer: The default time duration for a Cookie is 30 minutes.

Question 22: What is a Cookie? Where is it used in ASP.NET?

Answer: Cookie is a lightweight executable program, which the server posts to client machines. Cookies store the identity of a user at the first visit of the Web site and
validate them later on the next visits for their authenticity. The values of a cookie can be transferred between the user's request and the server's response.

Question 23: How many types of Cookies are available in ASP.NET?

Answer: There are two types of Cookies available in ASP.NET,


 Session Cookie: Resides on the client machine for a single session until the user does not log out. 
 Persistent Cookie: Resides on a user's machine for a period specified for its expiry, such as 10 days, one month, and never.  27)What is the use of the Global.asax
file?
The Global.asax file executes application-level events and sets application-level variables.

Question 24: What events are fired when a page loads?

Answer: The following events fire when a page loads,


 Page_Init() - Fires when the page is initializing. 
 Page_LoadViewState() - Fires when the view state is loading. 
 Page_LoadPostData() - Fires when the postback data is processing. 
 Page_Load() - Fires when the page is loading. 
 Page_PreRender() - Fires at the brief moment before the page is displayed to the user as HTML. 
 Page_Unload() - Fires when the page is destroying the instances of server controls. 
Question 25: What is meant by Cursor in C#?

Answer: Cursor is an icon and it displays when a user moves a mouse, trackball or a pen. It can be managed in C# by Cursors class. It is present System.Windows.Forms
namespace.

C# Code

button1.Cursor = Cursors.Hand;
listBox1.Cursor =Cursors.No;

Creating a Cursor: Cursor is not a typical Windows Forms control. It is used as a helper control and does not have a user interface or design view. The Cursor class
represents a cursor and it is created either using the Cursors class or load a cursor from a file. The following code snippet creates a cursor.

Cursor cur = Cursors.WaitCursor;


this.Cursor = cur;

Question 26: What is meant by COLLECTIONS in C#?


 
Answer: Collection classes are normally used to hold collections of values or objects in memory. In collection classes, elements are inserted using either the Add orInsert
method, and deleted using the RemoveAt method. Finally, collections can be iterated over using the foreach statement.
1. ArrayList
2. HashTable
3. SortedList
4. BitArray
5. Queue
Question 27: What are the various types of Authentication?

Answer: There are 3 types of Authentication namely Windows, Forms and Passport Authentication: 
 Windows authentication: It uses the security features integrated in Windows NT and Windows XP OS to authenticate and authorize Web application users.

 Forms authentication: It allows you to create your own list of users and validate their identity when they visit the Web site.

 Passport authentication: It uses the Microsoft centralized authentication provider to identify users. Passport allows users to use a single identity across multiple
Web applications.
Question 28: What are the various session state management options provided by ASP.NET?

Answer: ASP.NET provides two session state management: 


 In-Process state management: In-Process stores the session in memory on the web server.

 Out-of-Process state management: Out-of-Process stores data in an external data source. This data source may be a SQL Server or a State Server service. 
Question 29: What are the validation controls available in ASP.NET?

Answer: ASP.NET validation controls are the following:


 RequiredFieldValidator: This validates controls if controls contain data.
 CompareValidator: This allows checking if data of one control match with other control.
 RangeValidator: This verifies if entered data is between two values.
 RegularExpressionValidator: This checks if entered data matches a specific format.
 CustomValidator: Validate the data entered using a client-side script or a server-side code.
 ValidationSummary: This allows developer to display errors in one place.
Question 1 - What is ASP.NET?
Answer: ASP.NET is Microsoft's framework to build Web applications. ASP.NET is a part of .NET Framework. ASP.NET and Web Forms are used to build the front end and in
the backend, C# langauge is used. ASP.NET runs on a Web Server, IIS.
Advantages of ASP.NET
Separation of Code from HTML
To make a clean sweep, with ASP.NET you have the ability to completely separate layout and business logic. This makes it much easier for teams of programmers and
designers to collaborate efficiently.
Support for compiled languages
Developers can use VB.NET and access features such as strong typing and object-oriented programming. Using compiled languages also means that ASP.NET pages do not
suffer the performance penalties associated with interpreted code. ASP.NET pages are precompiled to byte-code and Just In Time (JIT) compiled when first requested.
Subsequent requests are directed to the fully compiled code, which is cached until the source changes.
Use services provided by the .NET Framework
The .NET Framework provides class libraries that can be used by your application. Some of the key classes help you with input/output, access to operating system services,
data access, or even debugging. We will go into more detail on some of them in this module.
Graphical Development Environment
Visual Studio .NET provides a very rich development environment for web developers. You can drag and drop controls and set properties the way you do in Visual Basic 6.
And you have full IntelliSense support, not only for your code but also for HTML and XML.
State management
To refer to the problems mentioned before, ASP.NET provides solutions for session and application state management. State information can, for example, be kept in
memory or stored in a database. It can be shared across web farms, and state information can be recovered, even if the server fails or the connection breaks down.
Update files while the server is running
Components of your application can be updated while the server is online and clients are connected. The framework will use the new files as soon as they are copied to
the application. Removed or old files that are still in use are kept in memory until the clients have finished.
XML-Based Configuration Files
Configuration settings in ASP.NET are stored in XML files that you can easily read and edit. You can also easily copy these to another server, along with the other files that
comprise your application.
ASP.NET Overview
Here are some points that give a quick overview of ASP.NET.
 ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services.
 Like ASP, ASP.NET is a server-side technology.
 Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface. They
mirror typical HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are free to create your own user controls.
 Web Forms are designed to make building web-based applications as easy as building Visual Basic applications.
Continue to learn more here, Introduction to ASP.NET.
Question 2 - What are the different validators in ASP.NET?
Answer: ASP.NET validation controls define an important role in validating the user input data. Whenever the user gives the input, it must always be validated before
sending it across to various layers of an application. If we get the user input with validation, then chances are that we are sending the wrong data. So, validation is a good
idea to do whenever we are taking input from the user. There are the following two types of validation in ASP.NET,
 Client-Side Validation
 Server-Side Validation
Client-Side Validation
When validation is done on the client browser, then it is known as Client-Side Validation. We use JavaScript to do the Client-Side Validation.  Server-Side Validation When
validation occurs on the server, then it is known as Server-Side Validation. Server-Side Validation is a secure form of validation. The main advantage of Server-Side
Validation is if the user somehow bypasses the Client-Side Validation, we can still catch the problem on server-side. The following are the Validation Controls in ASP.NET,
 RequiredFieldValidator Control
 CompareValidator Control
 RangeValidator Control
 RegularExpressionValidator Control
 CustomFieldValidator Control
 ValidationSummary
For further information click on the link,
 Validation Controls in ASP.Net
Question 3 - What is View State?
Answer: View State is the method to preserve the Value of the Page and Controls between round trips. It is a Page-Level State Management technique. View State is
turned on by default and normally serializes the data in every control on the page regardless of whether it is actually used during a post-back.
A web application is stateless. That means that a new instance of a page is created every time when we make a request to the server to get the page and after the round
trip our page has been lost immediately
Features of View State These are the main features of view state,
1. Retains the value of the Control after post-back without using a session.
2. Stores the value of Pages and Control Properties defined in the page.
3. Creates a custom View State Provider that lets you store View State Information in a SQL Server Database or in another data store.
Advantages of View State
1. Easy to Implement.
2. No server resources are required: The View State is contained in a structure within the page load.
3. Enhanced security features: It can be encoded and compressed or Unicode implementation.
For further information click on the link,
 What is View State and How it Works in ASP.NET
Question 4: What are the different Session state management options available in ASP.NET?
Answer: State Management in ASP.NET
 A new instance of the Web page class is created each time the page is posted to the server.
 In traditional Web programming, all information that is associated with the page, along with the controls on the page, would be lost with each roundtrip.
 The Microsoft ASP.NET framework includes several options to help you preserve data on both a per-page basis and an application-wide basis. These options can
be broadly divided into the following two categories,  
o Client-Side State Management Options
o Server-Side State Management Options
Client-Side State Management
 Client-based options involve storing information either in the page or on the client computer.
 Some client-based state management options are,  
o Hidden fields
o View state
o Cookies
o Query strings
Server-Side State Management
 There are situations where you need to store the state information on the server side.
 Server-side state management enables you to manage application-related and session-related information on the server.
 ASP.NET provides the following options to manage state at the server side:  
o Application state
o Session state
For further information click on the link,
 State Management in ASP.Net
Question 5 - What is caching in ASP.NET?
Answer: Caching is one of the most interesting concepts and operations in ASP.NET. If you can handle it, you can run any web application by applying the caching concept
depending on the requirements. Caching is for providing solutions or the results to the users depending on their request, admin needs to recreate the pages often
depending on user requests…STOP!!! "A cache simply stores the output generated by a page in the memory and this saved output (cache) will serve us (users) in the
future.". Types

For further information click on the link,


 Caching in ASP.Net
Question 6 - How can we apply themes in ASP.NET application?
Answer: A theme is a collection of settings that define the look of controls and web pages. These themes are applied across all the pages in a web application to maintain
a consistent appearance. Themes are included images and skin files; the skin files set the visual properties of ASP.NET controls. Themes are of two types:  Page Theme A
Page theme contains the control skins, style sheets, graphic files, and other resources inside the subfolder of the App_Theme folder in the Solution Explorer window. A
page theme is applied to a single page of the web site. Global Theme A Global theme is a theme that is applied to all the web sites on a web server and includes property
settings, and graphics. This theme allows us to maintain all the websites on the same web server and define the same style for all the web pages of the web sites.
For further information click on the link,
 Creating Web Application Using Themes in ASP.NET
Question 7 - What is MVC?
Answer: Model-View-Controller (MVC) is a pattern to separate an application into the following three main components:
1. Model
2. View
3. Controller
The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating web applications. The ASP.NET MVC Framework is a lightweight,
highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-
based authentications. The MVC framework is defined in the System.Web.MVC assembly. It provides full control over HTML, JavaScript, and CSS. It's the better as well as a
recommended approach for large-scale applications where various teams are working together.

The ASP.NET MVC framework offers the following advantages,


 It makes it very easy to manage complexity by dividing an application into the Model, View and Controller.
 It does not use view state or server-based forms.
 Full control over HTML, JavaScript, and CSS.
 It provides better support for Test-Driven Development (TDD).
 It works well for Web applications that are supported by large teams of developers and for web designers who need a high degree of control over the application
behavior.
 By default support of Facebook and Google Authentication.
 It easy to manage a large application to divide into multiple areas.
For further information click on the link,
 Getting Started With ASP.Net MVC
Question 8 - What are Cookies in ASP.NET?
Answer: Cookies are a State Management Technique that can store the values of control after a post-back. Cookies can store user-specific information on the client's
machine, such as when the user last visited your site. Cookies are also known by many names, such as HTTP Cookies, Browser Cookies, Web Cookies, Session Cookies and
so on. Basically cookies are a small text file sent by the web server and saved by the Web Browser on the client's machine. List of properties containing the HttpCookies
Class,
1. Domain: Using these properties we can set the domain of the cookie.
2. Expires: This property sets the Expiration time of the cookies.
3. HasKeys: If the cookies have a subkey then it returns True.
4. Name: Contains the name of the Key.
5. Path: Contains the Virtual Path to be submitted with the Cookies.
6. Secured: If the cookies are to be passed in a secure connection then it only returns True.
7. Value: Contains the value of the cookies.
Limitation of the Cookies
1. The size of cookies is limited to 4096 bytes.
2. A total of 20 cookies can be used in a single website.
For further info click on the link,
 Introduction To Cookies in ASP.Net
Question 9 - What is Ajax in ASP.NET?
Answer. Ajax stands for Asynchronous JavaScript and XML; in other words Ajax is the combination of various technologies such as a JavaScript, CSS, XHTML, DOM, etc.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the entire page. We can also define Ajax is a combination of client-side technologies that provides asynchronous communication
between the user interface and the web server so that partial page rendering occurs instead of a complete page postback. Ajax is platform-independent; in other words,
AJAX is a cross-platform technology that can be used on any Operating System since it is based on XML & JavaScript. It also supports open source implementation of other
technology. It partially renders the page to the server instead of the complete page being post back. We use AJAX for developing faster, better and more interactive web
applications. AJAX uses an HTTP request between web server & browser.
 With AJAX, when a user clicks a button, you can use JavaScript and DHTML to immediately update the UI, and spawn an asynchronous request to the server to
fetch results.
 When the response is generated, you can then use JavaScript and CSS to update your UI accordingly without refreshing the entire page. While this is happening,
the form on the user's screen doesn't flash, blink, disappear, or stall.
 The power of AJAX lies in its ability to communicate with the server asynchronously, using a XMLHttpRequest object without requiring a browser refresh.
 Ajax essentially puts JavaScript technology and the XMLHttpRequest object between your Web form and the server.
For further info click on the link:
 Introduction to Ajax and Ajax Control Toolkit
Question 10 - What are Web Services in ASP.NET?
Answer: A Web Service is a software program that uses XML to exchange information with other software via common internet protocols. In a simple sense, Web Services
are a way of interacting with objects over the Internet. A web service is,
 Language Independent.
 Protocol Independent.
 Platform Independent.
 It assumes a stateless service architecture.
 Scalable (e.g. multiplying two numbers together to an entire customer-relationship management system).
 Programmable (encapsulates a task).
 Based on XML (open, text-based standard).
 Self-describing (metadata for access and use).
 Discoverable (search and locate in registries)- ability of applications and developers to search for and locate desired Web services through registries. This is based
on UDDI.
Key Web Service Technologies,
 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.
 For further info click on the link:
 ASP.NET Web Service Basics
Question 11 - What are the Advantages of ASP.NET?
Answer: ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services like ASP. ASP.NET is a server-side technology.
Web applications are built using Web Forms. ASP.NET comes with built-in Web Form controls, which are responsible for generating the user interface. They mirror typical
HTML widgets such as text boxes or buttons. If these controls do not fit your needs, you are free to create your own user controls.  Advantages of ASP.NET,
 Separation of Code from HTML
 Support for compiled languages
 Use services provided by the .NET Framework
 Graphical Development Environment
 Update files while the server is running
 XML-Based Configuration Files

For further info click on the link:


 Introduction to ASP.NET
Question 12 - What are the concepts of Globalization and Localization in .NET?
Answer: Localization means "the process of translating resources for a specific culture", and Globalization means "the process of designing applications that can adapt to
different cultures". 
 Proper Globalization Your application should be able to Accept, Verify, and Display all kinds of global data. It should well also be able to operate over this data,
accordingly.   
 Localizability and Localization Localizability stands for clearly separating the components of culture-based operations regarding the user interface, and other
operations from the executable code.
.NET framework has greatly simplified the task of creating the applications targeting the clients of multiple cultures. The namespaces involved in creation of globalize,
localizing applications are,
 System.Globalization
 System.Resources
 System.Text
For further info click on the link,
 Globalization and Localization in .NET: Part I
Question 13 - What is the Web.config file in ASP?
Answer: Configuration file is used to manage various settings that define a website. The settings are stored in XML files that are separate from your application code. In
this way you can configure settings independently from your code. Generally a website contains a single Web.config file stored inside the application root directory.
However there can be many configuration files that manage settings at various levels within an application. Usage of configuration file ASP.NET Configuration system is
used to describe the properties and behaviors of various aspects of ASP.NET applications. Configuration files help you to manage the settings related to your website. Each
file is an XML file (with the extension .config) that contains a set of configuration elements. Configuration information is stored in XML-based text files.  Benefits of XML-
based Configuration files
 ASP.NET Configuration system is extensible and application specific information can be stored and retrieved easily. It is human-readable.
 You need not restart the web server when the settings are changed in configuration files. ASP.NET automatically detects the changes and applies them to the
running ASP.NET application.
 You can use any standard text editor or XML parser to create and edit ASP.NET configuration files.
For further info click on the link:
 ASP.NET Web Configuration File
Question 14 - What is the App Domain Concept in ASP.NET?
Answer: ASP.NET introduces the concept of an Application Domain which is known as AppDomain for short. It can be considered as a lightweight process which is both a
container and boundary. The .NET runtime uses an AppDomain as a container for code and data, just like the operating system uses a process as a container for code and
data. As the operating system uses a process to isolate misbehaving code, the .NET runtime uses an AppDomain to isolate code inside a secure boundary. The CLR can
allow the multiple .NET applications to run in a single AppDomain. Mulitple Appdomains can exist in Win32 process.
How to create AppDomain
AppDomains are created using the CreateDomain method. AppDomain instances are used to load and execute assemblies (Assembly). When an AppDomain is no longer in
use, it can be unloaded.
public class MyAppDomain: MarshalByRefObject
{
public string GetInfo()
{
return AppDomain.CurrentDomain.FriendlyName;
}
}
public class MyApp
{
public static void Main()
{
AppDomain apd = AppDomain.CreateDomain("Rajendrs Domain");
MyAppDomain apdinfo = (MyAppDomain) apd.CreateInstanceAndUnwrap(Assembly.GetCallingAssembly(
)
.GetName()
.Name, "MyAppDomain");
Console.WriteLine("Application Name = " + apdinfo.GetInfo());
}
}
C#
Copy
For further info click on the link,
 AppDomain concept in ASP.Net
Question 15 - What is Query String in ASP?
Answer: A QueryString is a collection of characters input to a computer or web browser. A Query String is helpful when we want to transfer a value from one page to
another. When we need to pass content between the HTML pages or aspx Web Forms in the context of ASP.NET, a Query String is Easy to use and the Query String follows
a separating character, usually a Question Mark (?). It is basically used for identifying data appearing after this separating symbol. A Query String Collection is used to
retrieve the variable values in the HTTP query string. If we want to transfer a large amount of data then we can't use the Request.QueryString. Query Strings are also
generated by form submission or can be used by a user typing a query into the address bar of the browsers. Syntax of Query String Request.QueryString(variable)
[(index).count]

Advantages
 Simple to Implement
 Easy to get information from Query string.
 Used to send or read cross domain (from different domain).
Disadvantages
 Human Readable
 Client browser limit on URL length
 Cross paging functionality makes it redundant
 Easily modified by end user
For further info click on the link,
 Query Strings in ASP.Net
Question 16 - What is master page in ASP.NET?
Answer: The extension of MasterPage is '.master'. MasterPage cannot be directly accessed from the client because it just acts as a template for the other Content Pages.
In a MasterPage we can have content either inside ContentPlaceHolder or outside it. Only content inside the ContentPlaceHolder can be customized in the Content Page.
We can have multiple masters in one web application.A MasterPage can have another MasterPage as Master to it. The MasterPageFile property of a webform can be set
dynamically and it should be done either in or before the Page_PreInit event of the WebForm. Page.MasterPageFile = "MasterPage.master". The dynamically set Master
Page must have the ContentPlaceHolder whose content has been customized in the WebForm. A master page is defined using the following code,  <%@ master
language="C#" %> Adding a MasterPage to the Project 
1. Add a new MasterPage file (MainMaster.master) to the Web Application.
2. Change the Id of ContentPlaceHolder in <Head> to "cphHead" and the Id "ContentPlaceHolder1" to "cphFirst".
3. Add one more ContentPlaceHolder (cphSecond) to Master page.
4. To the master page add some header, footer and some default content for both the content place holders.
5. <form id="form1" runat="server"> Header...
6. <br />
7. <asp:ContentPlaceHolder id="cphFirst" runat="server"> This is First Content Place Holder (Default) </asp: ContentPlaceHolder>
8. <br />
<asp:ContentPlaceHolder ID="cphSecond" runat="server">
ASP.NET (C#)
Copy
This is the second Content Place Holder (Default).
</asp:ContentPlaceHolder>
<br /> Footer...
</form>
ASP.NET (C#)
Copy
For further info click on the link:
 Master Page in ASP.NET
Question 17 - What is tracing in .NET?
Answer: Tracing helps to see the information of issues at the runtime of the application. By default Tracing is disabled. Tracing has the following important features:
1. We can see the execution path of the page and application using the debug statement.
2. We can access and manipulate trace messages programmatically.
3. We can see the most recent tracing of the data.
Tracing can be done with the following 2 types.
1. Page Level When the trace output is displayed on the page and for the page-level tracing we need to set the property of tracing at the page level.  <%@ Page
Trace="true" Language="C#"  
2. Application Level In Application-Level tracing the information is stored for each request of the application. The default number of requests to store is 10. But if you
want to increase the number of requests and discard the older request and display a recent request then you need to set the property in the web.config
file. <trace enabled="true"/>
For further info click on the link,
 Introduction to Tracing in .Net
Question 18 - What are the data controls available in ASP.NET?
Answer: The Controls having DataSource Property are called Data Controls in ASP.NET. ASP.NET allows a powerful feature of data binding, you can bind any server control
to simple properties, collections, expressions and/or methods. When you use data binding, you have more flexibility when you use data from a database or other means.
Data Bind controls are container controls. Controls -> Child Control Data Binding is binding controls to data from databases. With data binding we can bind a control to a
particular column in a table from the database or we can bind the whole table to the data grid. Data binding provides simple, convenient, and powerful way to create a
read/write link between the controls on a form and the data in their application. Data binding allows you to take the results of properties, collection, method calls, and
database queries and integrate them with your ASP.NET code. You can combine data binding with Web control rendering to relieve much of the programming burden
surrounding Web control creation. You can also use data binding with ADO.NET and Web controls to populate control contents from SQL select statements or stored
procedures. Data binding uses a special syntax <%# %> The <%#, which instructs ASP.NET to evaluate the expression. The difference between a data binding tags and a
regular code insertion tags <% and %> becomes apparent when the expression is evaluated. Expressions within the data binding tags are evaluated only when the
DataBind method in the Page objects or Web control is called. Data Bind Control can display data in connected and disconnected model. Following are data bind controls
in ASP.NET,
 Repeater Control
 DataGrid Control
 DataList Control
 GridView Control
 DetailsView
 FormView
 DropDownList
 ListBox
 RadioButtonList
 CheckBoxList
 BulletList etc.
For further info click on the link,
 Data Bind Controls in ASP.NET
Question 19 - What are the major events in global.aspx?
Answer: The Global.asax file, which is derived from the HttpApplication class, maintains a pool of HttpApplication objects, and assigns them to applications as needed. The
Global.asax file contains the following events,
 Application_Init
 Application_Disposed
 Application_Error
 Application_Start
 Application_End
 Application_BeginReques
For further info click on the link,
 Major Events in GLOBAL.ASAX file
Question 20 - What is the use of CheckBox in .NET?
Answer: The CheckBox control is a very common control of HTML, unlike radio buttons it can select multiple items on a webpage. The CheckBox control in ASP.NET has
many properties and some of them are listed below.
Property Description
Specifies whether the form should be posted immediately after the Checked
AutoPostBack
property has changed or not. The default is false.
CausesValidation Specifies if a page is validated when a Button control is clicked.
Checked Specifies whether the check box is checked or not.
Attribute names and values used for the Input element for the CheckBox
InputAttributes
control.
Attribute names and values used for the Label element for the CheckBox
LabelAttributes
control.
runat Specifies that the control is a server control. Must be set to "server".
Text The text next to the check box.
TextAlign On which side of the check box the text should appear (right or left).
Group of controls for which the Checkbox control causes validation when it
ValidationGroup
posts back to the server.
The name of the function to be executed when the Checked property has
OnCheckedChanged
changed.
For further info click on the link,
 Use CheckBox inside Gridview in ASP.NET
Question 21 - What is authentication and authorization in ASP.NET?
Answer 
 Authentication: Prove genuineness
 Authorization: process of granting approval or permission on resources.
In ASP.NET authentication means to identify the user or in other words it's nothing but validating that he exists in your database and he is the proper user. Authorization
means does he have access to a particular resource on the IIS website. A resource can be an ASP.NET web page, media files (MP4, GIF, JPEG etc), compressed file (ZIP,
RAR) etc.

  
Types of authentication and authorization in ASP.NET
There are three ways of doing authentication and authorization in ASP.NET:
Windows authentication
In this methodology ASP.NET web pages will use local windows users and groups to authenticate and authorize resources.
Forms Authentication
This is a cookie based authentication where username and password are stored on client machines as cookie files or they are sent through URL for every request. Form-
based authentication presents the user with an HTML-based Web page that prompts the user for credentials.
Passport authentication
Passport authentication is based on the passport website provided by the Microsoft .So when user logins with credentials it will be reached to the passport website ( i.e.
hotmail,devhood,windows live etc) where authentication will happen. If Authentication is successful it will return a token to your website.
Anonymous access
If you do not want any kind of authentication then you will go for Anonymous access.
In 'web.config' file set the authentication mode to 'Windows' as shown in the below code snippets.
<authentication mode="Windows"/>
ASP.NET (C#)
Copy
We also need to ensure that all users are denied except authorized users. The below code snippet inside the authorization tag that all users are denied. '?' indicates any
unknown user. 
<authorization>
<deny users="?"/>
</authorization>
ASP.NET (C#)
Copy
For further info click on the link:
 ASP.NET Authentication and Authorization
Question 22 - What are the HTML server controls in ASP.NET?
Answer: The Microsoft.NET Framework provides a rich set of server-side controls for developing Web applications. You can add these controls to WebForms pages just as
you add Windows controls to a form. Server-side controls are often called server controls or Web Forms controls. There are four types of Server controls: HTML server
controls. Web server controls, validation control, and user controls.
 HTML Server controls HTML developers must be familiar with old HTML controls, which they use to write GUI applications in HTML. These controls are the same
HTML controls; you can run these controls on the server by defining the runat ="server" attribute. These control names start with Html.  
Controls Description
HtmlForm Create an HTML form control, used as a place holder of other controls.
HtmlInputText Creates an input text box control used to get input from user.
HtmltextArea Creates multiline text box control.
HtmlAnchor Creates a Web navigation.
HtmlButton Creates a button control.
HtmlImage Creates an image control, which is used to display an image.
HtmlInputCheckBox Creates a check box control.
HtmlInputRadioButton Creates a radio button control.
HtmlTable Creates a table control.
HtmlTableRow Creates a row within a table.
HtmlTableCell Creates a cell with in a row.
o Web Server Controls
o Validation Controls
o User Controls
For further info click on the link:
 ASP .NET Server-Side controls
Question 23 - What are the authentication modes in ASP.NET for security?
Answer: When you begin a program for a customer using ASP.NET, you should consider about security. Security is one of the most important components of any
application. Security is even more important when you are making a web application which is exposed to million of users. ASP.NET provides classes and methods that
ensure that the application is secure from outside attacks. In this article we will investigate the different types of authentication provided by ASP.NET. In web.config file
you can set authentication mode value 'windows' or 'forms'. What's about difference and how to you use them? (Authentication have some other values to, this article
does not consider them.). How to use mode "Windows"? Windows Authentication mode provides the developer the ability to authenticate a user based on Windows
user accounts. This is the default authentication mode provider by ASP.NET. This will return the computer name along with the user name.  
<authentication mode="Windows">
<forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/"timeout="30" />
</authentication>
ASP.NET (C#)
Copy
How to use mode "Forms"? Insert the <Forms> tag, and fill the appropriate attributes.
<authentication mode="Forms">
<forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/"timeout="30" />
</authentication>
ASP.NET (C#)
Copy
For further info click on the link,
 Authentication Modes in ASP.Net for Security
Question 24 - What is the web API in ASP.NET?
Answer: It is a framework provided by Microsoft for writing HTTP services. There are many frameworks available to build HTTP based services. They follow a common
guideline of international standardization but with different flavors. For example, all framework must adhere to these status codes-
 1xx - Informational Message
 2xx - Successful
 3xx - Redirection
 4xx - Client Error
 5xx - Server Error
Features
 It is light weight and thus good for small devices also like tablets, smart phones.
 No tedious & extensive configuration like WCF REST is required.
 MediaTypeFormatter makes easy to configure your APIs response type in single line (JSON, XML and so on).
 IIS Hosting dependency is no more and it can be hosted in application too.
 Easy and simple control with HTTP features such as Caching, Versioning, request/response headers and its various content formats.
 It support content-negotiation (deciding the best response data format that client can accept).
For further info click on the link,
 Basic Understanding On ASP.NET Web API
Question 25 - Describe application state management in ASP.NET?
Answer: Application Level State Management is used to maintain the state of all the users accessing the web forms present within the website. The value assigned for an
application is considered as an object. Application object will not have any default expiration period. Whenever the webserver has been restarted or stopped then the
information maintained by the application object will be lost. If any data is stored on the application object then that information will be shared upon all the users
accessing the webserver. Since the information is shared among all the users, it is advisable to lock and unlock the application object as per requirement.  Global
Application Class(Global.asax) It is a Class which consists of event handlers which executes the code implicitly whenever a relevant task has been performed on the web
server.Design: 
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
}
</script>
C#
Copy
For further info click on the link,
 Application Level State Management in ASP.NET
Question 26 - What is the code behind and Inline Code?
Answer Code Behind Code Behind refers to the code for an ASP.NET Web page that is written in a separate class file that can have the extension of .aspx.cs or .aspx.vb
depending on the language used. Here the code is compiled into a separate class from which the .aspx file derives. You can write the code in a separate .cs or .vb code file
for each .aspx page. One major point of Code Behind is that the code for all the Web pages is compiled into a DLL file that allows the web pages to be hosted free from any
Inline Server Code. Inline Code Inline Code refers to the code that is written inside an ASP.NET Web Page that has an extension of .aspx. It allows the code to be written
along with the HTML source code using a <Script> tag. It's major point is that since it's physically in the .aspx file it's deployed with the Web Form page whenever the Web
Page is deployed. For further info click on the link,
 Code Behind and Inline Code in ASP.NET
Question 27 - What is the ASP.NET page life Cycle?
Answer: When a page is requested by the user from the browser, the request goes through a series of steps and many things happen in the background to produce the
output or send the response back to the client. The periods between the request and response of a page is called the "Page Life Cycle".
 Request: Start of the life cycle (sent by the user).
 Response: End of the life cycle (sent by the server).
There are four stages that occur during the Page Life Cycle before the HTML Response is returned to the client. Later in this article we"ll study all these stages and their
sub events.
1. Initialization
2. Loading
3. Rendering
4. Unloading
Initialization During this stage the IsPostback property is set. The page determines whether the
request is a Postback (old request) or if this is the first time the page is being
processed (new request). Controls on the page are available and each control's
UniqueID property is set. Now if the current request is a postback then the data has
not been loaded and the value of the controls have not yet been restored from the
view state.
Loading At this stage if the request is a Postback then it loads the data from the view state.
Before rendering, the View State is saved for the page and its controls. During this
Rendering phase, the page calls the render method for each control, providing a text writer that
writes its output to the OutputStream of the page's Response property.
Unload is called after the page has been fully rendered, sent to the client and is ready
Unloading to be discarded. At this point also the page properties such as Response and Request
are unloaded.
For further info click on the link:
 ASP.Net Page Life Cycle
Question 28- What is the ASP.NET page life cycle events?
Answer: We have many events in ASP.NET page life cycle let’s see some most important events:
 Page request When ASP.NET gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly
the response is sent,  
 Starting of page life cycle At this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page
is set to true. The UICulture property of the page is also set.  
 Page initialization At this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request
postback data is loaded and the control properties are restored to the view-state values.  
 Page load At this stage, control properties are set using the view state and control state values.  
 Validation Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.  
 Postback event handling If the request is a postback (old request), the related event handler is called.  
 Page rendering At this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is
written to the OutputStream class of the Page's Response property.  
 Unload The rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.
ASP.NET Page Life Cycle Events Following are the page life cycle events:
 PreInit PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master
pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a
Page_PreInit handler.  
 Init Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init
handler.  
 InitComplete InitComplete event allows tracking of view state. All the controls turn on view-state tracking.  
 LoadViewState LoadViewState event allows loading view state information into the controls.  
 LoadPostData During this phase, the contents of all the input fields defined with the <form> tag are processed.  
 PreLoad PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.  
 Load The Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load handler.  
 LoadComplete The loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler.  
 PreRender The PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output
is rendered.  
 PreRenderComplete as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.  
 SaveStateComplete State of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This
stage can be handled by overriding the Render method or creating a Page_Render handler.  
 UnLoad The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup
is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a
Page_UnLoad handler.
For further info click on the link,
 Page Life Cycle in ASP.Net and its Events
Question 29 - Describe login Controls in ASP?
Answer: The Login control provides the user interface to log a user into a web site. The Login control uses the Membership service to authenticate the user in your
membership system. The default Membership service from your configuration file will be used automatically, however you can also set the Membership provider that you
would like used as a property on the control. The Login Control consists of,
 Username Label and Textbox: Collects the string used to identify the user in the membership system.
 Password Label and Textbox: Collects the password for the specified user. The textbox text is always obscured.
 LoginButton: The button to submit the users request for authentication.
 RememberMe: Configurable to display a checkbox giving the user the option to store a persistent cookie on the user's machine.
 Title and Instruction: Text to orient and guide the user through the process.
 Links: Configurable links to help, password recovery and user registration information.
 Validators: Required field Validators for the username and password textboxes.
For Example,
<asp:Login ID="Login1" runat="server" BackColor="#FFE0C0" BorderColor="Red" ></asp:Login>
ASP.NET (C#)
Copy
For further info click on the link,
 How to use Login Control in Visual Studio 2008
Question 30 - How to use repeater control in ASP.NET?
Answer: A Repeater is a Data-bound control. Data-bound controls are container controls. It creates a link between the Data Source and the presentation UI to display the
data. The repeater control is used to display a repeated list of items. The main use of Repeater Control is for displaying a repeated list of items bound to the control. A
Repeater Control is faster and lightweight for displaying data compared to a GridView or DataGrid. With the Repeater control we can display data in a custom format. The
main drawback of a Repeater Control is that it doesn't support paging and sorting. The Repeater Control has the following types of template fields,
 Item Template
 AlternatingItem Template
 Header Template
 Footer Template
 Separator Template
Write connection code and select command in code bihaind file like: 
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP34;Initial Catalog=yatendra;Persist Security Info=True;User ID=sa;
Password = Password$2 ");
SqlDataAdapter sda = new SqlDataAdapter("select * from Student_Details1", con); DataTable dt = new DataTable(); sda.Fill(dt); Repeater1.DataSource = dt;
Repeater1.DataBind();
}
C#
Copy
Now use Repeater control object in .aspx file like:  
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div>
<table>
<tr>
<th>Student
<%#Eval("S_ID")%>
</th>
</tr>
<tr>
<td>Student Name</td>
<td>
<%#Eval("Student_Name")%>
</td>
</tr>
<tr>
<td>Registration Number</td>
<td>
<%#Eval("Register_No")%>
</td>
</tr>
<tr>
<td>Date Of Birth</td>
<td>
<%#Eval("D_O_B")%>
</td>
</tr>
<tr>
<td>Date Of Examination</td>
<td>
<%#Eval("D_O_E")%>
</td>
</tr>
<tr>
<td>Department</td>
<td>
<%#Eval("Department")%>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
ASP.NET (C#)
Copy
 
When you run this page the output will look like:
For further info click on the link,
 ASP.Net Repeater Control Using C#
Question 31 - What are different methods of session maintenance in ASP.NET?
Answer: Session is a State Management Technique. A Session can store the value on the Server. It can support any type of object to be stored along with our own custom
objects. A session is one of the best techniques for State Management because it stores the data as client-based, in other words the data is stored for every user
separately and the data is secured also because it is on the server. We can set the session on one of the following 2 types of configuration files:
1. Machine Configuration file: Machine Configuration is applied for all application.
2. Application Configuration file: It's applied for only application by application basis.

Session Mode In ASP.NET there are 4 types of Session Mode. Off


We can disable the session mode for the entire application using the off mode.

According to performance and durability the difference between InProc,State Server and SQL Server is:
Session mode Performance Durability
InProc More(1 processor and 1 server) less.
State Server Medium(n processor and 1 server) Medium
SQL Server Less More
For further info click on the link,
 Introduction To ASP.NET Sessions
Question 32 - What is the Difference between session and caching?
Answer: The first main difference between session and caching is: a session is per-user based but caching is not per-user based, So what does that mean? Session data is
stored at the user level but caching data is stored at the application level and shared by all the users. It means that it is simply session data that will be different for the
various users for all the various users, session memory will be allocated differently on the server but for the caching only one memory will be allocated on the server and if
one user modifies the data of the cache for all, the user data will be modified. For further info click on the link,
 Difference Between Session and Caching
Question 33 - What is the difference between HttpContext.Current.Items and HttpContext.Current.Session in ASP.NET?
Answer: Session state is one of the popular state management techniques in ASP.NET environment. We developer people play with session storage every now and then.
It’s pretty simple to manage session if you understand the basic concept. Here is the syntax to do that
Session[“KEY”] =”Value”;
C#
Copy
Or
Session[index] = ”Value”;
C#
Copy
 Let’ s a have an example: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApp
{
public partial class WebForm1: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
HttpContext.Current.Items["Value"] = "Sourav Kayal in ITEM";
HttpContext.Current.Session["Value"] = "Sourav Kayal in SESSION";
Response.Write((string)(HttpContext.Current.Items["Value"]) + "<br>");
Response.Write((string)(HttpContext.Current.Session["Value"]));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write((string)(HttpContext.Current.Items["Value"]) + "<br>");
Response.Write((string)(HttpContext.Current.Session["Value"]));
}
}
}
C#
Copy

Question 34 - What is the difference between Server.Transfer and Response.redirect?


Answer: Both Response.Redirect and Server.Transfer methods are used to transfer a user from one web page to another web page. Both methods are used for the same
purpose but still there are some differences as follows. The Response.Redirect method redirects a request to a new URL and specifies the new URL while the
Server.Transfer method for the current request, terminates execution of the current page and starts execution of a new page using the specified URL path of the page.
Both Response.Redirect and Server.Transfer has same syntax like:
Response.Redirect("UserDetail.aspx");
Server.Transfer("UserDetail.aspx");
Before touching on more points I want to explain some HTTP status codes, these are important for the understanding of the basic differences between these two. The
HTTP status codes are the codes that the Web server uses to communicate with the Web browser or user agent.

Question 35 - What is page directives in ASP.NET?


Answer: Basically Page Directives are commands. These commands are used by the compiler when the page is compiled. How to use the directives in an ASP.NET page It
is not difficult to add a directive to an ASP.NET page. It is simple to add directives to an ASP.NET page. You can write directives in the following format:  <%@[Directive]
[Attributes]%> See the directive format, it starts with "<%@" and ends with "%>". The best way is to put the directive at the top of your page. But you can put a directive
anywhere in a page. One more thing, you can put more than one attribute in a single directive. Here is the full list of directives,
 @Page
 @Master
 @Control
 @Import
 @Implements
 @Register
 @Assembly
 @MasterType
 @Output Cache
 @PreviousPageType
 @Reference

What is a Page Directive?

Basically, Page Directives are commands. These commands are used by the compiler when the page is compiled.

How to use the directives in an ASP.NET page

It is not difficult to add a directive to an ASP.NET page. It is simple to add directives to an ASP.NET page. You can write directives in the following format:

<%@[Directive][Attributes]%>

See the directive format, it starts with "<%@" and ends with "%>". The best way is to put the directive at the top of your page. But you can  put a directive anywhere in a
page. One more thing, you can put more than one attribute in a single directive.

Here is the full list of directives:


 @Page
 @Master
 @Control
 @Import
 @Implements
 @Register
 @Assembly
 @MasterType
 @Output Cache
 @PreviousPageType
 @Reference
Let's discuss something about each directive.

@Page

When you want to specify the attributes for an ASP.NET page then you need to use @Page Directive. As you know, an ASP.NET page is a very important part of ASP.NET,
so this directive is commonly used in ASP.NET.

Example:
1. <%@Page Language="C#" AutoEventWIreup="false" CodeFile="Default.aspx.cs" Inherits="_Default"%>  
@Master

Now you have some information about @Page Directives. The @Master Directive is quite similar to the @Page Directive. The only difference is that the @master directive
is for Master pages. You need to note that, while using the @Master Directive you define the template page's property. Then any content page can inherit all the
properties defined in the Master Page. But there are some properties that are only available in a Master Page.

Example
1. <%@Master Language="C#" AutoEventWIreup="false" CodeFile="MasterPage1.master.cs" Inherits="MasterPage"%>
@Control

@Control builds ASP.NET user controls. When you use the directive you define the properties to be inherited by the user controls and theses values are assigned to the
user controls

Example:
1. <%@Control Language="C#" Explicit="True" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
@Import

As you know you need to define namespaces in your .cs class before using a C# or VB class. So the @Import Directive imports namespaces. This directive supports just a
single attribute "namespace" and this attribute takes a string value that specifies the namespace to be imported. One thing you need to note is that the @Import Directive
cannot contain more than one attribute/value pair. But you can use multiple lines.

Example:
1. <%@Import Namespace="System.Data"%>
@Implements

The @Implements Directive gets the ASP.NET pages to implement .Net framework interfaces. This directive only supports a single attribute interface.

Example:
1. <%@Implements Interface="System.Web.UI.IValidator"%>
@Register

When you create a user control and you drag that user control onto your page then you will see the @Register directive. This directive registers your user control on the
page so that the control can be accessed by the page.

Example:
1. <%@ Register TagPrefix="MayTag Namespace="MyName.MyNameSpace" Assembly="MyAssembly"%>
@Assembly

The @Assembly Directive attaches assemblies to the page or an ASP.NET user control thereby all the assembly classes and interfaces are available to the class. This
directive supports the two attributes Name and src. The Name attribute defines the assembly name and the src attribute defines the source of the assembly.

Example:
1. <%@Assembly Name="MyAssembly"%>  
2. <%@Assembly src="MYAssembly.cs">
@MasterType

The @MasterType Directive connects a class name to the ASP.NET page for getting strongly typed references or members contained in the specified Master Page. This
directive supports the two attributes Typename and virtualpath. Typename sets the name of the derived class from which to get the strongly typed or reference members
and virtualpath sets the location of the page from which these are retrieved.

Example:
1. <%@MasterType VirtualPath="/MasterPage1.master"%>
@output cache

It controls the output caching policies of an ASP.NET page.

Example:
1. <%@ OutputCache Duration ="180" VaryByParam="None"%>
@Previouspagetype

This directive specifies the page from which any cross-page posting originates.

@Reference

This directive declares that another page or user control shout be complied along with the active page or control. This directive supports the single attribute virtualpath. It
sets the location of the page or user control from which the active page will be referenced.

Example:
1. <%@Reference VirtualPayh="~/MyControl.ascx"%>

Question 36 - What is HTTP Handler?


Answer: Every request into an ASP.NET application is handled by a specialized component known as an HTTP handler. The HTTP handler is the most important ingredient
while handling ASP.NET requests. Examples: ASP.NET uses different HTTP handlers to serve different file types. For example, the handler for web Page creates the page
and control objects, runs your code, and renders the final HTML. ASP.NET default handlers,
1. Page Handler (.aspx) - Handles Web pages.
2. User Control Handler (.ascx) - Handles Web user control pages.
3. Web Service Handler (.asmx) - Handles Web service pages.
4. Trace Handler (trace.axd) - Handles trace functionality.
Why we need to create our own HTTP Handler: Sometime we need to avoid ASP.NET full page processing model, which saves lot of overheads, as ASP.NET web form
model has to go through many steps such as creating web page objects, persisting view state etc. What we are interested in is to develop some low level interface that
provides access to objects like Request and Response but doesn't use the full control based web form model discussed above. Examples
1. Dynamic image creator - Use the System.Drawing classes to draw and size your own images.
2. RSS - Create a handler that responds with RSS-formatted XML. This would allow you to add RSS feed capabilities to your sites.
3. Render a custom image,
4. Perform an ad hoc database query,
5. Return some binary data.
All HTTP handlers are defined in the <httpHandlers> section of a configuration file which is nested in the <system.web> element.
<httpHandlers>
<add verb="*" path="trace.axd" validate="true" type="System.Web.Handlers.TraceHandler" />
<add verb="*" path="*.config" validate="true" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.cs" validate="true" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.aspx" validate="true" type="System.Web.UI.PageHandlerFactory" /> </httpHandlers>
Question 37 - What are the differences between ASP.NET HttpHandler and HttpModule?
Answer: The user requests for a resource on web server. The web server examines the file name extension of the requested file, and determines which ISAPI extension
should handle the request. Then the request is passed to the appropriate ISAPI extension. For example when an .aspx page is requested it is passed to ASP.NET page
handler. Then Application domain is created and after that different ASP.NET objects like Httpcontext, HttpRequest, HttpResponse are created. Then instance of
HttpApplication is created and also instance of any configured modules. One can register different events of HttpApplication class like BeginRequest, AuthenticateRequest,
AuthorizeRequest, ProcessRequest etc. HTTP Handler HTTP Handler is the process which runs in response to a HTTP request. So whenever user requests a file it is
processed by the handler based on the extension. So, custom http handlers are created when you need to special handling based on the file name extension. Let's
consider an example to create RSS for a site. So, create a handler that generates RSS-formatted XML. Now bind the .rss extension to the custom handler.  HTTP
Modules HTTP Modules are plugged into the life cycle of a request. So when a request is processed it is passed through all the modules in the pipeline of the request. So
generally http modules are used for,
 Security: For authenticating a request before the request is handled.
 Statistics and Logging: Since modules are called for every request they can be used for gathering statistics and for logging information.
 Custom header: Since response can be modified, one can add custom header information to the response.
Question 38 - Explain the AdRotator Control?
Answer: AdRotator controls are used to create a dynamic ads. The AdRotator Control presents ad images each time a user enters or refreshes a webpage. When the ads
are clicked, it will navigate to a new Web location. The AdRotator control is used to display a sequence of ad images.The AdRotator control to work we need an
Advertisement file (XML file) and some sample images. Adding the AdRotator web server control to your web application. first, select the AdRotator and drag and drop the
control to your web form. Map the XML file which contains the details about each and every ad. The advertisement file is an XML file. The following are some of the
elements of this XML file.
1. <imageUrl>: Optional. The path to the image file.
2. <NavigateUrl>: Optional. The URL to link to if the user clicks the ad.
3. <AlternateText>: Optional. An alternate text for the image.
4. <Impressions>: Optional. The display rates in percent of the hits.
XML code that has the details about the ads. The file Ads.xml looks like the code below
<Advertisements>
<Ad>
<ImageUrl>adimages/2.jpg</ImageUrl>
<NavigateUrl>http://cat2.com</NavigateUrl>
<AlternateText>Cat 2</AlternateText>
<Impressions>30</Impressions>
</Ad>
<Ad>
<ImageUrl>adimages/3.jpg</ImageUrl>
<NavigateUrl>http://cat3.com</NavigateUrl>
<AlternateText>Cat 3</AlternateText>
<Impressions>20</Impressions>
</Ad>
<Ad>
<ImageUrl>adimages/4.jpg</ImageUrl>
<NavigateUrl>http://cat4.com</NavigateUrl>
<AlternateText>Cat 4</AlternateText>
<Impressions>10</Impressions>
</Ad>
</Advertisements>
Question 39 - What is cross-page posting in ASP.NET?
Answer: ASP.NET 1.1 provides for web forms posting back only to themselves. In many situations, the solution requires posting to a different web page. The traditional
workaround alternatives were to use Response.Redirect and/or Server.Transfer to move to a different page and simulate cross page post-back behavior. ASP.NET 2.0
provides a feature known as Cross Page PostBack for a web form to post-back to a different web form (other than itself) How to post to a different page To set a web
form to post back to a different web form, in the source web form, set the PostBackURL property of a control that implements IButtonControl (eg. Button, ImageButton,
LinkButton) to the target web form. When the user clicks on this button control, the web form is cross-posted to the target web form. No other settings or code is required
in the source web form. Access source page info within the posted page: FindControl Method The target web form resulting from the cross-page postback provides a
non-null PreviousPage property. This property represents the source page and provides reference to the source web form and its controls. The controls on the source
page can be accessed via the FindControl method on the object returned by the PreviousPage property of the target page.
protected void Page_Load(object sender, EventArgs e)
{
...
TextBox txtStartDate = (TextBox) PreviousPage.FindControl("txtStartDate ");
...
}
C#
Copy
At this point the target page does not have any knowledge of the source page. The PreviousPage property is of the type Page. For accessing controls using FindControl, the
developer has to presume a certain structure in the source web form. This approach using FindControl has a few limitations. FindControl is dependent on the developer to
provide the ids of the controls to access. The code will stop working if the control id is changed in the source web form. The FindControl method can retrieve controls only
within the current container. If you need to access a control within another control, you need to first get a reference to the parent control.  Access source page info within
the posted page: @PreviousPageType Directive There is another more direct option to get access to the source page controls if the source page is pre-determined. The
@PreviousPageType directive can be used in the target page to strongly type the source page. The directive specifies the source page using either the VirtualPath attribute
or the TypeName attribute. The PreviousPage property then returns a strongly typed reference to the source page. It allows access to the public properties of the source
page.
SourcePage.aspx
<form runat="server"> ...
<asp:textbox runat="server" id="txtFirstName" />
<asp:textbox runat="server" id="txtLastName" />
<asp:button runat="server" id="btnViewReport" Text="View Report" PostbackURL="~/targetpage.aspx" /> ... public string FirstName { get { return
txtFirstName.Text; } } ...
ASP.NET (C#)
Copy
TargetPage.aspx
<%@ PreviousPageType VirtualPath="sourcepage.aspx" %>
string strFirstName;
strFirstName = PreviousPage.FirstName; //Strongly Typed PreviousPage allows direct access to the public properties of the source page
Question 40 - Explain GridView control in ASP.NET?
Answer: The GridView control displays the values of a data source in a table. Each column represents a field, while each row represents a record. The GridView control
supports the following features,
 Binding to data source controls, such as SqlDataSource.
 Built-in sort capabilities.
 Built-in update and delete capabilities.
 Built-in paging capabilities.
 Built-in row selection capabilities.
 Programmatic access to the GridView object model to dynamically set properties, handle events, and so on.
 Multiple key fields.
 Multiple data fields for the hyperlink columns.
 Customizable appearance through themes and styles.
Creating a GridView
<asp:GridView ID="gridService" runat="server">
</asp:GridView>
Question 41 - What is the difference between ASP.NET Web API and WCF?
Answer: The ASP. NET Web API is a framework that uses the HTTP services and makes it easy to provide the response to the client request. The response depends on the
request of the clients. The Web API builds the HTTP services, and handles the request using the HTTP protocols. The request may be GET, POST, DELETE, PUT. We can also
say that the ASP. NET Web API:
 Is an HTTP service.
 Is designed for reaching the broad range of clients.
 Uses the HTTP application.
We use the ASP. NET Web API for creating the REST ful (Representational State Transfer) services. The following are some important points of the ASP. NET Web API,
 The ASP. NET Web API supports the MVC application features that are controller, media formatters, routing etcetera.
 It is a platform for creating the REST services.
 It is a framework for creating the HTTP services.
 Responses can be formatted by the APIs MediaTypeFormatter into the Java Script Object Notation (JSON) and Extencible Markup Language (XML) formats.
For further info click on the link,
 http://www.c-sharpcorner.com/UploadFile/2b481f/difference-between-Asp-Net-web-api-and-wc
Question 42 - What is the PostBack property in ASP.NET?
Answer: If we create a web Page, which consists of one or more Web Controls that are configured to use AutoPostBack (every Web controls will have their own
AutoPostBack property), the ASP.NET adds a special JavaScipt function to the rendered HTML Page. This function is named _doPostBack() . When Called, it triggers a
PostBack, sending data back to the web Server. ASP.NET also adds two additional hidden input fields that are used to pass information back to the server. This information
consists of ID of the Control that raised the event and any additional information if needed. These fields will empty initially as shown below,  
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
ASP.NET (C#)
Copy
The following actions will be taken place when a user changes a control that has the AutoPostBack property set to true: 
1. On the client side, the JavaScript _doPostBack function is invoked, and the page is resubmitted to the server.
2. ASP.NET re-creates the Page object using the .aspx file.
3. ASP.NET retrieves state information from the hidden view state field and updates the controls accordingly.
4. The Page.Load event is fired.
5. The appropriate change event is fired for the control. (If more than one control has been changed, the order of change events is undetermined.)
6. The Page.PreRender event fires, and the page is rendered (transformed from a set of objects to an HTML page).
7. Finally, the Page.Unload event is fired.
8. The new page is sent to the client.
Question 43 - Explain Cookie-less Session in ASP.NET.
Answer: By default a session uses a cookie in the background. To enable a cookie-less session, we need to change some configuration in the Web.Config file. Follow these
steps,
1. Open Web.Config file.
2. Add a <sessionState> tag under <system.web> tag.
3. Add an attribute "cookieless" in the <sessionState> tag and set its value to "AutoDetect" like below:
<sessionState cookieless="AutoDetect" regenerateExpiredSessionId="true"/>
ASP.NET (C#)
Copy
The possible values for "cookieless" attribute are,
 AutoDetect: Session uses background cookie if cookies are enabled. If cookies are disabled, then the URL is used to store session information.
 UseCookie: Session always use background cookie. This is default.
 UseDeviceProfile: Session uses background cookie if browser supports cookies else URL is used.
 UseUri: Session always use URL.
"regenerateExpiredSessionId" is used to ensure that if a cookieless url is expired a new new url is created with a new session. And if the same cookieless url is being used
by multiple users an the same time, they all get a new regenerated session url. For further info click on the link,
 Using Cookie-less Session in ASP.NET
Question 44 - What is Themes in ASP.NET?
Answer: A theme decides the look and feel of the website. It is a collection of files that define the looks of a page. It can include skin files, CSS files & images. We define
themes in a special App_Themes folder. Inside this folder is one or more subfolders named Theme1, Theme2 etc. that define the actual themes. The theme property is
applied late in the page's life cycle, effectively overriding any customization you may have for individual controls on your page. How to apply themes There are 3 different
options to apply themes to our website,
1. Setting the theme at the page level: the Theme attribute is added to the page directive of the page.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"Inherits="Default" Theme="Theme1"%>
ASP.NET (C#)
Copy
2. Setting the theme at the site level: to set the theme for the entire website you can set the theme in the web.config of the website. Open the web.config file and
locate the <pages> element and add the theme attribute to it:
3. <pages theme="Theme1">
4. ....
5. ....
</pages>
ASP.NET (C#)
Copy
6. Setting the theme programmatically at runtime: here the theme is set at runtime through coding. It should be applied earlier in the page's life cycle ie.
Page_PreInit event should be handled for setting the theme. The better option is to apply this to the Base page class of the site as every page in the site inherits
from this class.
Page.Theme = Theme1;
Uses of Themes
1. Since themes can contain CSS files, images and skins, you can change colors, fonts, positioning and images simply by applying the desired themes.
2. You can have as many themes as you want and you can switch between them by setting a single attribute in the web.config file or an individual aspx page. Also
you can switch between themes programmatically.
3. Setting the themes programmatically, you are offering your users a quick and easy way to change the page to their likings.
4. Themes allow you to improve the usability of your site by giving users with vision problems the option to select a high contrast theme with a large font size.
Question 45 - What are the Navigations techniques in ASP.NET?
Answer: Navigation can cause data loss if it not properly handled. We do have many techniques to transfer data from one page to another but every technique has its own
importance and benefits. We will discuss the following techniques in this article. 
 Response.Redirect
 Server.Transfer
 Server.Exceute
 Cross page posting
Question 46 - What is WebParts in ASP.NET?
Answer: ASP.NET 2.0 incorporates the concept of WEB PARTS in itself and we can code and explore that as easily as we have done with the other controls in the previous
sessions. We can compose web parts pages from "web parts", which can be web controls, user controls. Component of Web Parts The web parts consist of different
components like,
 Web Part Manager
 Web Part Zone
 CatLog Part
 CatLog Zone
 Connections Zone
 Editor Part
 Editor Zone
Web Part Zone
 Web Part Zone can contain one or more Web Part controls.
 This provides the layout for the Controls it contains. A single ASPX page can contain one or more Web Part Zones.
 A Web Part Control can be any of the controls in the toolbox or even the customized user controls.
Question 47 - What are master pages?
Answer
Some points about Master Pages,
1. The extension of MasterPage is '.master'.
2. MasterPage cannot be directly accessed from the client because it just acts as a template for the other Content Pages.
3. In a MasterPage we can have content either inside ContentPlaceHolder or outside it. Only content inside the ContentPlaceHolder can be customized in the
Content Page.
4. We can have multiple masters in one web application.
5. A MasterPage can have another MasterPage as Master to it.
6. The content page content can be placed only inside the content tag.
7. Controls of MasterPage can be programmed in the MasterPage and content page but a content page control will never be programmed in MasterPage.
8. A master page of one web application cannot be used in another web application.
9. The MasterPageFile property of a webform can be set dynamically and it should be done either in or before the Page_PreInit event of the WebForm.
Page.MasterPageFile = "MasterPage.master". The dynamically set Master Page must have the ContentPlaceHolder whose content has been customized in the
WebForm.
10. The order in which events are raised: Load (Page) a Load (Master) a LoadComplete (Page) i.e. if we want to overwrite something already done in Load event
handler of Master then it should be coded in the LoadComplete event of the page.
11. Page_Load is the name of method for event handler for Load event of Master. (it's not Master_Load).

Question 48 - What is Data Cache in ASP.NET and how to use?


Answer: Data Cache is used to store frequently used data in the Cache memory. It's much more efficient to retrieve data from the data cache instead of database or other
sources. We need to use System.Web.Caching namespace. The scope of the data caching is within the application domain unlike "session". Every user is able to access this
object. When client requests to the server, server executes the stored procedure or function or select statements on the Sql Server database then it returns the response
to the browser. If we run again same process will happen on the web server with sql server. How to create data cache? Cache ["Employee"] = "DataSet Name" We can
create data caching use Cache Keyword. It's located in the System.Web.Caching namespace. It's just like assigning value to the variable.  How to remove a Data Cache? We
can remove Data Cache manually.
//We need to specify the cache name
Cache.Remove(String key);
Question 49 - Enterprise Library in ASP.NET?
Answer: Enterprise Library: It is a collection of application blocks and core infrastructure. Enterprise library is the reusable software component designed for assisting the
software developers. We use the Enterprise Library when we want to build application blocks intended for the use of developers who create complex enterprise level
application.
Enterprise Library Application Blocks
Security Application Block
Security Application Block provide developers the ability  to incorporate security functionality in the application. This application can use various blocks such as
authenticating and authorizing users against the database.
Exception Handling Application Block
This block allows the developers to create consistency for processing the error that occur throughout the layers of Enterprise Application.
Cryptography Application Block
Cryptography application blocks allows developers to add encryption and hashing functionality in the applications.
Caching Application Block
Caching Application Block allows developers to incorporate local cache in the applications.
Question 50 - How can we improve the Performance of an ASP.NET Web Page?
Answer: This is the most common question from the  ASP.NET forum in any interview. In this post I’m going to point out some of the important points that may help to
improve the performance. Here I used the word “improve performance” in the sense to decrease the loading time of the page. There are various reasons behind this.
Some of them we look into from the “backend side” (Database side) and rest of them we need to take care in “front-end” ((UI) side. For illustrative purposes, you have an
ASP.NET Web site, one of the aspx page take much time to load. Throughout this article, we are going to see how to decrease the loading time.  Back End (DB)
1. Try to check the Query performance -  that is how much time the query will take to execute and pull the records from DB. Then use SQL Server Profiler and
Execution plan for that query so that you can come to a conclusion in which part it took much time.
2. Check in every table (who are all part of the query) Index is created properly.
3. If your query involves a complex stored procedure, which in turn use lot of joins, then you should focus on every table. In some cases, sub-query perform better
than the joins.
4. If your web page involves paging concepts, try to move the paging concepts to SQL Server. I meant that based on the page count the SP will return the records,
instead of bringing the records as a whole.
Storing Session State in a SQL Server Database

Session State and Associated Problems


As in classic ASP, by default the session state is maintained in the Web server's memory. However, this approach poses two problems:
·         It overburdens the server, affecting the Web site's scalability
·         It cannot be used effectively in Web farm scenarios
Let me discuss these problems in a bit of detail so that you can appreciate your choice of a session store.
Session variables are created on a per-user basis. By default, they are maintained in the Web server's memory. Imagine a Web site with thousands of users. Because of the
huge number of users, the number of active sessions on the Web server also will be very high. That means you are storing too much data in the Web server's memory. If
the load on the server keeps of increasing, it may reach saturation and cause trouble for overall scalability of your application.
To tackle the issue of scalability mentioned above people, implement Web farms. A Web farm is a cluster of Web servers running in parallel. Each Web server in the
cluster has a mirror of your Web site. The traffic of your Web site is equally distributed among the available servers, thus providing load balancing. Storing session
variables in the Web server's memory can hamper the Web farm's architecture. Assume that there are three Web servers—S1, S2, and S3—connected in parallel and
serving the incoming requests. A request R1 comes into the cluster and the load balancing logic decides that S2 and S3 are busy with some other task, but S1 is free to
process your request. Naturally, the request gets forwarded to S1 for processing. Now, imagine that during the processing, you store a session variable in S1's memory. So
far, so good. After some time, the same user gives another request, R2, that needs the session variable stored by the previous request, R1. However, this time S1 was
occupied with some work and S2 and S3 are free. You would expect that as per the load-balancing rule, R2 should get forwarded to S2 or S3. But, if that happens, how will
R2 get access to the session variables? After all, they are stored in the memory of the altogether-separate Web server S1. This means R2 still needs to wait for S1 to
become free. This is, of course, a poor use of Web farm resources.
Configuring SQL Server to Store a Session State

Before you can actually store a session state in SQL server, you need to configure it. This configuration is done via a command line tool called  ASPNET_REGSQL.EXE. You
can store the session state in three possible locations within the SQL Server:
Temporary storage: In this case, the session state is stored in the "tempdb" database of SQL Server. The tool creates a database called ASPState and adds certain
stored procedures for managing session to it. The tool also creates required tables in the "tempdb" database. If you restart the SQL server, the session data is not
persisted.
Persistent storage: The tool creates a database called ASPState and adds stored procedures for managing a session to it. The session state is stored in
the ASPState database. The advantage of this method is that the data is persisted even if you restart the SQL server.
Custom storage: Both the session state data and the stored procedures are stored in a custom database. The database name must be specified in the
configuration file.
The following table lists various command line switches of the tool with respect to session store configuration:
Command Description

-S <server> Species the IP address or the name of SQL server in which you want to store the session
state

-U Specifies the user ID to be used when connecting to the SQL Server

-P Specifies the password to be used when connecting to the SQL Server

-E Indicates that you want to use integrated security when connecting to the SQL Server

-ssadd Adds support for the SQLServer mode session state


-ssremove Removes support for the SQLServer mode session state

-sstype Type of session state support. This option can be:


t for temporary storage
p for persistent storage
c for custom storage

-d <database> The name of the custom database to use if -sstype switch is "c"
 
To run the Aspnet_regsql.exe, Startà All Programsà Microsoft Visual Studio 2005/2008à Visual Studio Toolsà Visual Studio 2008 Command Prompt.
It opens command prompt.  Type the following command to create the SQL State Database tables and procedures.

Fig: For creating default Database for SQL State.

Fig: For using the Custom Data Base for maintain SQL State information
Note:  If you use custom database to store Session data, you need to set the property “allowCustomSqlDatabase=True" in Session state attribute in web.config ad
specify the Custom database name in the sqlConnectionString attribute.

 Once completed the above steps, the database tables looks like this:
 
And, The Stored procedures created are:
 
Once Above steps completed, perform the following steps:
1.       Open SQL Server Management Studio.
2.       In SQL Server Management Studio, on the File menu, click Open.
3.       In the Open Query File dialog box, browse to the InstallSqlState.sql script file, and then click Open. By default, InstallSqlState.sql is located in one of the
following folders:
4.       system drive\WINNT\Microsoft.NET\Framework\version\

system drive\Windows\Microsoft.NET\Framework\version\
5.       After InstallSqlState.sql opens, click Execute on the Query menu to run the script.
Required Tables and Stored Procedures will be created for  SQL Server State management.
 
Example:
Open Visual Studioà fileà newà websiteà
Name it as sample.
Open Web.config file to configure SQL State management:
Write this session state configuration:
<system.web>     
<sessionState mode="SQLServer" sqlConnectionString="data source=RAVIKRISHNA; user id=sa;password=sa12$;" cookieless="false" timeout="20"/>
</system.web>
 
Default.aspx:
protected void Page_Load(object sender, EventArgs e)
    {
        Session["Name"] = "Ravikrishna";
        Session["Mobile"] = "9948869222";
    }
 
Once run this website by clicking on “F5†, this session data will be stored on database.

You might also like