Professional Documents
Culture Documents
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.
ValidateRequest="false"
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();
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.
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;
}
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?
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. 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".
Answer: ASP.NET is open source server-side web application framework designed for web development to produce dynamic web pages.
Answer
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.
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).
1. int y = (int)obj;
Note: Conversion of Boxing and UnBoxing reduces Application Performance.
Answer: Garbage collection is the process of managing the allocation and release of memory in your applications.
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.
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.
Answer
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.
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.
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?
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?
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.
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
Basically, Page Directives are commands. These commands are used by the compiler when the page is compiled.
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.
@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
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"%>
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
-E Indicates that you want to use integrated security when connecting to the SQL Server
-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 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.