+ All Categories
Home > Documents > ASP.net Matrial

ASP.net Matrial

Date post: 20-Jul-2016
Category:
Upload: krishna-sai
View: 43 times
Download: 2 times
Share this document with a friend
Description:
Usufull
54
CodeExecutionProcess in asp.net : Versions in asp.net: http://www.wiseowl.co.uk/versions/asp.net/aspnet-40.htm ........ http://www.aspdotnet-suresh.com/2011/10/what-are-differences-between- aspnet-35.html .. http://www.aspdotnet-suresh.com/2011/10/what-are-difference-between- aspnet-20.html CODE EXECUTION PROCESS IN ASP.NET STEP 1 : Client sends request for the required file to the IIS (Webserver). STEP 2 : IIS will locate the requested file. STEP 3 : If requested file is found, IIS will submit that to ISAPI.dll ISAPI.dll is known as ASPX Engine. ISAPI means Internet Services Application Programming Int erface. STEP 4 : ISAPI.dll will generate a Page Class file, by separating Client side code, Server side code & by adding required methods to execute the server side code. STEP 5 : This Page Class is submitted to Compilers (In case of pre-Compilation is not done).
Transcript
Page 1: ASP.net Matrial

CodeExecutionProcess in asp.net :

Versions in asp.net:

http://www.wiseowl.co.uk/versions/asp.net/aspnet-40.htm........

http://www.aspdotnet-suresh.com/2011/10/what-are-differences-between-aspnet-35.html..

http://www.aspdotnet-suresh.com/2011/10/what-are-difference-between-aspnet-20.html

CODE EXECUTION PROCESS IN   ASP.NET

STEP 1: Client sends request for the required file to the IIS (Webserver).

STEP 2: IIS will locate the requested file.

STEP 3: If requested file is found, IIS will submit that to ISAPI.dll

      ISAPI.dll is known as ASPX Engine.

     ISAPI means Internet Services Application Programming Interface.

STEP 4: ISAPI.dll will generate a Page Class file, by separating Client side code, Server side

code & by adding required methods to execute the server side code.

STEP 5: This Page Class is submitted to Compilers (In case of pre-Compilation is not

done).

STEP 6: Compilers will compile the Source Code & will generate MSIL code.

STEP 7: MSIL code will be submitted to CLR.

    CLR will perform 3 tasks here,1. Instantiation:  Creates object to the respective Page Class2. Processing:  Executes the Result/Code3. Rendering:  Converts the Server side code into Client Understandable

format (i.e., HTML and JAVASCRIPT).

STEP 8: CLR will generate complete Execution Result.

Page 2: ASP.net Matrial

STEP 9: Execution Result will be delivered to IIS.

STEP 10: IIS will deliver the result to CLIENT.

Once the Result is delivered to the client, The Object at the Server will be destroyed…

ApplicationDomains:

The CLR can allow the multiple .Net applications to be run in a single AppDomain.

The CLR isolates each application domain from all other application domains and prevents

the configuration, security, or stability of a running .NET applications from affecting other

applications.AnAppDomain can be destroyed without effecting the other Appdomains in

the process.

How to create AppDomain

.NET introduces the concept of an application domain, or AppDomain. Like a process, the AppDomain is both a container and a 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 of a secure boundary…

An AppDomain belongs to only a single process, but single process can hold multiple AppDomains. An AppDomain is relatively cheap to create (compared to a process), and has relatively less overhead to maintain than a process. For these reasons, an AppDomain is a great solution for the ISP who is hosting hundreds of applications. Each application can exist inside an isolated AppDomain, and many of these AppDomains can exist inside of a single process – a cost savings.

AppDomainsAnd You

AppDomains are generally created by Hosts for example Internet Explorer and Asp.net. The following is an example to create instance of an object inside it and then executes one of the objects methods. This is the explicit way of creating AppDomain by .Net Applications 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()

Page 3: ASP.net Matrial

    {        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());    }} The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown. 

Advantages

A single CLR operating system process can contain multiple application domains. There are advantages to having application domains within a single process.

1. Lower system cost - many application domains can be contained within a single system process.

2. Each application domain can have different security access levels assigned to them, all within a single process.

3. Code in one AppDomain cannot directly access code in another AppDomain.4. The application in an AppDomain can be stopped without affecting the state of

another AppDomain running in the same process.5. An  Exception in on AppDomain will not affect other AppDomains or crash the entire

process that hosts the AppDomains

Worker Process:  

Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. All the ASP.Net functionality runs under the scope of worker process. When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS. 

Page 4: ASP.net Matrial

Application Pool:    

Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availabilityfor any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they they are configured into different application pools.

Application Pool with multiple worker process is called “Web Garden”.Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let’s have look how IIS process the request when a new request comes up from client.

Web Farm

After developing our asp.net web application we host it on IIS Server.  Now one standalone server is sufficient to process ASP.NET Request and response for a small web sites but when the site comes for big organization where there an millions of daily user hits then we need to host the sites on multiple Server. This is called web farms. Where single site hosted on multiple IIS Server and they are  running behind the Load Balancer.

Page 5: ASP.net Matrial

Fig : General Web Farm Architecture

This is the most common scenarios for any web based production environment. Where Client will hit an Virtual IP ( vIP) . Which is the IP address of Load Balancer. When Load balancer received the request based on the server load it will redirect the request to particular Server.

Web Garden

All IIS Request process by worker process ( w3wp.exe). By default each and every application pool contain single worker process. But An application pool with multiple worker process is called Web Garden.   Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time. And Each Worker Process Should have there own Thread and Own Memory space.

Page 6: ASP.net Matrial

There are some Certain Restriction to use Web Garden with your web application. If we use Session Mode to "in proc", our application will not work correctly because session will be handled by different Worker Process. For Avoid this Type of problem we should have to use Session Mode "out proc" and we can use "Session State Server" or "SQL-Server Session State".

