Saturday 31 August 2013

ASP.net Statemanagement.?

 

Q) Why State management…?

A) Web is stateless because of HTTP.

Q) What is stateless environment..?

A) In stateless environment Application & client will not maintain any status of there process. Every request of client is identified as a new request. Application that we develop required lot of state full behavior. So, we have to implement state management options provided by Asp.net making our Application state full..


ASP.net state management options:


                 ASP.net provides almost all state management options in a simplified method. Starting from Control level till Application level it provides all state support. As a web developer it is very important to understand the state requirement properly and apply the available options. To start with state management first we have to manage controls and objects ( variables ) with in the date to retain their values. ASP.net provides a logic or concept called " VIEWSTATE" for providing controls and variables state.

Controls level:

For controls by default ASP.net provides state using EnableViewState & ViewStateMode properties we can control the statemanagement options.

Variables level:

For variables we have to explicitly maintain State using ViewStateObject provided by ASP.net.

Q) How ASP.net maintains state for it's Controls..? (or) How ViewState for controls work…?


A)
  •  Client makes a request for page
  •  Server process the page and concatenates all the result into a string.
  •  This string is converted into base64 encoding format. Which is not encrypted and secured format.
  •  This data is now stored In Hidden Field. Which is created by ASP.net implicitly.
  •  Now, the page is returned to client along with user created control and also Hidden Fields.
  •  Now client modify & re-submit the page to server.
  •  Server first off all now reads the hidden fields data. So, that it retains its previously given result. Then start processing the page where old result and new values.
  •  It repeats this cycle for every client as long as client is working with current page.
  •  This result in statefull behavior of page related to controls.
Ex:

1) In a new form drag & drop a textbox , HTML Textbox, label , Button controls.
2) And in code behind write the below code.
3) Declare a global variable
4) Write a below code on button click event.


int a; 
protected void btn_Click(object sender,EventArgs e)
{
    a++;
    lbl.Text=a.ToString();
}
 
5) Then see the output.


VIEWSTATE Object:

1) To maintain state for our variables & objects defined in page code window we have a viewstate property of a page. This property is a reference to a class called StateBag.

2) This class is responsible for maintaining viewstate concept. So, when we use viewstate object then our data will also be stored as part of ASP.net " StateBag".

3) Viewstate object can store any type of data, because StateBag class is of Type Object.

4) The only condition for viewstate Data is data should be in Serializable format. Because server has to Serialize & DeSerialize data between request & response.

5) By default viewstate data is not secure, but to make it secure we have a property called EnableViewStateMac is to be true. Attribute as a part of <%page directive%>.

Ex:
EnableViewStateMac="true/false"

6) When secure more ustomize in encryption can be perform using MachineKey in web.config. We can also perform these settings from IIS.

7) With all about consideration viewstate can be use effectively for statemanagement as well as performance.


Ex:

1) Declare a statebag class, under satebag class write below lines of code.

Page.ViewState["a"]=10;

2) Create a new page and declare label and button control.
3) Write a below lines of code in code behind.
EX:

Page Load event:

if(!IsPostBack)
{
   ViewState["a"]=0;
}
 
Button Click Event:

protected void btn_click(object sender,EventArgs e)
{
    ViewState["a"]= Convert.ToInt32(ViewState["a"])+1;
    Label1.Text=ViewState["a"].ToString();
}


Q) What type of Data store in ViewState…?

A) 
  • Primitive ---- int,bool……
  • Complex ---- DataSet,List<> …

EX:
ViewState["a"]=ds;
ViewState["a"]=List<>;

ViewState --> StateBag --> Object --> any value.

Store any type of data but serialization.

Q) What is Serialization…?

A) The process of converting in- memory form of data into byte format is called Serialization.

Q) Why Serialization..?

A)
  •  To transfer Data over network.
  •  To make object persist.

Note: By default DataSet is serializable object.

Ex:
Normal class:

class Employee
{
}
 
Serializable class:

[Serilizable]class Employee
{
}


Note: more complex type in ViewState will reduce the performance of Application. Because server has to perform more Serialization & DeSerialization process.


Multiple Page State:


              Using ViewState and some other concepts like QueryString,Server.Transfer we get state in a single page (or) state in 2 pages. If we want to maintain state for multiple pages of the website we have to use other concepts provided by ASP.net and also by HTTP.
 
HTTP provides a concept called COOKIES which are supported by all web development coding, using COOKIES we maintain state for small amount of information.

