Monday 26 July 2010

Unload Event in ASP.NET Page Life Cycle

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.

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.

protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);

// your code
}


ASP.NET Page Life Cycle Overview

General 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

PreInit

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

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 the Response.Write method, the page will throw an exception.

Tuesday 20 July 2010

ASP.NET 2.0 Wizard Control

One of the useful new controls in ASP.NET 2.0 is the <asp:wizard> control, which allows developers to easily create multi-step UI (with built-in previous/next functionality and state management of values).

There is a nice 14 minute online video now available that walks through how to build an ASP.NET 2.0 application from scratch that provides a customer online signup form system using the <asp:wizard> control, the asp.net validation controls, and the new System.Net.Mail mail library. You can watch it being built from scratch and learn the high-level concepts of how the Wizard control works here (to find other short task-focused videos in the new ASP.NET 2.0 "How Do I" series click here).

Here are a few other articles you can read to learn more about the <asp:wizard> control and how to take advantage of it:

* MSDN Magazine Cutting Edge Article (note: this is a little old -- but provides a good conceptual overview)
* ASP.NET QuickStart Samples for the Wizard Control
* Create a Basic Wizard Control
* Create an Advanced Wizard Control
* Wizard Control MSDN Reference Overview

One nice tip/trick you can use with the Wizard control is to host it within the new <atlas:updatepanel> control -- which turns the wizard into an Ajax based wizard (no full page post-backs required). This is trivial to-do and doesn't require any code changes. This blog post of Scott Gu talks a little about using the <atlas:updatepanel> with the december CTP drop of Atlas, and builds an Ajax task-list in 39 lines of code with it (no javascript required -- it can all be done with C#). You can learn more about the January CTP drop (which has a lot of enhancements and new features for the <atlas:updatepanel> here).

http://weblogs.asp.net/scottgu/archive/2006/02/21/438732.aspx

Wednesday 7 July 2010

Explicit and Implicit Interface Implementation

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

Explicit interface implementation also allows the programmer to inherit two interfaces that share the same member names and give each interface member a separate implementation.


http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx

Generating Forms Authentication Compatible Passwords (SHA1)

Why would we want to create an SHA1 Password Hash?
The answer to this is easy. It is dangerous to store passwords anywhere in plain text!! SHA1 gives a quick and easy way to encode a password into a non-human readable form. This means it is safer to store in a database, and should the database be viewed by anyone who shouldn't know the passwords, it will be much more difficult for them to work out what a user's password is.

When creating a Web Application we can use the HashPasswordForStoringInConfigFile object in the FormsAuthentication namespace to generate our SHA1 password hash.

The following section of code shows an example of this:

Dim encpass As String = _
FormsAuthentication.HashPasswordForStoringInConfigFile(tbxPassword.Text, _
"sha1")
tbxResult.Text = encpass.ToString()

The code takes the text from the "thePassword" textbox control and hashes the contents with the SHA1 algorithm. The result is then in the "theResult" textbox control.

This hashed password can then be placed in your web.config file or in a database and used in your web application for Forms Authentication. In a future tutorial we will show how to go on and use this in an application.


http://www.stardeveloper.com/articles/display.html?article=2003062001&page=1

Cookieless Forms Authentication

ASP.NET 2.0 supports cookieless forms authentication. This feature is controlled by the cookieless attribute of the forms element. This attribute can be set to one of the following four values:

* UseCookies. This value forces the FormsAuthenticationModule class to use cookies for transmitting the authentication ticket.
* UseUri. This value directs the FormsAuthenticationModule class to rewrite the URL for transmitting the authentication ticket.
* UseDeviceProfile. This value directs the FormsAuthenticationModule class to look at the browser capabilities. If the browser supports cookies, then cookies are used; otherwise, the URL is rewritten.
* AutoDetect. This value directs the FormsAuthenticationModule class to detect whether the browser supports cookies through a dynamic detection mechanism. If the detection logic indicates that cookies are not supported, then the URL is rewritten.

If your application is configured to use cookieless forms authentication and the FormsAuthentication.RedirectFromLoginPage method is being used, then the FormsAuthenticationModule class automatically sets the forms authentication ticket in the URL. The following code example shows what a typical URL looks like after it has been rewritten:

http://localhost/CookielessFormsAuthTest/(F(-k9DcsrIY4CAW81Rbju8KRnJ5o_gOQe0I1E_jNJLYm74izyOJK8GWdfoebgePJTEws0Pci7fHgTOUFTJe9jvgA2))/Test.aspx


The section of the URL that is in parentheses contains the data that the cookie would usually contain. This data is removed by ASP.NET during request processing. This step is performed by the ASP.NET ISAPI filter and not in an HttpModule class. If you read the Request.Path property from an .aspx page, you won't see any of the extra information in the URL. If you redirect the request, the URL will be rewritten automatically.

Note It is not possible to secure authentication tickets contained in URLs. When security is paramount, you should use cookies to store authentication tickets.

http://msdn.microsoft.com/en-us/library/ff647070.aspx