Wednesday, April 28, 2010

ASP.NET Page Life Cycle Stages:

Page request : The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start : In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

Initialization : During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load : During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling : If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Rendering : Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

Unload : The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

Life-Cycle Events
Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.

The page life-cycle events that you will use most frequently are given below.
PreInit :Raised after the start stage is complete and before the initialization stage begins.

Use this event for the following:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.

  • Create or re-create dynamic controls.

  • Set a master page dynamically.

  • Set the Theme property dynamically.

  • Read or set profile property values.

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 the Init event of the page.

Use this event to read or initialize control properties.

InitComplete : Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.

Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad : Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load :The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.

Use the OnLoad event method to set properties in controls and to establish database connections.

Control events : Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

In a postback request, if the page contains validator controls, check the IsValid 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 calls EnsureChildControls for each control and for the page.)

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete :

Raised after each data bound control whose DataSourceID property is 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 a Render method that writes out the control's markup to send to the browser.

If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Unload :

Raised for each control and then for the page.

In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

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


Tuesday, April 27, 2010

The .NET Framework

The .NET Framework is a common environment for building, deploying, and running Web Services and Web Applications.


NET framework 2.0:

It brings a lot of evolution in class of the framework and refactor control including the support of:
Generics, Anonymous methods, Partial class, Nullable type..
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework
New personalization features for ASP.NET, such as support for themes, skins and webparts.

.NET framework 3.0:

Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which will make use of 3D computer graphics hardware and Direct3D technologies.
• Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
• Windows Workflow Foundation (WWF) allows for building of task automation and integrated transactions using workflows.
• Windows CardSpace (WCS), formerly code-named InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.
Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website

.NET framework 3.5:
It implement Linq evolution in language. So we have the folowing evolution in class:

Linq for SQL, XML, Dataset, Object Addin system, p2p base class, Active directory,
ASP.NET Ajax, Anonymous types with static type inference, Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.


Session and Cookie

If you set the variable to "cookies", then your users will not have to log in each time they enter your community.

The cookie will stay in place within the user’s browser until it is deleted by the user.

But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.

If you set the variable to "sessions", then user activity will be tracked using browser sessions, and your users will have to log in each time they re-open their browser. Additionally, if you are using the "sessions" variable, you need to secure the "sessions" directory, either by placing it above the web root or by requesting that your web host make it a non-browsable directory.

The Key difference would be cookies are stored in your hard disk whereas a session aren't stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.

The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not. This difference determines what each is best used for.

A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie. The trouble is that a user can block cookies or delete them at any time. If, for example, your website's shopping cart utilized cookies, and a person had their browser set to block them, then they could not shop at your website.

Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit.

You can of course get the best of both worlds! Once you know what each does, you can use a combination of cookies and sessions to make your site work exactly the way you want it to.

A session is a store of data on the server containing state information on a user. A particular sessions is identified by its session id, ideally a large (i.e. unguessable) random number. For example, the session could hold a user's shopping cart.


A cookie is also a store. To create a cookie, the server sends a HTTP header to the client (i.e. the web browser). If the client supports and accepts the cookie, the cookie will be sent back to the server along with every request made to the server.

Cookies are often used to store a session id, binding the session to the user.

No doubt you found the term ,,cookie'' appear frequently when ,,sessions'' are being discussed.
A cookie is a bit of information which is sent to your browser and stored there. The browser will send this information back to the server every time you send a request. (to the server that set the cookie)
This behavior can be used to identify a session if sessions take more than one (server-(client)-server) transactions.


Hmmm, analogy?
Imagine the web application as a fairground (carnival?). You pay for a ticket when you enter (start a session). The ticket now is your cookie and every ride (transaction) you want to go on you wave your ticket (cookie) and get on it. Without a cookie you would have to buy a ticket for every single ride.

Remember, HTTP is a stateless protocol. Without adding any extra magic, if a user visits your site twice in a row, as far as the web server is concerned, those are two totally separate visits having nothing in common with eachother (save for coming from the same IP address).

If you want your web server to be able to remember users between pages they visit, you need some way to create a "session" -- some way to save information about the user so you can recognize them the next time they request a page.

The most common way to do this is by using cookies.

So, sessions are what you want, and cookies are most often how you get them.

Cookies persist on your local computer, they are small text files that are stored there by websites and web applications that contain some basic information about you as a user.

Sessions are application specific and persist only as long as you are actively engaged with a particular web site. For instance if you leave Amazon.com open do some shopping, then close the web browser before making any purchases, your session has ended, however the cookie that identifies your username still exists on your local computer.

1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects.

ASP.NET Session State

ASP.NET session state solves all of the above problems associated with classic ASP session state:

· Process independent. ASP.NET session state is able to run in a separate process from the ASP.NET host process. If session state is in a separate process, the ASP.NET process can come and go while the session state process remains available. Of course, you can still use session state in process similar to classic ASP, too.

