Master C# Logo banner
Welcome to MasterCSharp.com - Master C#, the easy way... - by Saurabh Nandu

 


Xml Counter 4

Add Comment
 

 
Download File SDK
counter4.zip (6kb) v1.0.3705

Introduction
Page Counter - Everyone wants to know how many people and from where are visiting their pages (including Me) . A component without which any website is incomplete, is a good Counter which helps the Web Developer to track the viewers visiting his site.
 To meet this requirement I have developed a Counter in ASP.NET, since I have access only to free resources in have used XML as my database to store the visitor information. Although I am fully aware that if your site has high visitor count, XML won't be a good database since the file size of the database file will run into Megabytes in the span of few hours. But you will find this example very useful to learn Xml interaction in C#. This example has been updated for .NET SDK v1

Explanation
This example consists of 2 pages.
1) Counter.aspx - Contains the code to get the Viewer information and post it in a XML file. 
2) viewcounter.aspx - Is a Administrator file. 

Requirements
1) .NET SDK v1 (Note: This example might not run on future versions of the SDK).
2) ASP.NET hosting with appropriate write permissions.

XML Schema 

<Visitors xmlns="http://tempuri.org/xmlcounter.xsd">
  <xs:schema id="Visitors" targetNamespace="http://tempuri.org/xmlcounter.xsd" 
	xmlns:mstns="http://tempuri.org/xmlcounter.xsd" 
	xmlns="http://tempuri.org/xmlcounter.xsd" 
	xmlns:xs="http://www.w3.org/2001/XMLSchema" 
	xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" 
	attributeFormDefault="qualified" elementFormDefault="qualified">
    <xs:element name="Visitors" msdata:IsDataSet="true"
 		msdata:EnforceConstraints="False">
      <xs:complexType>
        <xs:choice maxOccurs="unbounded">
          <xs:element name="Viewer">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="UserAgent" type="xs:string" minOccurs="0" />
                <xs:element name="UserHostAddress" type="xs:string" minOccurs="0" />
                <xs:element name="UserHostName" type="xs:string" minOccurs="0" />
                <xs:element name="BrowserType" type="xs:string" minOccurs="0" />
                <xs:element name="BrowserName" type="xs:string" minOccurs="0" />
                <xs:element name="MajorVersion" type="xs:string" minOccurs="0" />
                <xs:element name="MinorVersion" type="xs:string" minOccurs="0" />
                <xs:element name="Platform" type="xs:string" minOccurs="0" />
                <xs:element name="Date" type="xs:string" minOccurs="0" />
                <xs:element name="Time" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
</Visitors>

Code
1) counter.aspx :- The Counter Page 

<%@ page language="c#"  EnableSessionState="True" %>
<%-- These are the imported namespaces need to run the counter --%>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<html>

<head>

<title>Saurabh's XML Counter Script</title>

 <script language="C#" runat="server">
 //script is called when the page is loaded
 public void Page_Load(Object src, EventArgs e)
 {
   //the path to the Xml file which will contain all the data
   //modify this if you have any other file or directory mappings.
   string dataFile="db/xmlcounter.xml" ;

   if(!Page.IsPostBack){
   //try-catch block containing the counter code
   try {

     DataSet counterData = new DataSet();
     //It is very Important to specify the "FileShare.ReadWrite" option.
     //This allows other viewers to also read and write to the Database
     FileStream dataIn ;
     dataIn = new FileStream(Server.MapPath(dataFile), FileMode.Open,
		FileAccess.Read, FileShare.ReadWrite) ;
     counterData.ReadXml(dataIn);
     dataIn.Close();
     //Update the Database only if a new session is there 	
     if(Session["counter"]==null)
     {
       //Create a new DataRow from the DataSet schema
       DataRow newRow = counterData.Tables[0].NewRow();

       //Fill the columns of the DataRow
       newRow["UserAgent"]=Request.UserAgent ;
       newRow["UserHostAddress"]=Request.UserHostAddress ;
       newRow["UserHostName"]=Request.UserHostName;
       HttpBrowserCapabilities bc = Request.Browser;
       newRow["BrowserType"]=bc.Type;
       newRow["BrowserName"]=bc.Browser;
       newRow["MajorVersion"]=bc.MajorVersion.ToString() ;
       newRow["MinorVersion"]=bc.MinorVersion.ToString();
       newRow["Platform"]=bc.Platform;
       DateTime now = DateTime.Now ;
       newRow["Date"]=now.ToShortDateString();
       newRow["Time"]=now.ToShortTimeString();
       counterData.Tables[0].Rows.Add(newRow);
       FileStream dataOut ;
       //Save the Updated file to disk!
       dataOut = new FileStream(Server.MapPath(dataFile), FileMode.Open,
				FileAccess.Write, FileShare.ReadWrite) ;
       counterData.WriteXml(dataOut, XmlWriteMode.WriteSchema);
       dataOut.Close();
       //Set a Session variable
       Session["counter"]="Set" ;
     }
     countMsg.Text+=counterData.Tables[0].Rows.Count.ToString();
    }
    catch(Exception edd)
    {
      //catch other exceptions
      Response.Write("<font color=#FF0000>An Exception Occurred "
			+edd.ToString()+"</font>") ;
    }
  }
}

