asp.net asax file usage and counter instances

Source: Internet
Author: User
Tags datetime

Application Object (HttpApplicationState type, Translator: Application object is a property of the HttpApplication class, the Web application is globally unique, The first time a Web application was asked to come in is a place where we save global information in a Web application, where the Application object is a convenient place to save global information, such as a connection string to save the database tutorial:

private void Page_Load (object sender, System.EventArgs e)

{

string connectionstring = application["ConnectionString"].tostring ();

. . .

}

You can also declare static member variables in the HttpApplication class to hold application state information, for example, the database connection string in the example above can be saved in the following way.

public class Global:system.web.httpapplication

{

public static readonly string connectionstring = "Connection Information";

. . .

}


You can access the static member variable anywhere in the ASP tutorial. NET code, for example: string connectionstring = global.connectionstring;

It is very important that if you want the string to be accessible globally, the string must be declared as a static member variable (you can also create a static property).

Conversely, if you use a generic member variable (non-static) in the global type, you can only save the request state, for example, to show that the following code will output the processing time (in milliseconds) of all requests in the Debug window

public class Global:system.web.httpapplication

{

protected DateTime beginrequesttime;

protected void Application_BeginRequest (object sender, EventArgs e)

{

Beginrequesttime = DateTime.Now;

}

protected void Application_EndRequest (object sender, EventArgs e)

{

String Messageformat = "Elaps Tutorial ed Request time (ms) = {0}";

TimeSpan difftime = Datetime.now-beginrequesttime;

Trace.WriteLine (

String.Format (Messageformat, difftime.totalmilliseconds));

}

. . .

}


OK, now let's go back to the topic on saving application state. Is it better to save a reference to an object in a Application object or to declare a static member or attribute in the global class? Every way has its pros and cons. Saving global static members in the global class can make your data access strongly typed, unlike application objects, you do not need to type conversions, and the following code illustrates their differences:
DataSet Cacheddata = (DataSet) application["myDataSet"];

String mystring = application["mystring"].tostring ();

DataSet cacheddata = Global.mydataset;

string mystring = global.mystring;

Strong typing makes your code clearer and stronger, which avoids the performance penalty of Run-time type conversions when application performance requirements are high. If you are saving data of value type, strong typing can also avoid the loss of performance caused by boxing (boxing) and unloading (unboxing). In addition, the Application object also has a performance problem with locking caused by thread synchronization. If your global data is initialized only once and will not change again, using static members in the global class avoids the loss of performance caused by locking. However, if you take this approach, it is highly recommended that you use accessors (properties) to ensure that the variable is read-only. If you want to read both static member variables in the global class, keep the thread safe. The Application object provides thread-safety assurance internally by acquiring a read-write lock.


Take a look at the use of asax files to do site counters

Added Global.asax,app_code folder Global.asax.cs, text file site_counter.txt and write number 0, the code is as follows:

Global.asax

<%@ application inherits= "Linker.global" language= "C #"%>
Global.asax.cs

using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.web.ui.webcontrols.webparts;
Using System.Web.UI.HtmlControls;
Using System.IO;

NAMESPACE linker
... {
/**////<summary>
Summary description of Global
</summary>
public class Global:httpapplication
... {
Public Global ()
... {
//
TODO: Add constructor logic here
//
}
protected void Application_Start (object sender, EventArgs e)
... {
Code that runs when the application starts
StreamReader rd = New StreamReader (Server.MapPath ("Site_counter.txt"));
Application.Lock ();
application["Site_counter"] = Int.parse (Rd.readline ());
Application.UnLock ();
Rd.close ();
}
protected void Session_Start (object sender, EventArgs e)
... {
Code that runs when a new session starts
Application.Lock ();
application["Site_counter"] = Convert.ToInt32 (application["Site_counter"]) + 1;
Application.UnLock ();

StreamWriter wt = new StreamWriter (Server.MapPath ("Site_counter.txt"), false);
Application.Lock ();
Wt.writeline (application["Site_counter"]);
Application.UnLock ();
Wt.close ();
}
}
}
And then display the system on the page that needs to be displayed.

For example, simple:

Label_site_counter.text = convert.tostring (application["Site_counter"));

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.