ASP.NET - Click count

Asked By Gunasundari Loganathan
26-Sep-11 02:10 AM
Hi all,

       I have two links in my website. i want to know how many times those links are clicked. i want to save it in an XMl file. Help me please.
  Suchit shah replied to Gunasundari Loganathan
26-Sep-11 02:12 AM
Step 1:

- first we need to add these lines to our global.asax file
(if your website do not have it, create it by right-clicking on website in solution explorer,
and choosing Add New Item > Global Application Class option)

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["OnlineUsers"] = 0;
    }
 
    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
        Application.UnLock();
    }
 
    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["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
        Application.UnLock();
    }

This will allow us that whenever some distant web visitor opens our website in his browser,
and new session is created for him, our "OnlineUsers" variable in the global HttpApplicationState class instance
is increased.

Also when user closes his browser or does not click on any links in our website, session expires,
and our "OnlineUsers" global variable is decreased.

To know more about ApplicationState and HttpApplicationState class visit this MSDN link:
http://msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspx

NOTE:
we are using Application.Lock and Application.Unlock methods to prevent multiple threads
from changing this variable at the same time.

By calling Application.Lock we are receiving exclusive right to change the values in Application state.
But we must not forget to call Application.Unlock() afterwards.

Step 2:
In order for this to work correctly we need to enable sessionstate and configure its mode to InProc value (in our web.config file):

        <system.web>
        <sessionState mode="InProc" cookieless="false" timeout="20" />
        </system.web>

In-process mode stores session state values and variables in memory on the local Web server.
It is the only mode that supports the Session_OnEnd event that we used previously.

Timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' - in other words
here we set how long our users can be inactive before considered Offline.

In this example timeout is set to 20 minutes, so while our visitors click on some links in our website at least once
in a 20 minutes, they are considered online.
If they do not open any pages on our website longer than 20 minutes, they are considered Offline, and their session
is destroyed, so our online visitor counter is decreased by 1.
(You can experiment with lower or higher values of Timeout settings to see what is the best for your website).

Ok, so now we are done with configuration steps, let us see how to use this:

To show number of online visitors/users on your ASPX page you can use this code:

Visitors online: <%= Application["OnlineUsers"].ToString() %>

Next you could put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel control, and
use Timer to refresh it in regular intervals without refreshing the whole page, but that is another story
  smr replied to Gunasundari Loganathan
26-Sep-11 02:12 AM
HI

To avoid that the clicks made by crawlers and spiders, you can use this simple little trick that filters them out.

<a href="http://example.com" onclick="if(this.href.indexOf('redirect.ashx')==-1)this.href='redirect.ashx?url='+this.href">Click here</a>

refer
http://madskristensen.net/post/Count-clicks-on-external-links-in-ASPNET.aspx
http://forums.asp.net/t/1352022.aspx/1
  Anoop S replied to Gunasundari Loganathan
26-Sep-11 02:17 AM

To avoid that the clicks made by crawlers and spiders, you can use this simple little trick that filters them out.


<a href="http://example.com" onclick="if(this.href.indexOf('redirect.ashx')==-1)this.href='redirect.ashx?url='+this.href">Click here</a>

  Anoop S replied to Gunasundari Loganathan
26-Sep-11 02:19 AM

We can use a javascript function to call a server side function to add the clicking count.

Use ICallBackEventHandler to process this feature.

  • Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages
    http://msdn.microsoft.com/en-us/library/ms178208.aspx
    <script type="text/javascript">
       
function AddCountToServer(para) {
           
CallServer(para);
            window
.open("PDF/" + para);
           
return false;
       
}
   
</script>
<asp:TemplateField>
   
<ItemTemplate>
        <asp:HyperLink ID="Path" runat="server" NavigateUrl='
<%#Eval("id","javascript:return AddCountToServer(\"{0}\");") %>' >Path</asp:HyperLink>
   