How To Configure Web Garden?

Right Click on Application Pool > Properties >GoTo Performance Tab In bottom Group Section  Increase the Worker Process Count.

The Application Pool

In this part, we will take a look at one of the new features in IIS 6.0, named Application Pool, and demonstrate the use of application pools in isolating ASP.NET Web applications, thereby increasing the reliability of your ASP.NET Web applications. Then, we also will explore how these application pools affect ASP.NET applications in terms of the identity that is used to run your ASP.NET applications. Along the way, we will also look at the steps to be followed for creating application pools and assigning ASP.NET applications to run under a specific application pool. Finally, we will illustrate how to configure an application pool to run using the credentials of a specific user account.

What is an Application Pool?

An Application Pool can contain one or more applications and allows us to configure a level of isolation between different Web applications. For example, if you want to isolate all the Web applications running in the same computer, you can do this by creating a separate application pool for every Web application and placing them in their corresponding application pool. Because each application pool runs in its own worker process, errors in one application pool will not affect the applications running in other application pools. Deploying applications in application pools is a primary advantage of running IIS 6.0 in worker process isolation mode because you can customize the application pools to achieve the degree of application isolation that you need.

When you configure application pools for optimum availability, you also should consider how to configure application pools for application security. For example, you might need to create separate application pools for applications that require a high level of security, while allowing applications that require a lower level of security to share the same application

Page 7: ASP.net Matrial

pool. In the later part of this article, we will see how to configure identities at the application pool level.

Creating a new Application PoolCreating a new application pool is a very simple process that is carried out by using the IIS manager. When you create a new application pool, you have the following two options:

1. You can either create a new application pool from scratch or2. You can create a new application by importing the configuration settings from an

external XML file

To create a new application pool from scratch, right-click on the Application Pools node from the tree view and select New->Application Pool from the context menu. You will be presented with the following screen, where you need to enter a name for the application pool.

When creating a new application, you also have the option of inheriting the settings from an existing application pool. For example, if you want your new application pool to inherit the settings from theDefaultAppPool, you can do that by selecting the option Use existing application pool as a template in the above screen. After you pick this option, the Application Pool name dropdown box will be enabled from where you can select an existing application pool.

After the pool is created, you can save the settings of the application pool to an external XML file any time by right-clicking the application pool and selecting the option All Tasks->Save Configuration to a File that is available from the context menu. This is an extremely useful feature that makes it possible for you to easily recreate the same application pool on the same server or on a different server with minimal effort.

Page 8: ASP.net Matrial

Configuring Identity for ASP.NET Web Applications

Related Articles

Secure Your ASP.NET Application from a SQL Injection Attack IIS 6.0 and ASP.NET, Part 1 Managing Complex Layout and Nesting DataGrids in ASP.NET

In previous versions of IIS, worker processes ran as LocalSystem, a powerful account that has system administrator privileges on the server. Because LocalSystem has access to almost all resources on the operating system, this caused security implications. As mentioned previously, in IIS 6.0, you can set the identity of the worker process at the application pool level. The identity of an application pool is the account under which the application pool's worker process runs. By default, application pools operate under the NetworkService account, which has low-level user access rights. The NetworkService account has the following seven privileges:

Adjust memory quotas for a process Generate security audits Log on as a service Replace process level token Impersonate a client after authentication Allow logon locally Access this computer from the network

By running the worker process using a very low-privileged account such as NetworkService, you can reduce the security vulnerability. However, by using IIS manager, you can configure the application pool to run as any of the following pre-defined accounts:

NetworkService LocalSystem LocalService

To configure identity for an application pool, right-click the application pool and select Propertiesfrom the context menu. In the Properties dialog box, select the Identity tab and you will see the following screen.

Page 9: ASP.net Matrial

In the above dialog box, when you select the Predefined option, you can select any of the pre-defined accounts from the dropdown box. Instead of using a pre-defined account, if you want your application pool to run under a different account, select the Configurable option and then set the User nameand Password in the textboxes. This approach is particularly useful especially when you are running multiple applications or sites on one Web server. For example, if an ISP hosts two companies—who may even be competitors—on one Web server, it has to guarantee that these two applications run in isolation from each other. More importantly, the ISP has to make sure that a malicious administrator for one application can't access the data of the other application. You can accomplish this level of isolation by using the configurable worker process identity

HTTP Handlers and HTTP Modulers:

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx

Page 10: ASP.net Matrial

file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request…

d/f b/w HTTP HANDLERS AND MODULERS:

HTTP handlers are the end point objects in ASP.NET pipeline and an HTTP Handler essentially processes the request and produces the response. For example an ASP.NET Page is an HTTP Handler.

HTTP Modules are objects which also participate the pipeline but they work before and after the HTTP Handler does its job, and produce additional services within the pipeline (for example associating session within a request before HTTP handler executes, and saving the session state after HTTP handler has done its job, is basically done by an HTTP module..

Connection pooling in asp.net :

Connection pools are actually containers that contain open and reusable connections. Multiple pools can exist in the same application domain at the same point in time, but Connection Pools cannot be shared across application domains. Note that one pool is created per unique connection string. A Connection Pool is created the first time a request for a connection to the database comes in with a unique connection string. Note that if another request comes in with a different connection string for the database, another Connection Pool would be created. Hence, we have one Connection Pool per connection string and not per database. The following code listings below illustrate this.

Listing 1// A new pool is created.SqlConnection sqlConnection = newSqlConnection();sqlConnection.ConnectionString = "Server=localhost;Database=test;User ID=joydip;Password=joydip;Trusted_Connection=False";sqlConnection.Open();      

Listing 2// A new pool is created as the connection strings differ.

Page 11: ASP.net Matrial

SqlConnection conn = new SqlConnection();sqlConnection.ConnectionString = "Server=localhost;Database=test;User ID=test;Password=test;Trusted_Connection=False";sqlConnection.Open();   

Listing 3// The connection string is the same as in Listing 1 so no new pool is created.SqlConnection conn = new SqlConnection();sqlConnection.ConnectionString = "Server=localhost;Database=test;User ID=joydip;Password=joydip;Trusted_Connection=False";sqlConnection.Open();      

When a request for a new connection comes in the connection is served from the Connection Pool without creating a new one, i.e., the connections are re-used without creating new ones.  Therefore, it improves the performance and scalability of your applications. When your application closes an open connection, it is returned to the pool where it waits until a reconnect time out period expires. This is the period within which it waits to connect to the same database using the same credentials. If none comes in within this period, the connection to the database is closed and the connection instance is removed from the pool.

When a new Connection Pool is created, the connection objects are placed in the pool and the pool and the connections contained in it are made available for immediate use. The pool can house connections up to the maximum limit as specified in the connection string that was used to connect to the database. Connections are removed from the pool when they remain inactive for a long period of time or have outlived its specified life time or server connectivity.

A Connection Pool is maintained internally by the Connection Pool Manager. When a request for a subsequent connection comes in, the Connection Pool Manager searches the pool for the availability of a free connection and returns it to the application if one is available. The following points elaborate how the Connection Pool Manager works- the operations that it performs when a request for a new connection comes to it.

         If any unused connection is available, it returns one.

         If all connections are used up, a new connection is created and added to the pool.

         If the number of connections reaches the maximum number of connections in the pool, the requests are queued until a connection becomes free for reuse.

Connection Pooling is controlled and the parameters passed to a connection string that basically comprises the following:

         Connect Timeout

         Min Pool Size

         Max Pool Size

         Pooling

Page 12: ASP.net Matrial

In order to use Connection Pooling efficiently, remember to close the connections once you are done with it so that it returns to the pool….

State Management:

Mainatain state or page information over the multiple requests for same page or d/f page.

ClientSide:

HIddenField:

1. Hidden field

Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It store one value for the variable and it is a preferable way when a variable's value is changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible on the browser. A hidden field travels with every request like a standard control’s value.

if (HiddenField1.Value != null) {int val= Convert.ToInt32(HiddenField1.Value) + 1; HiddenField1.Value = val.ToString(); Label1.Text = val.ToString(); }..

ViewState:

ViewState:

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page..ViewState is used to maintain the state of controls during page postback and if we save any control values or anything in viewstate we can access those values throughout the page whenever it required for that check below simple example..By Default Viewstate is enabled for page and controls.

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its

Page 13: ASP.net Matrial

controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hiddenfield to store its information in a encoding format.

Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code

Example With Code:

Get str=”sdadsadd”; get into lable .in that while clicking the button to post backing that data has to be kept in viewstate.We can Enable or disable to page or controls using viewstate property Enableviewstate=true;

protectedvoidPage_Load(object sender, EventArgs e) {if (!IsPostBack) {stringstr = "Welcome to Aspdotnet-Suresh Site";if (ViewState["SampleText"] == null) {ViewState["SampleText"] = str; } } }

protectedvoid Button1_Click(object sender, EventArgs e) { Label1.Text = ViewState["SampleText"].ToString(); } }…..

Page 14: ASP.net Matrial

Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,

First, you can make sure that the view state information is tamper-proof by using "hash code". You can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands for "Message Authentication Code"

A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.

Second option is to set ViewStateEncryptionMode="Always" with your page directives, which will encrypt the view state data. You can add this in following way

It ViewStateEncryptionMode has three different options to set:

Always Auto Never

Always, mean encrypt the view state always, Never means, Never encrypt the view state data andAuto Says , encrypt if any control request specially for encryption. For auto , control must callPage.RegisterRequiresViewStateEncryption() method for request encryption.

we can set the Setting for "EnableViewStateMAC" and ViewStateEncryptionMode" in web.configalso.

Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.

Page 15: ASP.net Matrial

Step1:- We  get the data table from database in page load event and store it in view state.

protected void Page_Load(object sender, EventArgs e)    {       stringstr = System.Configuration.ConfigurationManager.AppSettings["keyString"];        SqlConnection con = new SqlConnection(str);        SqlDataAdapteradap = new SqlDataAdapter("select * from product", con);       DataTabledt = new DataTable();       adap.Fill(dt);       ViewState["TempTable"] = dt;    }

Step2:-Now we access the table from viewstate on button click event and bind in gridview.

    protected void Button1_Click(object sender, EventArgs e)    {        GridView1.DataSource = (DataTable)ViewState["TempTable"];        GridView1.DataBind();    }..Data Types You Can Store in View StateYou can store objects of the following types in view state:

Strings Integers Boolean values Array objects ArrayList objects Hash tables Custom type converters (see the TypeConverter class for more information)

..ControlState:

 Control State

Control State is another client side state management technique. Whenever we develop a custom control and want to preserve some information, we can use view state but suppose view state is disabled explicitly by the user, the control will not work as expected. For expected results for the control we have to use Control State property. Control state is separate from view state.

Page 16: ASP.net Matrial

How to use control state property: Control state implementation is simple. First override theOnInit() method of the control and add a call for thePage.RegisterRequiresControlState() method with the instance of the control to register. Then override LoadControlState and SaveControlState in order to save the required state information..

QueryString:protected void btnSend_Click(object sender, EventArgs e){Response.Redirect("Default2.aspx?UserId="+txtUserId.Text+"&UserName="+txtUserName.Text);}…Cookies:http://www.codeproject.com/Articles/31914/Beginner-s-Guide-To-ASP-NET-Cookies..Cookie is a small text file which is created by the client's browser and also stored on the client hard disk by the browser. It does not use server memory. Generally a cookie is used to identify users.How:A cookie is a small file that stores user information. Whenever a user makes a request for a page the first time, the server creates a cookie and sends it to the client along with the requested page and the client browser receives that cookie and stores it on the client machine either permanently or temporarily (persistent or non persistence). The next time the user makes a request for the same site, either the same or another page, the browser checks the existence of the cookie for that site in the folder. If the cookie exists it sends a request with the same cookie, else that request is treated as a new request.

Types of Cookies1. Persistence Cookie: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.

Let us see how to create persistence cookies. There are two ways, the first one is:   

 Collapse | Copy Code

Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);

And the second one is:  

 Collapse | Copy Code

HttpCookie aCookieValPer = new HttpCookie("Persistance");aCookieValPer.Value = "This is A Persistance Cookie";

Page 17: ASP.net Matrial

aCookieValPer.Expires = DateTime.Now.AddSeconds(10);Response.Cookies.Add(aCookieValPer);

2. Non-Persistence Cookie: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.

Let us see how to create a non persistence cookies. There are two ways, the first one is:

 Collapse | Copy Code

Response.Cookies["nameWithNPCookies"].Value = "This is A Non Persistance Cookie";

And the second way is:

 Collapse | Copy Code

HttpCookie aCookieValNonPer = new HttpCookie("NonPersistance");aCookieValNonPer.Value = "This is A Non Persistance Cookie;Response.Cookies.Add(aCookieValNonPer);how to create cookie :

How to read a cookie:

 Collapse | Copy Code

if (Request.Cookies["NonPersistance"] != null)Label2.Text = Request.Cookies["NonPersistance"].Value;

Let's understand persistence and non persistence cookies more clearly with a diagram:

Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data. 

Page 18: ASP.net Matrial

ServerSide:

What is SessionState?

The session state is used to maintain the session of each user throughout the application. Session allows information to be stored in one page and access in another page and support any type of object. In many websites we will see the functionality like once if we login into website they will show username in all the pages for that they will store username in session and they will access that session username in all the pages.

…By default, ASP.NET session state is enabled for all ASP.NET applications.Session variables are stored in a SessionStateItemCollectionobject that is exposed through the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object.

CookielessSessionIDsBy default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting thecookieless attribute to true in the sessionState section of the Web.config file.

Example:Default.aspx:

protected void btnSubmit_Click(object sender, EventArgs e){Session["FirstName"] = txtfName.Text;Session["LastName"] = txtlName.Text;Response.Redirect("Default2.aspx");}

..Default2.aspx:

protected void Page_Load(object sender, EventArgs e){if(!IsPostBack){if (Session["FirstName"] == null && Session["LastName"]==null){Session["FirstName"] = "Aspdotnet";Session["LastName"] = "  Suresh";lblString.Text = "Welcome " + Session["FirstName"] + Session["LastName"];}else

Page 19: ASP.net Matrial

{lblString.Text = Session["FirstName"]+" " + Session["LastName"];lblfName.Text = Session["FirstName"].ToString();lbllName.Text = Session["LastName"].ToString();}}……………………….

Session Events in ASP.NET  To manage a session, ASP.NET provides two events: session_start and session_end that is written in a special file called Global.aspx in the root directory of the project. Session_Start: The Session_start event is raised every time a new user makes a request without a session ID, i.e., new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.  

 Collapse | Copy Code

void Session_Start(object sender, EventArgs e){ Session["Count"] = 0; // Code that runs when a new session is started}

Session_End: The Session_End event is raised when session ends either because of a time out expiry or explicitly by using Session.Abandon(). The Session_End event is raised only in the case of Inproc mode not in the state server and SQL Server modes. There are four session storage mechanisms provided by ASP.NET:

There are four session storage mechanisms provided by ASP.NET:

In Proc mode  State Server mode   SQL Server mode  Custom mode  

In Process mode: Note:When the session state mode is set to InProc, the session state variables are stored on the web server memory inside the asp.net worker process. This is the default session state mode..In proc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server's memory (in IIS). If there are more than one IIS servers then session values are stored in each server separately on which request has been made. Since the session values are stored in server, whenever server is restarted the session values will be lost. Advantages of InProc session state mode:1. Very easy to implement. All that is required is, to set, the session state mode=InProc in web.config file.2. Will perform best because the session state memory is kept on the webserver, within the ASP.NET worker process(w3wp.exe).3. Suitable for web applications hosted on a single server.

Page 20: ASP.net Matrial

4. Objects can be added without serialization

Dis-advantages of InProc session state mode:1. Session state data is lost, when the worker process or application pool is recycled.2. Not suitable for web farms and web gardens.3. Scalability could be an issue.

 Collapse | Copy Code

<configuration><sessionstatemode="InProc"cookieless="false"timeout="10"stateConnectionString="tcpip=127.0.0.1:80808"sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/></configuration>

In State Server mode: This mode could store session in the web server but out of the application pool. But usually if this mode is used there will be a separate server for storing sessions, i.e., stateServer. The benefit is that when IIS restarts the session is available. It stores session in a separate Windows service. For State server session mode, we have to configure it explicitly in the web config file and start the aspnet_state service.Notes:the session state variables are stored in a process, called as asp.net state service. This process is different from the asp.net worker process. The asp.net state service can be present on a web server or a dedicated machine. .Advantages of using StateServer session state mode:1. ASP.NET worker process independent. Survives worker process restart. 2. Can be used with web farms and web gardens.3. State server offers more scalability than InProc.

Dis-advantages of using StateServer session state mode:1. StateServer is slower than InProc2. Complex objects, need to be serialized and deserialized3. If the StateServer, is on a dedicated machine, and if the server goes down all the sessions are lost.

 Collapse | Copy Code

<configuration><sessionstatemode="stateserver"cookieless="false"timeout="10"stateConnectionString="tcpip=127.0.0.1:42424"sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/></configuration>

In SQL Server mode: Session is stored in a SQL Server database. This kind of session mode is also separate from IIS, i.e., session is available even after restarting the IIS server. This mode is highly secure and reliable but also has a disadvantage that there is overhead from serialization and deserialization of session data. This mode should be used when reliability is more important than performance. 

Page 21: ASP.net Matrial

Steps to follow, to configure asp.net web application to use SQLServer:1. Create the ASPState database using aspnet_regsql.exe tool. There are several versions of this tool. I am running .NET version 4.0, on a 64 bit operating system. So I will use the version that is present inC:\Windows\Microsoft.NET\Framework64\v4.0.30319.   a) click Start > Type Run > Press Enter   b) Type cmd> Press Enter   c) In the command prompt type - cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319   d) Press Enter   e) Type - aspnet_regsql.exe -S SQLServerName -E -ssadd -sstype p   f) Press Enter. At this point you should have ASPState Database added.   g) For help running this tool, please refer to the following MSDN article         http://msdn.microsoft.com/en-us/library/ms229862(v=vs.100).aspx  Collapse | Copy Code

