I haven't worked on an ASP. NET project for a long time. Suddenly, a project requires statistics on the number of visitors to the website and the number of online users.
Add the following code to the Global. asax file:
<% @ Application language = "C #" %>
<SCRIPT runat = "server">
String slogfile = appdomain. currentdomain. basedirectory + "visitedlog.txt ";
Void application_start (Object sender, eventargs E)
{
// Code that runs when the application starts
// Code that runs on application startup
// The number of items to be read from the record file to prevent unexpected server crashes and restart
If (! System. Io. file. exists (slogfile ))
{
System. Io. filestream fsnew = system. Io. file. Create (slogfile );
Fsnew. Close ();
}
String [] lines = system. Io. file. readalllines (slogfile );
Double itotalcount = 0;
Int ionline = 0;
If (lines! = NULL & lines. length> 0)
{
Double. tryparse (lines [lines. Length-1]. tostring (), Out itotalcount );
}
Application ["totalcount"] = itotalcount;
Application ["online"] = ionline;
}
Void application_end (Object sender, eventargs E)
{
// Code that runs when the application is closed
System. Io. streamwriter RW = system. Io. file. createtext (slogfile );
RW. writeline (application ["totalcount"]);
// RW. writeline ();
RW. Flush ();
RW. Close ();
}
Void application_error (Object sender, eventargs E)
{
// Code that runs when an unhandled error occurs
}
Void session_start (Object sender, eventargs E)
{
// The code that runs when the new session starts
// Code that runs when a new session is started
Session. Timeout = 10;
Application. Lock ();
Application ["totalcount"] = system. Convert. todouble (application ["totalcount"]) + 1;
Application ["online"] = system. Convert. toint32 (application ["online"]) + 1;
Application. Unlock ();
If (convert. toint32 (application ["totalcount"]) % 50 = 0)
{
System. Io. streamwriter RW = system. Io. file. createtext (slogfile );
RW. writeline (application ["totalcount"]);
// RW. writeline ();
RW. Flush ();
RW. Close ();
}
}
Void session_end (Object sender, eventargs E)
{
// The code that runs when the session ends.
// Note: Only the sessionstate mode in the web. config file is set
// The session_end event is triggered only when inproc is used. If the session mode is set to StateServer
// Or sqlserver, the event is not triggered.
Application. Lock ();
Application ["online"] = system. Convert. toint32 (application ["online"])-1;
Application. Unlock ();
}
</SCRIPT>