HTTP Cookies:


                A Cookie is _name, value pair just like a variable but which travel automatically between every request and response. Cookies are maintained by browser and we have to understand how they are maintained and consume them in our Application.

                COOKIES are maintained by Browser a standard limitations are imposed by W3 and Browser. Every Cookie is created by Browser based on the Domain or based on the specific path given by Cookie. 20 COOKIEs per domain are allowed, and upto 4KB of data is restricted. These are W3 standards and Browsers like IE7 and above have higher limits than these.

                COOKIES can store only simple form of data like strings. A complex type cann't be directly stored in a Cookie.

                Browser can allow (or) deny cookies for security, personalization and other reasons. In IE "@" we can configure this restriction in security & privacy options.

How to create COOKIE in ASP.net….?

System.web.HTTPCookie is the class using which we can create, cookie in ASP.net classical method or another method of creating cookie is using.
Ex: Response.Cookies[""].Value="10";

Prefered is using HTTPCookie class because it is type safe method.


Ex:
Change.aspx:

1) In a form drag & drop a ListBox and Button controls.
2) In ListBox add a Country names in static manner.
3) On Button click event write a below code.
        protected void btn_click(object sender,EventArgs e)
        {
            HTTPCookie obj=new HTTPCookie("Ckctry");
            Obj.Value=ListBox1.SelectedValue;
            Response.Cookies.Add(obj);
            Response.Redirect("Default.aspx");
        }


Default.aspx:

1) In a form drag & drop label and LinkButton controls.
2) On load event write a below lines of code.

        protected void Page_Load(object sender,EventArgs e)
        {
           if(Request.Cookies["Ckctry"]!=null)
          Label1.Text=Request.Cookies["Ckctry"].Value;
           else
          Label1.Text="INDIA";
        }


3) On button click event write the below lines of code.
        protected void lnkbtn_Click(object sender,EventArgs e)
        {
         Response.Redirect("Change.aspx");
        }


How to search COOKIE in system..?

Goto Browser --> Tools --> internet options --> settings --> View files


MultiValued COOKIEs:

                   A multivalued cookie means like an array of COOKIE where we can store multiple values in a single Cookie. The advantage of multi valued cookie is we can create more values in the form of cookie and also save space in saving disk storage of 4 KB. To create multi valued cookie ASP.net provides values collections.

How to create multiple cookies..?

   HTTPCookie obj=new HTTPCookie("UserDetails");
   Obj.Values["name"]="naveen";
   Obj.Values["mail"]="mailid";
   Obj.Values["num"]="1234";

How to Read multiple Cookies….?


Request.Cookies["UserDetails"]["name"];
           (or)HTTPCookie ck=Request.Cookies["UserDetails"];


Limitations of COOKIEs…?

1) Size limitation ( 4 kb)
2) Type of data limitations ( string)
3) No.of cookies ( 20 cookies / domain)
4) Not secured
  •  Client side - dependent on Browser
  •  Travel in plain Textual format. (HTTP Headers)
  •  Remote site – Access client Resources.

How to make COOKIES secured….?


By default cookies are not secured to make it secure we have to follow 2 things.

1) Encrypt values using some encryption algorithms supported by .net (or) which are provided by third party for .net( RS Algorithem), and store them as part of cookie.

2) Use secure property of cookie and communicate using HTTPS. For this server should be enabled (or) installed with SSL certificates. HTTPS communication mode means entire page data will be encrypted and used in Request / Response.

Note:

Browser --> tools --> Advanced --> Browser --> Use SSL3.0

For multiple page state only but with all functionality which is missing in cookies and also with more required features we have to use server side state management options.

Ex: ASP.net, DataBase, Services, Cloud.

ASP.net options:

1) Application
2) Sessions
3) Cache

  • Server side statemanagement will have load on server because we will use server for processing our data. Advantage of server side state management is we get security with unlimited storage options.
  • ASP.net provides Applications & sessions objects has key objects for storing data. Apart from state usage these objects also represents the process of ASP.net and IIS.
  • Application object is used to represent the entire ASP.net application process memory and we can use it for storing Application wide accessible data.
  • Session object represents the process which is created by ASP.net exclusively for particular user. We can use it to store users specific information. Both these process are automatically started and stop. They are managed by server and it is important to consume them properly by a developer.

Application/ session – start up / shut down:


               Because Application / session represents ASP.net process their Startup & ending is important to understand as well as to perform some Applications tasks.

               An ASP.net Application is automatically started by IIS. When first user makes a request for resources. Application shutdown will happen when all the users leave the Application & Application idle time out expire.

               Session is started Automatically by ASP.net for every new user. Every session is provided with session Id which is internally a COOKIE created by ASP.net. Session Id will travel between every request & response. A session is enabled by ASP.net based on idle timeout. By default session idle timeout is 20min. which means if user doesn't request for server for 20min, then server will destroy the session. we can change this time in web.config as well as programmatically using session object.

