IntroductionIn this codesnippet, i will show you, How to create Hit Counter UserControl in ASP.NET.The hit counter is useful, when you are develop a web page, and then you have to monitor how many visitors visiting your page. ImplementationCreate a usercontrol using visual studio, and then add a label control to display count as like following, <asp:Label ID="lblCounter" runat="server"></asp:Label> Next ,add server side code for capture the visitor count. using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class WebUserControl : System.Web.UI.UserControl
{protected void Page_Load(object sender, EventArgs e)
{this.countMe();
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}private void countMe()
{
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());
hits += 1;
tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();
tmpDs.WriteXml(Server.MapPath("~/counter.xml"));
}
}
The important point,here you have to place xml file named counter.xml in your web server location.The XML file stricture will be following, <counter><count><hits>0</hits></count></counter> That's all for implementation of the hit counter. How to useJust drag and drop the this user control, where you want to capture the visitors count. ConclusionIn this codesnippet, i had demonstrated to you, How to create Hit Counter UserControl in ASP.NET. |