<configuration><sessionstatemode="sqlserver"cookieless="false"timeout="10"stateConnectionString="tcpip=127.0.0.1:4 2424"sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/></configuration>..Advantages of using SQLServer session state mode:1. SQLServer is the most reliable option. Survives worker process recycling and SQL Server restarts.2. Can be used with web farms and web gardens.3. More scalable than State server and InProc session state modes.

Dis-advantages of using StateServer session state mode:1. Slower than StateServer and InProc session state modes2. Complex objects, need to be serialized and deserialized…

Custom Session mode: Generally we should prefer in proc state server mode or SQL Server mode but if you need to store session data using other than these techniques then ASP.NET provides a custom session mode. This way we have to maintain everything customized even generating session ID, data store, and also security. 

Attributes   Description 

Cookieless true/false  

Indicates that the session is used with or without cookie.cookieless set to true indicates sessions without cookies is used and cookieless set to false indicates sessions with cookies is used. cookieless set to false is the default set. 

timeout  Indicates the session will abound if it is idle before session is abounded explicitly (the default time is 20 min).

Page 22: ASP.net Matrial

StateConnectionString

Indicates the session state is stored on the remote computer (server). This attribute is required when session mode isStateServer

SqlConnectionString Indicates the session state is stored in the database. This attribute is required when session mode is SqlServer. 

2. Application

Application state is a server side state management technique. The date stored in application state is common for all users of that particular ASP.NET application and can be accessed anywhere in the application. It is also called application level state management. Data stored in the application should be of small size.  

How to get and set a value in the application object: Collapse | Copy Code

Application["Count"] = Convert.ToInt32(Application["Count"]) + 1; //Set Value to The Application ObjectLabel1.Text = Application["Count"].ToString(); //Get Value from the Application Object

Application events in ASP.NETThere are three types of events in ASP.NET. Application event is written in a special file calledGlobal.asax. This file is not created by default, it is created explicitly by the developer in the root directory. An application can create more than one Global.asax file but only the root one is read by ASP.NET.Application_start: The Application_Start event is raised when an app domain starts. When the first request is raised to an application then the Application_Start event is raised. Let's see the Global.asax file. 

 Collapse | Copy Code

void Application_Start(object sender, EventArgs e){ Application["Count"] = 0;}

Application_Error: It is raised when an unhandled exception occurs, and we can manage the exception in this event.Application_End: The Application_End event is raised just before an application domain ends because of any reason, may IIS server restarting or making some changes in an application cycle. Caching:

Page 23: ASP.net Matrial

Caching is a technique where we can store frequently used data, and web pages are stored temporarily on the local hard disk for later retrieval. This technique improves the access time when multiple users access a web site simultaneously, or a single user accesses a web site multiple times. Caching for web applications can occur on the client (browser caching), on a server between the client and the web server, (proxy caching / reverse proxy caching), and on the web server itself (page caching or data caching).Caching is a technique of persisting the data in memory for immediate access..ASP.NET Caching is used to build high-performance, scalable ASP.NET web applications by storing responses in memory.http://asp-net-example.blogspot.in/2009/02/aspnet-caching-example-how-to-use.html..http://support.microsoft.com/kb/308375

What are dependencies in cache and types of dependencies?When you add an item to the cache, you can define dependency relationships that can force that

item to be removed from the cache under specific activities of dependencies. Example if the

cache object is dependent on file and when the file data changes you want the cache object to be

update. Following are the supported dependency:-

• File dependency: – Allows you to invalidate a specific cache item when a diskbased file or files change.

• Time-based expiration: – Allows you to invalidate a specific cache item dependingon predefined time.

• Key dependency:- Allows you to invalidate a specific cache item depending whenanother cached item changes.

• Page Output CachingPage output caching adds the response of page to cache object. Later when

page is requested page is displayed from cache rather than creating the

page object and displaying it. Page output caching is good if the site is

fairly static…

O/p Cahing:Cache the page at specific time.Cache Expiration

Cache expiration strategies can be implemented in either of the following two ways:

         Time Based

         File Based

Page 24: ASP.net Matrial

         Key Based

Time Based Expiration

This is implemented by specifying a specific duration for which the item would remain in the cache. When the time elapses, the item is removed from the cache and subsequent requests to retrieve the item returns a null. Time based expiration strategies can be of the following two types:

         Absolute

         Sliding

Absolute

Cache.Insert("UserInfo", dsUserInfo, null,DateTime.Now.AddMinutes(1), NoSlidingExpiration); 

Sliding

Cache.Insert("UserInfo", dsUserInfo, null,NoAbsoluteExpiration, TimeSpan.FromSeconds(60));

Note that you cannot use both Absolute and Sliding expirations at the same time.

File Based Expiration