Note: from IIS 6.0 every ASP.net Application is created in another process called Application pool. Which is collection of Applications. By maintaining Application with Application pool concept we get lot of benefits like scallable, recoverable and maintainability. We have to manage Application pool at IIS level not in ASP.net project(or) VS.net.

When Application starts…..?

Application started automatically when first user make a request

When Session starts….?

When new user make a request session will starts.

When Pool starts…?

When IIS will starts pool started.

When pool ends…?

When IIS will end pool ended.

When Session ends….?

Idel time 20 mins session will end.

When Application ends…?

All sessions are ended then Application end.


Consuming Application / Session objects of ASP.net….:

               As a developer we can consume both these objects in the form of events and variables. Events for interpreting our project related tasks with process start up & shutdown like when Application starts go to DataBase and get the required values. To do this task we require Application start event so that we can write retrieval code another use is for state management we can create Application & session Data which provide global and individual access for all pages of site. Any type of data with no conditions can be stored as part of Application and session object.


EX:

  1.  Create a page user.aspx
  2.  Drag & Drop a label,textbox,button controls and the name of the label is "UserName" and Button name is "Submit".
  3. Write a below lines of code on button click event.

        protected void btnSubmit_Click (object sender,EventArgs e)
        {
             Session["User"]=txtUser.Text;
             Response.Redirect("online.aspx");
        }
 
  1.  Create another page online.aspx.
  2.  Drag & Drop a label control.
  3.  Wrote a below lines of code on load event of the page.

      protected void Page_Load(object sender,EventArgs e)      {
          if(Session["User"]!=null)
             lbl.Text="Hi ,"+Session["User"].ToString();
          else
             lbl.Text="Guest";
      }


Application / Session Events:


              Application / session events are return in a separate file or special file called global.asax . this file is called as Active Server Application file. Because for every request first this file is executed and then the requested file.

              A Project can have only one global.asax file and it should be placed in Root folder of our Application. By default Global.asax might not be present as part of some project templates. In such cases we have to add explicitly using AddNewItem option. Some events are already provided as empty procedure and we can additionally add other events. Some concepts like MVC, dynamic data are built on depending global.asax. In those projects global.asax file is automatically added. This file is configure by itself to reject any direct request which means user can't directly request global.asax file.


EX:

1) Open your global.asax file and write the following code in the specified location itself.
2) On your Application_Start of your global.asax wrtie below lines of code.

Application["TotalUsers"]=0;
Application["OnlineUsers"]=0;

3) On your Session_starts of your global.asax write below lines of code.

Application["TotalUsers"]=Convert.ToInt32(Application["TotalUsers"])+1;
Application["OnlineUsers"]=Convert.ToInt32(Application["OnlineUsers"])+1;


4) On your Session_End of your global.asax write a belowlines of code.

Application["OnlineUsers"]=Convert.ToInt32(Application["OnlineUsers"])-1;


5) Create a new page Status.aspx, drag & drop 2 label and button controls.

6) On load event of status page write a below lines of code.

protected void Page_Load(object sender,EventArgs e){
   Session.TimeOut=1; // programtically mentioned session timeout.
}


7) On button click event of status page write a below lines of code.


protected void btn_click(object sender,EventArgs e)
{
   Label1.Text="Total Users: "+Application["TotlaUsers"].ToString();
   Label2.Text="Online Users:"+Application["OnlineUsers"].ToString();
}


ASP.net Caching:


                Caching is used to improve performance of Application like consistency & looking. We can virtually provide results to user and run the Application more faster. Cache means programmed memory Area.

ASP.net supports caching in different concepts but the important areas. Where user has to involve and produce results are 3 types.
  1. Page output caching
  2. Data Caching
  3. Fragment Caching
All these caching methods objective is same but the only diff is what they cache.

1) In page output caching entire processed page request is cache. So , that for every request we provide output to uses from cacheinstead of performing process it.

2) It is also important to understand ASP.net page life cycle with caching & without caching . User has to explicitly add cahcing support in order to cache the page. Different directives are provided to implement page output cache.

Page Output Caching:


Design the page with all content regularly and write code according to requirement. Go to directives section and add

<%@OutPutCache Duration="n sec" VaryByParam="none/*/param"%>
to the page.
  • Duration specifies the amount of time we want to Cache the page OutPut Results.
  • VaryByParam is used to specify parameter based Caching when not required we specify none.

EX:

1) In a new page drag & drop label, textbox, button controls
2) On button click event write below lines of code.
 protected void btn_Click(object sender,EventArgs e){
   label1.Text=DateTime.Now.ToLongtimeString();
}

3) Go to directives section and add

< %@ OutPutCache Duration="60" VaryByParam="none"%>.


