Server Intellect
 
Home   Asp.Net Tutorials   What's New   Newsletter   More Resources
Tutorial RSS
 
  Categories
Advanced Technologies
AJAX
Internet Browsers
Charts
Controls
Database
Email
Error Handling
File
Graphics
Website Navigation
Network
Performance
User Interface and Themes
Validation
Visual Web Developer
Web Services
XML
Suggest Tutorial


Navigator: Home - Tutorials - Database - Creating a Simple Hit Counter with ASP.NET 4.0 and C#
Creating a Simple Hit Counter with ASP.NET 4.0 and C#

ASP.Net 4.0 Tutorials V4
Server Intellect Cloud Hosting

ASP.NET Database Tutorial

This tutorial will demonstrate how to create a simple system to count hits on individual pages using a database with ASP.NET 4.0 and C#.

Adding the Database
To keep track of the number of hits on each individual page of our sample site, we will need a small database that allows us to associate a number of hits to a given page. At this point in the tutorial I have created a new ASP.NET Empty Web Site. To create this database:
  1. Right click the project in your solution epxlorer.
  2. Select add ASP.NET folder.
  3. Select App_Data.
  4. Right click the App_Data folder.
  5. Select add new item...
  6. Select a SQL Database.
  7. Name it 'Database.mdf'.
  8. Click add.
  9. Expand the Database.mdf folder in your server/database explorer.
  10. Right click the Tables folder.
  11. Select add new table
  12. Add the following columns with their respective types to the table:
    Column Name  Data Type 
    Name  nvarchar(50) 
    Hits  int 
  13. Save the table as 'Hits'.
  14. Right click the Hits table.
  15. Select Show Table Data.
  16. Add the following rows to the table:
    Name  Hits 
    Default 
    About 
Yes, it is possible to find a good web host. Sometimes it takes a while to find one you are comfortable with. After trying several, we went with Server Intellect and have been very happy thus far. They are by far the most professional, customer service friendly and technically knowledgeable host we've found so far.

This table will keep track of the hits to our Default and About pages respectively.

Adding the ConnectionString
Now that we have our database setup, the next thing that we need to do is add the connection to it in our Web.Config file. To do this, open up the Web.Config file for editing and add in the following code in between the <configuration> and <system.web> tags:
<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

Adding the Default.aspx Page
Next, we need to add a couple of pages to our web site. First we will add the home page, Default.aspx. To do this:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Default.aspx'.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a hyperlink onto the web form.
  8. Change the NavigateUrl property of the hyperlink to '~/About.aspx'.
  9. Change the text of the hyperlink to 'About'.
  10. Add a break line after the hyperlink.
  11. Drag and drop a label underneath the break line.
  12. Change the ID property of the label to 'lblHits'.
  13. Change the Text property of the label to an empty string.
Adding the About.aspx Page
Next, we will add the about page, About.aspx. To do this:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'About.aspx'.
  5. Click add.
  6. Open About.aspx up to design mode.
  7. Drag and drop a hyperlink onto the web form.
  8. Change the NavigateUrl property of the hyperlink to '~/Default.aspx'.
  9. Change the text of the hyperlink to 'Home'.
  10. Add a break line after the hyperlink.
  11. Drag and drop a label underneath the break line.
  12. Change the ID property of the label to 'lblHits'.
  13. Change the Text property of the label to an empty string.
We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

Counting the Hits
Next, we need to add in some code that will increment the number of hits associated with each page when they are loaded. First, we will add the functionality to the Default.aspx page. To do this, open up Default.aspx.cs for editing and add in the following using statements:
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

Next, add the following code to the Page_Load event method:
protected void Page_Load(object sender, EventArgs e)
{
    //objects we will need to work with the db
    SqlConnection conn;
    SqlCommand cmd;

    //IF PAGE IS NOT A POSTBACK, ADD A HIT
    if (!Page.IsPostBack)
    {
        //connect to the db
        conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        //the sql command to increment hits by 1
        cmd = new SqlCommand("UPDATE Hits SET Hits = Hits+1 WHERE Name=@Name", conn);
        cmd.CommandType = CommandType.Text;

        //update where Name is 'Default' which corresponds to this page
        cmd.Parameters.AddWithValue("@Name""Default");

        using (conn)
        {
            //open the connection
            conn.Open();
            //send the query
            cmd.ExecuteNonQuery();
        }
    }

    //DISPLAY HITS IN OUR LABEL
    //connect to the db
    conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

    //the sql command to select the row of hits corresponding to this page
    cmd = new SqlCommand("SELECT * FROM Hits WHERE Name=@Name", conn);
    cmd.CommandType = CommandType.Text;

    //select where Name is 'Default' which corresponds to this page
    cmd.Parameters.AddWithValue("@Name""Default");

    using (conn)
    {
        //open the connection
        conn.Open();
        //send the query and store the results in a sqldatareader
        SqlDataReader rdr = cmd.ExecuteReader();

        if (rdr.Read())
        {
            //set the text of our label to the current # of hits
            lblHits.Text = "Default Page Hits - " + rdr["Hits"].ToString();
        }
    }
}

Let's review what this code is doing. First, it determines if the page load method is being triggered by a postback or not. If it is not a postback, we increment the hits in our table that correspond to the Default.aspx page. Then, we grab the number of hits from the database and display that in a label so that we can see the current number of hits. Next, we need to add similar code to the About.aspx page. To do this, open up About.aspx.cs for editing and add in the following using statements:
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

Next, add the following code to the Page_Load event method:
protected void Page_Load(object sender, EventArgs e)
{
    //objects we will need to work with the db
    SqlConnection conn;
    SqlCommand cmd;

    //IF PAGE IS NOT A POSTBACK, ADD A HIT
    if (!Page.IsPostBack)
    {
        //connect to the db
        conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        //the sql command to increment hits by 1
        cmd = new SqlCommand("UPDATE Hits SET Hits = Hits+1 WHERE Name=@Name", conn);
        cmd.CommandType = CommandType.Text;

        //update where Name is 'About' which corresponds to this page
        cmd.Parameters.AddWithValue("@Name""About");

        using (conn)
        {
            //open the connection
            conn.Open();
            //send the query
            cmd.ExecuteNonQuery();
        }
    }

    //DISPLAY HITS IN OUR LABEL
    //connect to the db
    conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

    //the sql command to select the row of hits corresponding to this page
    cmd = new SqlCommand("SELECT * FROM Hits WHERE Name=@Name", conn);
    cmd.CommandType = CommandType.Text;

    //select where Name is 'About' which corresponds to this page
    cmd.Parameters.AddWithValue("@Name""About");

    using (conn)
    {
        //open the connection
        conn.Open();
        //send the query and store the results in a sqldatareader
        SqlDataReader rdr = cmd.ExecuteReader();

        if (rdr.Read())
        {
            //set the text of our label to the current # of hits
            lblHits.Text = "About Page Hits - " + rdr["Hits"].ToString();
        }
    }
}

Need help with cloud hosting? Try Server Intellect. We used them for our cloud hosting services and we are very happy with the results!

Testing
To test this out, load up the web site and click back and forth on the links. Notice the number of hits displayed in the label go up. Refresh the page a few times to increase the count on one page and ensure that you have two different respective counts for each page.
Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!



 
  Developer Resources







Server Intellect Rocks