</ItemTemplate>
</asp:TemplateField>
        public void RaiseCallbackEvent(String eventArgument)
       
{
           
AddCount(eventArgument);
       
}

       
public string GetCallbackResult()
       
{
           
// Returns the results of a callback event to the client.
           
return GetCount();
       
}

       
void Page_Load(object sender, EventArgs e)
       
{
           
ClientScriptManager cm = Page.ClientScript;
           
String cbReference = cm.GetCallbackEventReference(this, "arg",
               
"ReceiveServerData", "");
           
String callbackScript = "function CallServer(arg, context) {" +
                cbReference
+ "; }";
            cm
.RegisterClientScriptBlock(this.GetType(),
               
"CallServer", callbackScript, true);
       
}
       
       
private AddCount(string para)
       
{
           
// add count to xml here.
       
}
  James H replied to Gunasundari Loganathan
26-Sep-11 02:19 AM
 Add a Global.asax file in your website >> Add New Item >>Global Application Class and write this code in it.
 
public static int count = 0;
 
void Application_Start(object sender, EventArgs e)
  {
   
Application["myCount"] = count;
 }

 
void Session_Start(object sender, EventArgs e)
  {
   count =
Convert.ToInt32(Application["myCount"]);
   
Application["myCount"] = count + 1;
 }
 
Now every time when visitor open your site the variable count will be increased by one.
 
► To Get the total at you home page you can write it as:
 
int a;
a = Convert.ToInt32(Application["myCount"]);
  Suchit shah replied to Gunasundari Loganathan