If we specify any parameter for VaryByParam attribute then ASP.net store different cache results for different values. But the load to maintain values will also increase. Parameter can be any control or QueryString value.

DataCaching:


                 In Data Caching we will Cache only the Data which we process with ours statement. It can be a simple variable or it can be a complex type. Cache object of ASP.net is used to create DataCaching this object is provided to overcome the drawbacks of Application object. Like consistency and looking and some programmatic issues. Apart from this Cache obj has exclusive advantages like Time Based Expiry, Dependence Base Expiry, Managed By Runtime.

EX:

1) In a new form drag & drop button , link button name as Refresh and GridView controls.

2) On your button click event write the below lines of code.

DataSet ds; protected void btn_click (object sender,EventArgs e){
   if(Cache["ds"]==null)
   {
       ds=new DataSet();
       ds=//Bind Data;
       Cache["ds"]=ds;
   }  
   else
   {
       ds=(DataSet)Cache["ds"];
   }
   Gv.DataSource=ds;
   Gv.DataBind();
}

3) On your link button click event write below lines of code.

protected void lnkbtn_Clck(object sender,EventArgs e)
{
    ds=new DataSet();
    ds=//Bind Data;
    Cache["ds"]=ds;
    Gv.DataSource=ds;
    Gv.DataBind();
}
              

The reason to provide Refresh button to our page is to make or generate consistence output. Without refresh button if we want to manage consistency logically. Then we can create admin page in order to update the Cache Data apart from doing logically we can also use TimeBased or DependencyBased features to provide consistency result.


The timebased Expire in Data Caching:

When we cache data by default it will be available as long as our Application is running apart from logical methods another updating methods that we can use are time based & dependency based expiry.

Time Based Expire:

In time based expire we will cache data and provide time for expire. So that we can reload over data from original datasource.
Cache object has insert method for creating time waste and dependence base expire object.

Ex:
if(Cache["ds"]==null){
   ds=//Bind Data;
   //Time Based Expire
   Cache.insert("ds",ds,null,DateTime.Now.AddMinutes(1),TimeSpan.Zero);
}
else
{
   ds=(DataSet)Cache["ds"];
}
Gv.DataSource=ds;
Gv.DataBind();


Note: After 1 min data will be loss. Why because here we add minutes 1.

Dependency Based Expiry:

To create dependency base expiry we use some insert method but with cache dependence class which will perform dependence based expiry. Some time we can't have logical update to our Cache Data and also time base expiry may not be better solution. In such cases we will go for dependency based Expire.

Note: We do either time based (or) dependency based not both at a time

Cache.Insert("ds",ds,new System.Web.Caching.CacheDependency(MapPath(.xml)));


Fragment Caching:


In this method we will Cache some part of our webpage unlike page output caching where entire data is Cache. Fragment caching is implemented with a concept but not with any new command or directive. Fragment caching is very important as we use web user control concept in it.

In ASP.net user defined control is created in 2 ways

  •  Using web User Control
  •  Using Custom control.

For any project user defined controls are required and it is very important to create new property and consume it with web user control we can create user defined controls with in the project and consumed it in the same project.


Web User Control:


• Add a new item --> web user control

A file with extension .ascx( Active Server control).
This file is created with< %@Control.....%>
Directive instead of <%@Page....%>
No default content like HTML, head are present in this file.
• Add <%@ OutPut Cache directive to the control.
• Go to Page and register to the control as it is compulsory to consuming a control.


Custom Control:

               with custom control also we can create ASP.net user defined control. Most of the standard controls are like custom controls. Unlike web user control. A custom control is prepared as .net library assembly . i.e. .dll. a custom control is created using the base control called web control. Which doesn't provide any functionality for a control. All content should be created and managed by developer only VS.net provides a separate project template for creating a custom control. We can use that and build a .net dll containing ASP.net control.

The following steps are followed fro developing custom control.

• Start file --> new project --> web --> ASP.net server control.
• A .cs file is created where a clas will be extending "web Control" class. Which is base class for all controls. Sample property & a method for displaying the control initial or processed output is also provided.
• User has to add all control functionality here i.e. in a class required for preparing a best control.
• We can add more controls to our project using add new item and ASP.net server control template. Every control is designed with same component building style.
• After preparing all these controls we have to just build our project and the result will be a .dll file containing all these controls.


Consuming the .dll file:


• Start a web site and create a tab in toolbox. So , that controls are not mixed up with other categories.
• Right click on the created tab and select choose items which will result in displaying of window showing all controls components that we can add / remove to our project.
• Browse our .dll file which is created and deserve how they are displayed in toolbox.
• From toolbox we can simply drag & drop asp.net automatically register created a control in pages.

No comments:

Post a Comment