This is implemented by using a file as a dependency. Whenever the contents of the dependency file are changed, the cached is invalidated. Please refer to the code below.

CacheDependency cacheDependency = newCacheDependency("userinfo.xml");Cache.Insert("UserInfo", xmldocObject,cacheDependency);

In addition to files, entire folders can be monitored for changes using the CacheDependency class.

Key Based Expiration

The third type of dependency is the key dependency.  With it, a cache entry can be made to depend on another, existing dependency.  When the depended-upon entry changes or expires, the dependent entry will also be expired.  An array of keys can be specified as a single CacheDependency.

string[] keys = new string[] {"key"};CacheDependency cacheDependency = newCacheDependency(null,keys);Cache.Insert("UserInfo", xmldocObject,cacheDependency);

 

Using Callbacks

The delegate CacheItemRemovedCallback event handler is used to respond to the event that is raised when an item is deleted from cache. This handler contains the code to populate / re-populate the cache. Please refer to the code snippet below.

public void onRemoveCallBack(string str, objectobj, CacheItemRemovedReason reason)

Page 25: ASP.net Matrial

{      DataSet dataset = GetUserInfoFromDatabase();      Cache["userInfo"] = dataset; }

1.      First declare a class variable onRemove as shown below.

private static CacheItemRemovedCallback onRemove = null; 

2.      This delegate is invoked as shown below.

onRemove = newCacheItemRemovedCallback(this.onRemoveCallBack);

3.      The following code snippet shows how this handler is specified when items are added to the Cache.

Cache.Insert("userInfo", ds, null, DateTime.Now.AddMinutes(2), NoSlidingExpiration, CacheItemPriority.High,CacheItemPriorityDecay.Slow, onRemove);The Cache Class

The Add/Insert method of the Cache class is used to add/insert an item into the cache. The Remove method removes a specified item from the cache. The Cache class contains the following properties and methods.

Properties

         Count

         Item

Methods

         Add

         Equals

         Get

         GetEnumerator

         GetHashCode

         GetType

         Insert

         Remove (Overloaded)

         ToString

Example:<%@ OutputCache Duration="20" VaryByParam="none"%>

Page 26: ASP.net Matrial

Label1.Text = "Time: " + DateTime.Now.TimeOfDay.ToString();

If we want get the data using specific controls we have to use.<%@ OutputCache Duration="20" VaryByControl="ddlsomecontrols"%>..http://www.codeproject.com/Articles/49704/ASP-NET-Page-Output-Cache

Fragment Caching:

ASP.NET provides a mechanism for caching portions of pages, called page fragment caching. To cache a portion of a page, you must first encapsulate the portion of the page you want to cache into a user control. In the user control source file, add an OutputCache directive specifying the Duration and VaryByParam attributes. When that user control is loaded into a page at runtime, it is cached, and all subsequent pages that reference that same user control will retrieve it from the cache.,\..Fragment caching is useful when you need to cache only a subset of a page. Navigation bars, header, and footers are good candidates for fragment caching. Here we are creating a ASPX page with two usercontrols inside it. We can control the caching of each usercontrols using fragment option as follow..

<%@ Register TagPrefix="uc1" TagName="FragmentCtrl1" Src="FragmentCtrl1.ascx

pageLoad:

Time.Text = "WebFormTime: " + DateTime.Now.TimeOfDay.ToString();

<%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="MyRadioButto

DataCaching:http://www.codeproject.com/Articles/14017/using-cache-to-store-Data-in-datatable-for-custom..real time scenario

How to create data cache? 

Cache["Employee"] = "DataSet Name"

In simple terms data caching is storing data in memory for quick access

http://www.c-sharpcorner.com/uploadfile/annathurai/data-cache-in-Asp-Net/

Data Cache is used to storing frequently used data in the Cache memory. It's much efficient to retrieve data from the data cache instead of database or other sources. We need use

Page 27: ASP.net Matrial

System.Web.Caching namespace. The scope of the data caching is within the application domain unlike "session". Every user can able to access this objects.

Application data caching is a mechanism for storing the Data objects on cache. It has nothing to do with the page caching. ASP.NET allows us to store the object in a Key-Value based cache. We can use this to store the data that need to cached.How to Read data from Data Cache?

Dataset dsEmployee = (Dataset) Cache ["Employee"]

Caching of data can dramatically improve the performance of an application by reducing database contention and round-trips. Simply data caching store the required data in cache so that web server did not send request to DB server every time for each and every request which increase the web site performance. For data caching we need to cached those data which is accessible to all or which is very common data. The data cache is a full-featured cache engine that enables you to store and retrieve data between multiple HTTP requests and multiple sessions within the same application .how we can implement data caching in our web application. There are Three Different way to add data or object into cache. But based upon the situation we have to access it. These methods are Cache[], Cache.add(), cache.insert(). The following table will show you the clear difference of there methods…..

Ex:GridView1.DataSource = (DataTable)Cache["Employee"];       GridView1.DataBind();.

