Monday, 30 September 2013

How to Count No of Visitors in ASP.NET Using C#?






Add a Global.asax file which interacts with the entire application. Global.asax is a page containg session level and application level events, this is also called an application file.


The sample code is given below:

Global.asax


<%@ Application Language="C#" %>

<script runat="server">
    public static int count = 0;
    void Application_Start(object sender, EventArgs e)
    {
        Application["Visitor"] = count;
        // Code that runs on application startup

    }
   
    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
        count = Convert.ToInt32(Application["Visitor"]);
        Application["Visitor"] = count + 1;
      
    }

    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.

    }
      
</script>
 

In above code “count “  start from 0 (zero)  but as it goes on the Application[“Visitor”] and “count” increase 1 (one) and hold the value 1 (one).

Default.aspx

 
Default.aspx.cs
(Write the below code in to code behind page or .cs file)


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int a;
        a = Convert.ToInt32((Application["Visitor"]));
        Label1.Text = Convert.ToString(a);
        if (a < 10)
            Label1.Text = "000" + Label1.Text;
        else if (a < 100)
            Label1.Text = "00" + Label1.Text;
        else if (a < 1000)
            Label1.Text = "0" + Label1.Text;
    }
}
 
Output: