Wednesday, 30 November 2011

State Management in ASP.Net

In general, Webapplications are stateless i.e. the objects wont persist its state accross request to the web application. In other words, the State or Cache Management is nothing but the way to storing the data in Client-Side and in Server-Side using pretty small memory to maintain its state. 
There are two major categories of the above :
1.      Server-Side State Management
2.      Client-Side State Management

Server-Side State Management
 
Session State: Its nothing but defined as a period of time shared between the web application and user. Every user has individual session. Items/Objects can be placed into the Session which would only define these objects for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application which can clear it, as well as through the timeout property in the web config file. Usually the timeout is 20 minutes by default.
Session Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.
The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection.
Lets get it cleared from following example:

Session[“firstName”] = “Saurav”   //User’s first name
Session[“lastName”] = “Arora”     //User’s last name
// Clear the session variable
Session[“FirstName”] = null;
//Clear all Session variables
Session.Abandon();  

ASP.NET application object
ASP.NET provides an object called Application object to store data that is accessible to all user requests. The life span of this object is tied to the application and it is re-created every time the application starts. Unlike ASP.NETSession object this object is accessible to all user requests. Since this storage is created and maintained in an application domain space, this should not be used for data storage in a web farm scenario. This option is very useful to store data like the application metadata (CONFIG files data) that can be loaded to the Application object during application start up and can be used during the life of the application without reloading it every time for each user request. But if there is a requirement to invalidate the cached data whenever there is any change to the CONFIG files while the application is running, this option should not be used as it doesn't provide any feature to expire the cached data. So in this case other options like the ASP.NET Cache object should be used, which is explained below.

Types of Cache –Dependencies
When anyone add an item to cache, he/she can define the dependency relationships that can force that item to be removed from the cache under specific activities of dependencies.
For example: If the cache is dependent on file and when the file data changes you want the cache object to be updated.
Following are the difference dependencies:

File Dependency :
Allows invalidating a specific cache item when a disk based file or files change.
object errorData;
 //Load errorData from errors.xml
 CacheDependency fileDependency =
     new CacheDependency(Server.MapPath("errors.xml"));
 Cache.Insert("ERROR_INFO", errorData, fileDependency);