if (Cache["Employee"] == null){            dtEmployee = newDataTable("Employee");dtEmployee.Columns.Add("EmpID", typeof(int));dtEmployee.Columns.Add("EmpName", typeof(string));DataRowrs = dtEmployee.NewRow();rs[0] = 10;rs[1] = "Annathurai";dtEmployee.Rows.Add(rs);

//To assign datatable to cache memory.            Cache["Employee"] = dtEmployee; Cache.Insert("Employee", dtEmployee, null, Cache.NoAbsoluteExpiration, ts); Response.Write("Its processing with Database hit");       }       else       {           //If cache has value, It retrive from cache memory and bind into the gridview           Response.Write("Its processing from cache");       }

Page 28: ASP.net Matrial

/Here we are converting cache into datatable        GridView1.DataSource = (DataTable)Cache["Employee"];       GridView1.DataBind();..

ASP.Net Application Life Cycle:

The application life cycle has the following stages:

User makes a request for accessing application resource, a page. Browser sends this request to the web server.

A unified pipeline receives the first request and the following events take place:

o An object of the ApplicationManager class is created.

o An object of the HostingEnvironment class is created to provide information regarding the resources.

o Top level items in the application are compiled.

Response objects are created .the application objects: HttpContext, HttpRequest and HttpResponse are created and initialized.

An instance of the HttpApplication object is created and assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.

ASP.Net Page Life Cycle:

When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.

The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'.

The page life cycle phases are:

Page 29: ASP.net Matrial

Initialization

Instantiation of the controls on the page

Restoration and maintenance of the state

Execution of the event handler codes

Page rendering

Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.

Following are the different stages of an ASP.Net page:

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.

Page 30: ASP.net Matrial

Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done..

Events:

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

Note

If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before

Page 31: ASP.net Matrial

theInit 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 andInitComplete 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 OnLoadmethod 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 theLoad event of the page.Use the OnLoad event method to set properties in controls and to establish database connections.

Page 32: ASP.net Matrial

Control events

Use these events to handle specific control events, such as a Buttoncontrol's Click event or a TextBoxcontrol's TextChanged event.Note

In a postback request, if the page contains validator controls, check theIsValid property of the Page and of individual validation controls before performing any processing.

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 callsEnsureChildControls for each control and for the page.)The Page object raises the PreRenderevent on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after thePreRender 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.

PreRenderComplete

Raised after each data bound control whose DataSourceID property is

Page 33: ASP.net Matrial

set calls its DataBind method. For more information, see Data Binding Events 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 aRender 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 Rendermethod. For more information, seeDeveloping 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.

Page 34: ASP.net Matrial

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

During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as theResponse.Write method, the page will throw an exception.

..@AutoeventWireup,@page,@assembly:

When AutoEventWireup is true, handlers are automatically bound to events at run time based on their name and signature. For each even.When AutoEventWireup is false, you must explicitly bind event handlers to events.

Directives in ASP.NET control the settings and properties of page and user control compilers. They can be included anywhere on a page, although it is standard to place them at the beginning. Directives are used in both .aspx files (ASP.NET pages) and .ascx files (user control pages). ASP.NET pages actually support eight different directives in Asp.net.

@ Page Page directives are the most commonly used directives, and are used to edit a wide

variety of settings that control how the page parser and page compiler work. @control:  @ Control directive (for a user control). @ Import Imports a namespace into a page or user control explicitly. @ Implements Indicates that a page or user control implements a specified .NET Framework interface

declaratively. @ Register Associates aliases with namespaces and classes, which allow user controls and custom

server controls to be rendered when included in a requested page or user control. @ Assembly Links an assembly to the current page or user control declaratively. @ OutputCache

Page 35: ASP.net Matrial

@ Reference Links a page, user control, or COM control to the current page or user control declaratively.

Authentication AndAutherization:

http://www.codeproject.com/Articles/98950/ASP-NET-authentication-and-authorization..

http://www.c-sharpcorner.com/UploadFile/718fc8/working-with-dataset-and-its-methods-in-ado-net/.Ado.Net:

Connected Disconnected

It is connection oriented. It is dis_connection oriented.

Datareader DataSet

Connected methods gives faster performance Disconnected get low in speed and performance.

connected can hold the data of single table disconnected can hold multiple tables of dataconnected you need to use a read only forward only data reader

disconnected you cannot

Data Reader can't persist the data Data Set can persist the data

It is Read only, we can't update the data. We can update data

Connected Architecture of ADO.NETThe architecture of ADO.net, in which connection must be opened to access the data retrieved from database is called as connected architecture. Connected architecture was built on the classes connection, command, datareader and transaction

Disconnected Architecture in ADO.NET

The architecture of ADO.net in which data retrieved from database can be accessed even when connection to database was closed is called as disconnected architecture. Disconnected architecture of ADO.net was built on classes connection, dataadapter, commandbuilder and dataset and dataview.…..CommandBuilder:

 CommandBuilder helps you to generate update, delete., and insert commands on a single database table for a

data adapter..

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employee ORDER by EmployeeID", conn);

            // Ceate a command builder object

            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

Page 36: ASP.net Matrial

            // Create a data Set object

            DataSet ds = new DataSet("EmployeeSet");            adapter.Fill(ds, "Employees");

            // Create a data table object and add a new row

            DataTable EmployeeTable = ds.Tables["Employees"];            DataRow row = EmployeeTable.NewRow();            row["FirstName"] = "Rodney";            row["LastName"] = "DangerField";            row["Title"] = "Comedian";            EmployeeTable.Rows.Add(row);

            // update data adapter

            adapter.Update(ds, "Emlpoyees");..

Table 5-26. The DataReader properties

PROPERTY DESCRIPTIONDepth Indicates the depth

of nesting for rowFieldCount Returns number of

columns in a rowIsClosed Indicates whether a

data reader is closedItem Gets the value of a

column in native format

RecordsAffected Number of row affected after a transaction

Table 5-27. The DataReader methods

Page 37: ASP.net Matrial

METHOD DESCRIPTIONClose Closes a DataRaeder

object.Read Reads next record in

the data reader.NextResult Advances the data

reader to the next result during batch transactions.

Getxxx There are dozens of Getxxx methods. These methods read a specific data type value from a column. For example. GetChar will return a column value as a character and GetString as a string.

..DataBoundControls in Asp.Net:

• GridView ASP.NET GridView control available in Visual Studio alows data binding and editing without writing a single line of code. • DetailsView The DetailsView control is used to display one or more fields from a single data record. The unadapted version of the DetailsView control renders these fields as rows in an HTML . An adapter can be used to render an unordered list (<ul> and <li> tags) instead.

• FormsView Show how the FormView control can display data for a user to edit, delete and also add to the database.Web.Config:• DataList TheDataList control is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, the DataList control adds a table around the data items by default. The DataList control may be bound to a database table, an XML file, or another list of items. Here we will show how to bind an XML file to a DataList control.• Repeater The Repeater control is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. Here we will show how to bind an XML file to a Repeater control.• ListView The ASP.NET ListView control enables you to bind to data items that are returned from a

Page 38: ASP.net Matrial

data source and display them. You can display data in pages. You can display items individually, or you can group them.The ListView control displays data in a format that you define by using templates and styles.

UserControls in asp.net:

Example:

Custom Control

1. You can create a Custom control when it is going to be used across different applications.2. Custom controls don't a visual interface.3. Custom controls however can be added to your tool box and used in different applications

without re-compiling.4. It's a .dll

User Control

1. If the control you are going to create is only for a particular website then User Control is the best option.

2. User controls have a visual interface.3. User control will not appear in tool box and it will not have design support and loaded at

runtime.4. It's a .ascx

Web custom controls are compiled code, which makes them easier to use but more difficult to create.Once you have

created the control you can add it to the Toolbox and display it in a visual designer with full Properties window support

and all the other design-time features of ASP.NET server controls. In addition you can install a single copy of the Web

custom control in the global assembly cache and share it between applications, which make maintenance easier.

Web user controls are compiled dynamically at run time they cannot be added to the Toolbox and they are represented by

a simple placeholder when added to a page.If you want to share the user control between applications is to put a separate

copy in each application, which takes more maintenance if you make changes to the control…

User Control can access only within the current application,if u want to access the user control to other application,u want

to copy that user control to that application.

Custom control can access from any application becs it is stored in GAC(Global Assembly Cache)…

Ascx.page:

1. <%@ Control Language="C#" ClassName="CalendarUserControl" %>  2.   3. <script runat="server">  

Page 39: ASP.net Matrial

4.     protected void Calendar1_SelectionChanged(object sender, System.EventArgs e) {  5.         Label1.Text = "Your selected Date is: " +  6.             Calendar1.SelectedDate.ToShortDateString();  7.     }  8. </script>  9. <h2>This is user control</h2>  10. <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkGreen"></asp:Label>  11. <br /><br />  12. <asp:Calendar ID="Calendar1" runat="server" BackColor="Beige" OnSelectionChange

d="Calendar1_SelectionChanged">  13. </asp:Calendar> 

After reuse the default.aspx page:

<%@ Register src="CalendarUserControl.ascx" tagname="CalendarUserControl" tagprefix="uc1" %>..

1. <div>  2.         <h1 style="color:Red;">This is page top</h1>  3.         <hr />  4.         <uc1:CalendarUserControl ID="CalendarUserControl1" runat="server" />  5.       6.     </div>  ..

Interviewquestions:

PostBack -> is the data posted to server, that means hitting the server in the name of request to the server for any

response.

IsPostBack -> verifying whether any postback event has been occured or not. It ensures whether the page is posted to

server and back to the client, i.e the page after the server's response or a new page.

ifIsPostBack = True }-> then the page displaying is the page after the server's response. Otherwise, its a new page.

Post back is the process the sending data get back to server for processing.Is post back property checks whether page is being loaded for first time.if it is False :means first time loaded.if it is True: means round trip to server..  postback: the page performs a POST request to itself

            autopostback: a postback is performed automatically, for example when the selected value of a dropdown changes

CrossPagepostback:Response.Write(

((TextBox)this.PreviousPage.FindControl("MyTextBox")).Text)

Page 40: ASP.net Matrial

Gridview Operations threetier:http://code.msdn.microsoft.com/Insert-Update-Delete-rows-b0a2d4e2

Listview using Three tier:http://code.msdn.microsoft.com/Insert-Update-and-Delete-f037854d/view/SourceCode#content...

The ListView is an extremely flexible data-bound control that renders its content based on the templates you define. Unlike the Repeater, the ListView adds higher level features such as selection and editing, which work in the same way as those in the GridView. But unlike the GridView, the ListView doesn’t support a field based model for creating quick and easy grids with a minimum of markup.

Templates control certain aspects of the ListView control's generated HTML. Templates are required with ListView; they are optional with other data controls. These templates provide complete control over the output; that is, all aspects of the ListView's generated markup are controlled via templates.

The following list offers details about the numerous templates available with ListView.

1.      AlternatingItemTemplate: Defines how alternating items are displayed.2.      EditItemTemplate: Defines the presentation for an item when it is edited.3.      EmptyDataTemplate: Specifies the content to display for empty individual items.4.      EmptyItemTemplate: Specifies the content to display for empty group items.5.      GroupSeparatorTemplate: Specifies the content to display between groups.6.      GroupTemplate: Defines the content for groups. This template is a placeholder for the

data displayed for individual group items (when data is grouped).7.      InsertItemTemplate: Defines the presentation for a new item being inserted into the

data set.8.      ItemSeparatorTemplate: Defines the content to display between individual data items.9.      ItemTemplate: Defines the data to display for single items.10.  LayoutTemplate: Defines the main presentation features for the control. This root

template contains placeholders that are replaced by what is defined by ItemTemplate and GroupTemplate.

11.  SelectedItemTemplate: Specifies the content to display when users select items.

In this article we will discuss features in ListView step by step.

         Data Binding         Data Pager         Add, Edit and Delete

In Data Binding we will bind ListView from database. To show data use ItemTemplate and AlternateItemTemplate show alternative row with different styles.

Page 41: ASP.net Matrial

1. Data Binding………….

Authentication and Authorizations in Asp.Net:

Security for Applications:

http://www.codeproject.com/Articles/98950/ASP-NET-authentication-and-authorization

http://www.codeproject.com/Articles/94612/Windows-Authentication

http://www.codeproject.com/Articles/94612/Windows-Authentication.


Recommended