开发者

About global.asax and the events there

So what i'm trying to understand is the whole global.asax events. I doing a simple counter that records website visits. I am using MSSQL.

Basicly i have two ints. totalNumberOfUsers - The total visist from begining. currentNumberOfUsers - Total of users viewing the site at the moment.

So the way i understand global.asax events is that every time someone comes to the site "Session_Start" is fired once. So once per user. "Application_Start" is fired only once the first time someone comes to the site.

Going with this i have my global.asax file here.

<script runat="server">

    string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup

        Application.Lock();
        Application["currentNumberOfUsers"] = 0;
        Application.UnLock();

        string sql = "Select c_hit from v_counter where (id=1)";
        SqlConnection connect = new SqlConnection(connectionstring);
        SqlCommand cmd = new SqlCommand(sql, connect);

        cmd.Connection.Open();

        cmd.ExecuteNonQuery();

        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            Application.Lock();
            Application["totalNumberOfUsers"] =  reader.GetInt32(0);
            Application.UnLock();
        }

        reader.Close();
        cmd.Connection.Close();

    }

    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }

    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started

        Application.Lock();
        Application["totalNumberOfUsers"] = (int)Application["totalNumberOfUsers"] + 1;
        Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] + 1;
        Application.UnLock();

        string sql = "UPDATE v_counter SET c_hit = @hit WHERE c_type = 'totalNumberOfUsers'";

        SqlConnection connect = new SqlConnection(connectionstring);
        SqlCommand cmd = new SqlCommand(sql, connect);

        SqlParameter hit = new SqlParameter("@hit", SqlDbType.Int);
        hit.Value = Application["totalNumberOfUsers"];
        cmd.Parameters.Add(hit);

        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

        Application.Lock();
        Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] - 1;
        Application.UnLock();
    }




</script>

In the page_load i have this

protected void Page_Load(object sender, EventArgs e)
{
    l_current.Text = Application["currentNumberOfUsers"].ToString();
    l_total.Text = Application["totalNumberOfUsers"].ToString();
}

So if i understand this right, every time someone comes to the site both the currentNumberOfUs开发者_如何学Goers and totalNumberOfUsers are incremented with 1. But when the session is over the currentNumberOfUsers is decremented with 1.

If i go to the site with 3 types of browsers with the same computer i should have 3 in hits on both counters. Doing this again after hours i should have 3 in current and 6 in total, right ?

The way its working right now is the current goes up to 2 and the total is incremented on every postback on IE and Chrome but not on firefox.

And one last thing, is this the same thing ?

Application["value"] = 0;
value = Application["value"]

//OR

Application.Set("Value", 0);
Value = Application.Get("Value");


Assuming that you're using a standard Asp.net membership provider you will be able to use membershipProvider.GetNumberOfUsersOnline

If you're looking to implement a custom solution, you may want to create a custom MembershipProvider and follow how Microsoft have implemented it. It is based on the count of all users with LastActivityDate greater than the current date minus UserIsOnlineTimeWindow


If you want to record number of hits on a site, why not just increment a column in your database every time Session_Start is hit?

Then when you want to display how many people have visited your site, just do a SQL Select statement from that column? Something like this..

void Session_Start(object sender, EventArgs e)
{
    string Sql = "UPDATE tbl_Visit SET TotalVisits=(TotalVisits+1)";
    // execute sql here
}

Then when you want to display it:

public void Page_Load(object sender, EventArgs e)  
{
    string Sql = "SELECT TotalVisits FROM tbl_Visit";

    lit_total_visits.Text = DataReader["TotalVisits"].ToString();
}

Probably the easiest way to go about it...


You can't track how many users there are currently on your site directly. The global.asax features a Session_End event, which is fired when a session times out, or after you manually forced Session.Abandon. But you can't really rely on the Event being fired.

A possibility would be to store the SessionID and the time of the last access in your database. Everytime a user loads a page, the last access time is set to the current time. To get the amount of users being online you can write a select that returns the amount of rows, where LastAccessTime > DateTime.Now.AddMinutes(-10)

Other suggestions were already made here: Best way to keep track of current online users

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