Time based expiration :
Allows to invalidate a specific cache item depending on predefined time.
//Absolute Expiration
Cache.Insert("EMP_NAME", "Shubhabrata", null,
             DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
//Sliding Expiration
Cache.Insert("EMP_NAME", "Shubhabrata", null,
             Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(60));

Key dependency :
Allows to invalidate a specific cache item depending when another cache item changes.
string[] relatedKeys = new string[1];
relatedKeys[0] = "EMP_NUM";
CacheDependency keyDependency = new CacheDependency(null, relatedKeys);
Cache["EMP_NUM"] = 5435;
Cache.Insert("EMP_NAME", "Shubhabrata", keyDependency);
Cache.Insert("EMP_ADDR", "Bhubaneswar", keyDependency);
Cache.Insert("EMP_SAL", "5555USD", keyDependency);

Client-Side State Management

Cookies
Cookie is a very familiar term in web development environment. Cookie is a client-side storage that is sent to the server for each request and also received as response back from the server. Because of its size limitation (4096 bytes) it should be used for storing small amount of data. Expiration policies can be set for cookies to invalidate the items after a certain period of time. The following example shows how Cookie can be used in an ASP.NET application:
if (this.Request.Cookies["NAME"] == null) {
    this.Response.Cookies.Add(new HttpCookie("NAME",
                                       "Shubhabrata Mohanty"));
}
else
{
    this.Response.Write(this.Request.Cookies["NAME"].Value);
}

ViewState
ASP.NET ViewState is a new concept. Here the data related to the pages and controls are stored in ViewState which retains the values across multiple requests to the server. If you remember correctly, in VB-ASP applications we used to store data across multiple requests using hidden fields. ViewState is actually implemented internally as hidden fields in ASP.NET but here the data is hashed to improve security as against hidden fields. To see how ViewState is implemented, you can view the source of the page in which ViewState is used in the Internet browser. ViewState should not be used to store large amounts of data as it is passed to the server for each request
protected void Page_Load(object sender, EventArgs e) {
    if (this.ViewState["NAME"] == null)
    {
        this.ViewState["NAME"] = "Shuby";
    }
        //txtName is a TextBox control
    this.txtName.Text = this.ViewState["NAME"].ToString();
}

Hidden fields
Hidden fields are very popular among VB-ASP web developers. Hidden field is similar to any other control in a page but the visible state of this control is always false. Like ViewState we should not use it for storing large amounts of data. 
Note:Similarly hidden frames can be used to cache data in the client side. But please note that hidden frames are not supported by all Internet browsers.
<!--In ASP.NET-->
<asp:HiddenField ID="myHiddenField" Value="Shubhy"  runat="server" />                                    
<!--In HTML-->
<input id="myHiddenField" type="hidden" value="Shubhy" />

Query Strings
Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue. 
http://www.CodeDigest.com/?authorid=4
Example
string authorid;
authorid=Request.Params[“authorid”];

You can only use HTTP-Get method to post the web page, or you will never get the value from query strings.




Tuesday, 29 November 2011

Page Life Cycle in ASP.NET

In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page.
When a user first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.
The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.
The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page. Now the processRequest() method cycles through the page's life cycle in the order listed below.

(1) PreInit The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.
 
(2)Init This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

(3)InitComplete Raised once all initializations of the page and its controls have been completed. Till now the view state values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback.

(4)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

      (1)Loads ViewState : ViewState data are loaded to controls 
          The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request. 
         (2)Loads Postback data : postback data are now handed to the page controls       During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.


(5)Load The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

(6)Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, for example.These are the events, the code for which is written in your code-behind class(.cs file). 

(7)LoadComplete This event signals the end of Load.

(8)PreRender Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.

(9)SaveStateComplete Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.

(10)Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

(11)UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on- 
     (a)Instances of classes i.e. objects
     (b)Closing opened files
     (c)Closing database connections.

Monday, 28 November 2011

Compilation Process in .Net

Under Microsoft .NET, applications are created using one or more high-level programming languages, such as VB.NET, C#, and COBOL .NET. Each .NET-compliant language goes through an initial compilation step that takes it from source-level code to the lowest common denominator language for .NET, Microsoft Intermediate Language (MSIL). MSIL is itself a full-fledged, object-aware language, and it's possible to build applications using nothing but MSIL. For a whirlwind tour of MSIL, see "Check under the MSIL hood to see how the CLR is running." An application stays in MSIL form until it's executed, at which time it is just-in-time (JIT) compiled into native code. Figure A illustrates this process.
Figure A
.NET's compilation process, from source to native instructions

JIT compilation occurs at the assembly level whenever an assembly is first loaded. (For more on assemblies, see "Introducing the assembly—a cure for 'DLL Hell'?".) When a reference to an object is first encountered, the JITer loads a stub for each method that matches that method's declaration. When a method is later invoked, the IL for it is compiled and the stub is replaced with the address of the method's compiled code. This happens each time a method is invoked for the first time, and the resulting native code is cached so that it can be reused the next time the assembly is loaded during that session. Obviously, this execution system results in more required overhead than that for a traditional compiled language, but not as much as you'd think.

That should clear up one common misconception: that .NET applications are interpreted. Another common misconception is that the JIT compiled code is stored on disk and reused for subsequent executions of the same application. While it's possible to do so, as you'll see shortly, this is not the default arrangement. The IL code for an application is recompiled into native code each time that application is run.

Sunday, 27 November 2011

Common Language Runtime(CLR)


The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET framework which manage the execution of .NET programs.
The Common Language Runtime is the engine that compiles the source code in to an intermediate language. This intermediate language is called the Microsoft Intermediate Language.
During the execution of the program this MSIL is converted to the native code or the machine code. This conversion is possible through the Just-In-Time compiler. During compilation the end result is a Portable Executable file (PE).
This portable executable file contains the MSIL and additional information called the metadata. This metadata describes the assembly that is created. Class names, methods, signature and other dependency information are available in the metadata. Since the CLR compiles the source code to an intermediate language, it is possible to write the code in any language of your choice. This is a major advantage of using the .Net framework.
The other advantage is that the programmers need not worry about managing the memory themselves in the code. Instead the CLR will take care of that through a process called Garbage collection. This frees the programmer to concentrate on the logic of the application instead of worrying about memory handling.

Saturday, 26 November 2011

Overview of .NET

ASP.NET is the next version of ASP,is a programming framework used to create enterprise-class Web Applications.These applications are accessible on a global basis leading to efficient information management.

Since 1995, Microsoft has been constantly working to shift it's focus from Windows-based platforms to the Internet. As a result, Microsoft introduced ASP (Active Server Pages) in November 1996. ASP offered the efficiency of ISA PI applications along with a new level of simplicity that made it easy to understand and use. However, ASP script was an interpreted script and consisted unstructured code and was difficult to debug and maintain. As the web consists of many different technologies, software integration for Web development was complicated and required to understand many different technologies. Also, as applications grew bigger in size and became more complex, the number of lines of source code in ASP applications increased dramatically and was hard to maintain. Therefore, an architecture was needed that would allow development of Web applications in a structured and consistent way. 
The .NET Framework was introduced with a vision to create globally distributed software with Internet functionality and interoperability. The .NET Framework consists of many class libraries, includes multiple language support and
a common execution platform. It's a very flexible foundation on which many different types of top class applications can be developed that do different things. Developing Internet applications with the .NET Framework is very easy.
 ASP.NET is built into this framework, we can create ASP.NET applications using any of the built-in languages.
Unlike ASP, ASP.NET uses the Common Language Run time (CLR) provided by the .NET Framework. This CLR manages execution of the code we write. ASP.NET code is a compiled CLR code instead of  interpreted code (ASP).CLR also allows objects written in different languages to interact with each other. The CLR makes development of Web applications simple.