26-Sep-11 02:22 AM
  1. Locate the code that starts with public class Global : System.Web.HttpApplication and add the following shaded lines of code:
  2. namespace HitCounters
    {
    /// <summary>
    /// Summary description for Global.
    /// </summary>
    public class Global : System.Web.HttpApplication
    {
private static int totalNumberOfUsers = 0;
private static int currentNumberOfUsers = 0;

/// <summary>
/// Required designer variable.
  1. The code that writes the counters to the database, makes use of objects like the http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemdataoledboledbconnectionclasstopic.asp (6), located in http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoledb.asp (7) namespace, so you'll need to add a reference to this namespace by adding a using statement, at the top of the page somewhere below the other using statements:
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
using System.Data.OleDb;
  1. The next step is to add code to the Session_Start event. This event will fire once for each user when they request the first page in your Web application, so this place is perfect for your hit counters. Inside this event, the values of the two hit counters are increased; one for the total number of users and one for the current number of users. Once the values are increased, the value of totalNumberOfUsers will be written to the database as well.

    Locate the skeleton for the Session_Start event and add the following code:
protected void Session_Start(Object sender, EventArgs e)
{
// Increase the two counters.
totalNumberOfUsers += 1;
currentNumberOfUsers += 1;

// Save the Total Number of Users to the database.
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Databases\Website.mdb;
User ID=Admin;Password=";

string sql = @"UPDATE Counters SET NumberOfHits = "
+ totalNumberOfUsers + " WHERE CounterType = 'UserCounter'";

OleDbConnection conn = new OleDbConnection(connectionString);

OleDbCommand cmd = new OleDbCommand(sql, conn);

// Open the connection, and execute the SQL statement.
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
  1. Just as with the Session_Start event, you'll need to write some code for the Session_End event as well. However, instead of increasing the counters, you should decrease the counter for the current number of users only. This means that whenever a user Session times out (usually 20 minutes after they requested their last page), the counter will be decreased, so it accurately holds the number of current users on your site. You should leave the counter for the total number of users untouched.
    Locate the Session_End event, and add this line of code:
protected void Session_End(Object sender, EventArgs e)
{
currentNumberOfUsers -= 1;
}
  dipa ahuja replied to Gunasundari Loganathan
26-Sep-11 03:35 AM
Untitled document
► Add a Global.asax file in your website >> Add New Item >>Global Application Class and write this code in it.
 
public static int count = 0;
 
void Application_Start(object sender, EventArgs e)
  {
   
Application["myCount"] = count;
 }

 
void Session_Start(object sender, EventArgs e)
  {
   count =
Convert.ToInt32(Application["myCount"]);
   
Application["myCount"] = count + 1;
 }
 
Now every time when visitor open your site the variable count will be increased by one.
 
► To Get the total at you home page you can write it as:
 
int a;
a = Convert.ToInt32(Application["myCount"]);
 
  dipa ahuja replied to James H
26-Sep-11 03:40 AM
@Tom Ritter 

Next time if you copy my code i will complaint to the moderator. If you don't know the answer don't copy paste my code

Message To Moderator : This person is has copied my code 2-3 times, please notice it.

Create New Account
help
Data.MySqlClient; using System.Data.OleDb; / / / <summary> / / / Summary description for Class1 / / / < / summary> public class Class2 { OleDbConnection myCon; OleDbDataAdapter myAdapter; OleDbDataReader myDataReader; DataSet myDataSet = new DataSet(); public string getConnection() { string connection = "Provider password, string desgn, string caddress, string baddress, string mobno, string phoneno, int type) { myCon = new OleDbConnection(getConnection()); OleDbCommand cmd = new OleDbCommand("insert into login (custfname, custlname, email, pwd, desgn, caddress, baddress, MobNo, Phone, TypeOfUsers) values ('" + fname lname + "', '" + email + "', '" + password + "', '" + desgn + "', '" + caddress + "', '" + baddress + "', '" + mobno + "', '" + phoneno + "', '" + type + "')", myCon); / / OleDbCommand cmd = new OleDbCommand("insert into login (custfname, custlname, Email, password, desgn, caddress, baddress, MobNo, Phone)values('" + fname + "', '" + lname myCon.Open(); cmd.ExecuteNonQuery(); myCon.Close(); } public DataSet fnlogin(string email, string password) { myCon = new OleDbConnection(getConnection()); / / string str = " select custid, custfname, email, pwd, Typeofusers from login where email = '" + email + "' and public void insertfinfo( string trucktype, string ocity, string destcity, string month, int frate) { myCon = new OleDbConnection(getConnection()); OleDbCommand cmd = new OleDbCommand("insert into freightinfo (trucktype, origincity, destcity, months, freightrate) values ('" + trucktype
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup message", "setconformation();setScrollerWidth();slidStart();", true); if (CadPartListpopUp ! = null) { / / ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "cadpop", "document.getElementById('" + CadPartListpopUp.ClientID + "').style.display = '';ShowBackShadow('dvbackShadow', true);", true); } } catch (ExceptionHandler ex) { ErrorHandler.SetMessage(ex.MessageDetails(), spnmessage); / / ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "popup message", "document.getElementById('" + ErrorPop.ClientID + "').style.display = '';", true); ScriptManager RegisterClientScriptBlock(this, this.GetType(), "popup message", "Message_MoveTO_popup('" + spnmessage.ClientID + "', 'spnmessage');JqueryPopupShow();", true); } catch (Exception ex) { objHandlers = new ExceptionHandler(ex, true); ErrorHandler.SetMessage(objHandlers.MessageDetails(), spnmessage); / / ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "popup message", "document.getElementById('" + ErrorPop.ClientID + "').style.display = '';", true); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "popup message", "Message_MoveTO_popup('" + spnmessage.ClientID + "', 'spnmessage');JqueryPopupShow();", true); } } private void BindActor() { / / ddlCustomer name = "sender"> < / param> / / / <param name = "e"> < / param> protected void imgbtnAddCadPro_OnClick(object sender, ImageClickEventArgs e) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "cadpop", "document.getElementById('" + CadProdListpopUp.ClientID + "').style.display = '';ShowBackShadow('dvbackShadow', true);", true); Chk_Product_Amada_CadCAM_Service GetProduct_Webservice(); } catch (Exception ex) { / / ErrorHandler.SetMessage(MessageHandler.AppMessage("127"), spnmessage); spnmessage.Text = ex.Message; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "popup message", "Message_MoveTO_popup('" + spnmessage.ClientID + "', 'spnmessage');JqueryPopupShow();", true); } if (obj ! = null) { List _Prod_name); } catch (Exception ex) { / / ErrorHandler.SetMessage(MessageHandler.AppMessage("127"), spnmessage); spnmessage.Text = ex.Message; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "popup message", "Message_MoveTO_popup('" + spnmessage.ClientID + "', 'spnmessage');JqueryPopupShow();", true); } / * Get Part Details From
Data.MySqlClient; using System.Data.OleDb; / / / <summary> / / / Summary description for Class1 / / / < / summary> public class Class2 { OleDbConnection myCon; OleDbDataAdapter myAdapter; OleDbDataReader myDataReader; DataSet myDataSet = new DataSet(); public string getConnection() { string connection = "Provider password, string desgn, string caddress, string baddress, string mobno, string phoneno, int type) { myCon = new OleDbConnection(getConnection()); OleDbCommand cmd = new OleDbCommand("insert into login (custfname, custlname, email, pwd, desgn, caddress, baddress, MobNo, Phone, TypeOfUsers) values ('" + fname lname + "', '" + email + "', '" + password + "', '" + desgn + "', '" + caddress + "', '" + baddress + "', '" + mobno + "', '" + phoneno + "', '" + type + "')", myCon); / / OleDbCommand cmd = new OleDbCommand("insert into login (custfname, custlname, Email, password, desgn, caddress, baddress, MobNo, Phone)values('" + fname + "', '" + lname myCon.Open(); cmd.ExecuteNonQuery(); myCon.Close(); } public DataSet fnlogin(string email, string password) { myCon = new OleDbConnection(getConnection()); / / string str = " select custid, custfname, email, pwd, Typeofusers from login where email = '" + email + "' and public void insertfinfo( string trucktype, string ocity, string destcity, string month, int frate) { myCon = new OleDbConnection(getConnection()); OleDbCommand cmd = new OleDbCommand("insert into freightinfo (trucktype, origincity, destcity, months, freightrate) values ('" + trucktype
Data.MySqlClient; using System.Data.OleDb; / / / <summary> / / / Summary description for Class1 / / / < / summary> public class Class2 { OleDbConnection myCon; OleDbDataAdapter myAdapter; OleDbDataReader myDataReader; DataSet myDataSet = new DataSet(); public string getConnection() { string connection = "Provider password, string desgn, string caddress, string baddress, string mobno, string phoneno, int type) { myCon = new OleDbConnection(getConnection()); OleDbCommand cmd = new OleDbCommand("insert into login (custfname, custlname, email, pwd, desgn, caddress, baddress, MobNo, Phone, TypeOfUsers) values ('" + fname lname + "', '" + email + "', '" + password + "', '" + desgn + "', '" + caddress + "', '" + baddress + "', '" + mobno + "', '" + phoneno + "', '" + type + "')", myCon); / / OleDbCommand cmd = new OleDbCommand("insert into login (custfname, custlname, Email, password, desgn, caddress, baddress, MobNo, Phone)values('" + fname + "', '" + lname myCon.Open(); cmd.ExecuteNonQuery(); myCon.Close(); } public DataSet fnlogin(string email, string password) { myCon = new OleDbConnection(getConnection()); / / string str = " select custid, custfname, email, pwd, Typeofusers from login where email = '" + email + "' and public void insertfinfo( string trucktype, string ocity, string destcity, string month, int frate) { myCon = new OleDbConnection(getConnection()); OleDbCommand cmd = new OleDbCommand("insert into freightinfo (trucktype, origincity, destcity, months, freightrate) values ('" + trucktype