· Support for server farm configurations. By moving to an out-of-process model, ASP.NET also solves the server farm problem. The new out-of-process model allows all servers in the farm to share a session state process. You can implement this by changing the ASP.NET configuration to point to a common server.

· Cookie independent. Although solutions to the problem of cookieless state management do exist for classic ASP, they're not trivial to implement. ASP.NET, on the other hand, reduces the complexities of cookieless session state to a simple configuration setting.

Session configuration

Below is a sample config.web file used to configure the session state settings for an ASP.NET application:

<>

<>

mode="inproc"

cookieless="false"

timeout="20"

sqlconnectionstring="data source=127.0.0.1;user id=;password="

server="127.0.0.1"

port="42424"

/>

The settings above are used to configure ASP.NET session state. Let's look at each in more detail and cover the various uses afterward.

· Mode. The mode setting supports three options: inproc, sqlserver, and stateserver. As stated earlier, ASP.NET supports two modes: in process and out of process. There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We'll discuss implementing these options shortly.

Cookieless. The cookieless option for ASP.NET is configured with this simple Boolean setting.

Timeout. This option controls the length of time a session is considered valid. The session timeout is a sliding value; on each request the timeout period is set to the current time plus the timeout value

Sqlconnectionstring. The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver.

Server. In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState.

Port. The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver.


There are four general configuration settings we can look at in more detail: in-process mode, out-of-process mode, SQL Server mode, and Cookieless.

In-process Mode

In-process mode simply means using ASP.NET session state in a similar manner to classic ASP session state. That is, session state is managed in process and if the process is re-cycled, state is lost. Given the new settings that ASP.NET provides, you might wonder why you would ever use this mode. The reasoning is quite simple: performance. The performance of session state, e.g. the time it takes to read from and write to the session state dictionary, will be much faster when the memory read to and from is in process, as cross-process calls add overhead when data is marshaled back and forth or possibly read from SQL Server.

In-process mode is the default setting for ASP.NET. When this setting is used, the only other session config.web settings used are cookieless and timeout.

If we call SessionState.aspx, set a session state value, and stop and start the ASP.NET process (iisreset), the value set before the process was cycled will be lost.


Out-of-process Mode

Included with the .NET SDK is a Windows® NT service: ASPState. This Windows service is what ASP.NET uses for out-of-process session state management. To use this state manager, you first need to start the service. To start the service, open a command prompt and type:

To do this we need to configure config.web:

                   configuration
                       sessionstate 
                           mode="stateserver"
                           cookieless="false" 
                           timeout="20" 
                           sqlconnectionstring="data source=127.0.0.1;user id=;password="
                           server="127.0.0.1" 
                           port="42424" 
                       /
                     /configuration·            
We changed only from inproc mode to stateserver mode.
This setting tells ASP.NET to look for the ASP state service on the server specified
in the
server and port settings—in this case, the local server.

We can now call SessionState.aspx, set a session state value, stop and start the IIS process (iisreset), and continue to have access to the values for our current state.


SQL Server Mode

The SQL Server mode option is similar to that of the Windows NT Service, except that the information persists to SQL Server rather than being stored in memory.

To use SQL Server as our session state store, we first must create the necessary tables and stored procedures that ASP.NET will look for on the identified SQL Server. The .NET SDK provides us with a SQL script (state.sql) to do just that.

state.sql

The state.sql file contains the SQL commands used to create the ASPState database. This script creates two tables and several stored procedures. ASP.NET uses both the tables and the procedures to store data in SQL Server. I would recommend reading through state.sql to learn more about what it is doing.

The state.sql file can be found in [system drive]\winnt\Microsoft.NET\Framework\[version]\


Applying the state.sql script

To apply the state.sql script, use the command line tool SQL Server provides: osql.exe. Using an sa equivalent SQL user, the syntax below is used:

Cookieless State

The last new feature that we can configure for ASP.NET session state is cookieless session state. Essentially this feature allows sites whose clients choose not to use cookies to take advantage of ASP.NET session state.

This is done by modifying the URL with an ID that uniquely identifies the session:

http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx

ASP.NET will modify relative links found within the page and embed this ID. Thus, as long as the user follows the path of links the site provides, session state can be maintained. However, if the end user re-writes the URL, the session state instance will most likely be lost.

The IIS 4.0 Resource Kit provided a similar feature. It was implemented as an ISAPI filter that could modify the incoming and outgoing byte stream to write and read the necessary information. The difference between this and the ASP.NET feature is the effort required to use the feature. In ASP.NET, it's simply a matter of flipping a Boolean value in the config.web file:

configuration
   sessionstate 
      mode="stateserver"
      cookieless="true" 
      timeout="20" 
      sqlconnectionstring="data source=127.0.0.1;user id=;password="
      server="127.0.0.1" 
      port="42424" 
  /
/configuration

Once cookieless is set to true, ASP.NET will do the work necessary to enable cookieless session state. Also note that all modes are supported for cookieless sessions.

Performance and Reliability Considerations

It's worth mentioning, briefly, some of the performance and reliability issues you should consider when using ASP.NET session state modes.

In process. In process will perform best because the session state memory is kept within the ASP.NET process. For Web applications hosted on a single server, applications in which the user is guaranteed to be re-directed to the correct server, or when session state data is not critical (in the sense that it can be re-constructed or re-populated), this is the mode to choose.

Out of process. This mode is best used when performance is important but you can't guarantee which server a user will request an application from. With out-of-process mode, you get the performance of reading from memory and the reliability of a separate process that manages the state for all servers.

SQL Server. This mode is best used when the reliability of the data is fundamental to the stability of the application, as the database can be clustered for failure scenarios. The performance isn't as fast as out of process, but the tradeoff is the higher level of reliability.


An overview of Asp.net Cookies

When working with a web application many a times we want to store the client specific data on the client side only. This helps in showing personalized data for the client. The session maintained by default is also done with the help of the session cookie only.

In a layman developer word a cookie is a small amount of data that is passed between the client and the server in the request and response. The data in the cookie can be read in interpreted by the server and is sent to the server whenever the user visits the same site.

But remember maintenance of cookie also depends on the user. Many user can turn there cookie off or the users can delete the cookies in there cookies. Moreover client can read the information kept in the cookie. That is why cookie cannot be used to store sensitive data.

Remember the cookie is set for a website and not individual pages of the site. Hence the cookie is sent to and from the browser on each and every request to the server. So we should also be very careful on how much data needs to be stored in a cookie. If the amount of data stored in a cookie is vary large than it can slow your site as the amount of data passed to and from is very high.

There are also some limitations in the cookies. Cookies of the maximum size 4096 bytes are supported by most of the browser. The limitation is not only on the bytes but also the number of cookies. One website can keep only up to a maximum of 20 cookies. If we try to store more number of cookies then the earlier cookies will be deleted by default. Many browsers have also kept a limitation on absolute number of the cookies. Most browser keeps only a maximum of 300 cookies from all the site combined.

One more very Important issue with cookie is the fact that it is entirely dependent on the browser. User may have turned off receiving any cookie from any site. No error is raised if the cookie is not written in the browser. Also the fact that the browser never sends information about its current cookie setting to the server and the server has no want to find if the cookie has been written properly or not

In Asp.net the cookie property does not indicate on weather the cookies are enabled in the browser or not (As discussed above there is no ways for the server to understand if the browser will accept cookies or not). It only indicates only the fact that the current browser support cookies or not.

A few interesting things about session in Asp.Net

If we have the session state enabled and we do not store anything in the session then the session Id will change every time a new request is made. This also means that a new session is created every time. But the sate is never saved as there is nothing to save. Note the session_Start event will not fire for every request. The session_start event will only fire once.

Another interesting stuff about session Id is that it does not changes after we have called the Session.Abondon() method or when the session times out. Even though Session State expires but the session ID remains same. The session Id will last as long as the browser session does.

Session Class has two methods. Session.Abondon() and Session.Clear(). Both the methods are used to clear the data in the session. But there is one difference between them. If we use Session.Abondon() then Session_end event will be fired and session_start event will be fired on the next request. The same is not true for session.Clear() method.



Request Validation - Preventing Script Attacks


This paper describes the request validation feature of ASP.NET where, by default, the application is prevented from processing unencoded HTML content submitted to the server. This request validation feature can be disabled when the application has been designed to safely process HTML data.

Why this feature is useful

Many sites are not aware that they are open to simple script injection attacks. Whether the purpose of these attacks is to deface the site by displaying HTML, or to potentially execute client script to redirect the user to a hacker’s site, script injection attacks are a problem that Web developers must contend with.

Script injection attacks are a concern of all web developers, whether they are using ASP.NET, ASP, or other web development technologies.

The ASP.NET request validation feature proactively prevents these attacks by not allowing unencoded HTML content to be processed by the server unless the developer decides to allow that content.

Disabling request validation on a page

To disable request validation on a page you must set the validateRequest attribute of the Page directive to false:

<%@ Page validateRequest="false" %>

Disabling request validation for your application

To disable request validation for your application, you must modify or create a Web.config file for your application and set the validateRequest attribute of the section to false:

Caution: When request validation is disabled, content can be submitted to your application; it is the responsibility of the application developer to ensure that content is properly encoded or processed.

How to HTML encode content

If you have disabled request validation, it is good practice to HTML-encode content that will be stored for future use. HTML encoding will automatically replace any ‘<’ or ‘>’ (together with several other symbols) with their corresponding HTML encoded representation. For example, ‘<’ is replaced by ‘<’ and ‘>’ is replaced by ‘>’. Browsers use these special codes to display the ‘<’ or ‘>’ in the browser.

Content can be easily HTML-encoded on the server using the Server.HtmlEncode(string) API. Content can also be easily HTML-decoded, that is, reverted back to standard HTML using the Server.HtmlDecode(string) method.