</script>
</head>
<body >
<h3 align="center">Welcome to Saurabh's Counter Script</h3>
<br>
<p align="center">
This is a sample page which has the counter scripting in it.
Take the script from this page and paste it on your page.
</p>
<asp:Label   text="You are visitor No: "
style="font-size:10pt" id="countMsg" runat="server" />

<br>
<br>
<h5>This counter script has been taken from
<a href="http://www.MasterCSharp.com" >http://www.MasterCSharp.com </a>
you can get more such free scripts too. <br>
Counter Script made by <a href="mailto:saurabh@MasterCSharp.com">Saurabh Nandu </a>
</h5>
</body></html>

 

2) viewcounter.aspx : The counter information viewing page

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>

<%@ Page Language="C#"  %>
<html>
<head>
<title>Saurabh's XML Counter Script</title>
<script language="C#" runat=server>
//this script is execute when the page is loaded
public void Page_Load(Object sender, EventArgs e)
{
  //the path to the Xml file which will contain all the data
  //modify this if you have any other file or directory mappings.
  string datafile="db/xmlcounter.xml" ;

  try
  {
    Dataset counterData = new DataSet();
    //Open a FileStream to the Database
    //"FileShare.ReadWrite" enables other user to also read and write to the file
    FileStream fin ;
    fin = new FileStream(Server.MapPath(datafile), FileMode.Open,
			 FileAccess.Read, FileShare.ReadWrite);
    // Infer the DataSet schema from the XML data and load the XML Data
    counterData.ReadXml(new StreamReader(fin));
    //Close the stream
    fin.Close();
    //get the total no of viewers by getting the count of the no of
    //rows present in the Table 
    showtotal.Text ="Total Viewers :"+ counterData.Tables[0].Rows.Count.ToString() ;

    //databind the Repeater to the Dataset of table '0' ie the 'Viewer'
    MyDataList.DataSource = counterData.Tables[0].DefaultView;
    MyDataList.DataBind();
  }
  catch (Exception ed)
  {
    //if there is any exception then display it 
    Response.Write("<font color=#FF0000>An Exception occurred "
		+ed.ToString()+"</font>") ;
  }
}
</script>
</head>
<body >
<h4>Welcome to Saurabh's XML Counter Viewing Page.</h4>
<asp:label id="showtotal" text="" runat="server" />
	<br>

  <ASP:Repeater id="MyDataList" runat="server">

      <headertemplate>

         <h5> Viewer Details </h5>
      </headertemplate>

      <itemtemplate>
	<br>
	<table class="mainheads" width="60%" style="font: 8pt verdana" >

	<tr style="background-color:#FFFFCC">
	  <td>User Agent :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "UserAgent") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>User Host Address :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "UserHostAddress") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>User Host Name :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "UserHostName") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>Browser Type :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "BrowserType") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>Browser Name :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "BrowserName") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>Major Version :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "MajorVersion") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>Minor Version :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "MinorVersion") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>Platform :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "Platform") %>
          </td></tr>
	<tr style="background-color:#FFFFCC">
	  <td>Date :</td>
          <td>
            <%# DataBinder.Eval(Container.DataItem, "Date") %>
          </td></tr>


        <tr style="background-color:#FFFFCC">
	<td>Time :</td>
	<td>
            <%# DataBinder.Eval(Container.DataItem, "Time") %>
          </td>
        </tr>
	</table><br>
      </itemtemplate>

  </ASP:Repeater>
<br>
<h5>This counter script has been taken from <a href="http://www.MasterCSharp.com" >
http://www.MasterCSharp.com</a>
you can get more such free scripts too. <br>
Counter Script made by <a href="mailto:saurabh@MasterCSharp.com">Saurabh Nandu </a>
</h5>
</body></html>

Comments

Add Comment