Application State in Asp.net

Next Post
By Admin at 9 Nov 2014, 17:52 PM
  • Application state is a data repository used to store data on the application machine. The data is stored in the memory and can be easily retrieved. It acts as a global variable shared by multiple users or sessions. A small portion of often used data can be stored in the application state.

    The Instance, HttpApplicationState will be created only once upon initial user request. After initial user request, it can be accessed using the Application property of the HttpContext

    The following example will show how to implement the Application State to increment the values.

    Example 1

    Design
    1. <html xmlns="http://www.w3.org/1999/xhtml">
    2. <head runat="server">
    3. <title>Application State</title>
    4. </head>
    5. <body>
    6. <form id="form1" runat="server">
    7. <div>
    8. <h3>Application State Example</h3>
    9. <asp:Label ID="lblCounter" runat="server" Text=""></asp:Label>
    10. <br />
    11. <asp:Button ID="btnCount" runat="server" Text="Count"
    12. onclick="btnCount_Click" />
    13. </div>
    14. </form>
    15. </body>
    16. </html>
    Code
    1. protectedvoid btnCount_Click(object sender, EventArgs e)
    2. {
    3. int MyCount = 0;
    4. if (Application["Counter"] != null)
    5. {
    6. MyCount = (int)Application["Counter"];
    7. }
    8. MyCount++;
    9. Application["Counter"] = MyCount;
    10. lblCounter.Text = MyCount.ToString();
    11. }

    Output

    undefined

    Example 2

    In the above example Application variable is used in the application. Application variable can be initialized in the Global.asax file also. There are specific methods to initialize the Application State variables. In the application folder you can get the Global.asax file. This file will be parsed and compiled dynamically. You cannot make any direct URL request during the runtime. When the application starts to run, then the Application_Start event will be started automatically. Below is the example to implement the Application state variable in the Application_Start Event.

    1. void Application_Start(object sender, EventArgs e)
    2. {
    3. Application["UserName"] = " TestUser";
    4. }

    When the application starts the UserName will be stored in the application state. This value will be available to the all users. The following code will get the value from the application state and displays in the label.

    1. lblUserName.Text = Application["UserName"].ToString();

    undefined


    Comments

     

    Post a comment

    Please correct the following: