asp.net C# hit counter

Codeaddict7423
Codeaddict7423 used Ask the Experts™
on
Hello,

I have attempted to write a simple hit counter using both *.txt files and *.xml files.  
The hit counters seem to work locally, however, when I upload these files to my production server, the code does not seem to recognize the *.txt files or the *.xml files.

My code for the *.txt files follow:
-------------------
<form id="form1" runat="server">
    <div>
    <table border="1">
    <tr>
    <td> Visitor Count: </td>
    <td valign="top" align="center" style="background-color:Aqua;" >
   
       <asp:Label ID="Label1" runat="server" Text="Visitor Count:"></asp:Label>
     </td>
    </tr>
    </table>
       
     
    </div>
    </form>
----------------

My codebehind follows:
---------------

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;
using System.IO;

namespace HSCO_Sheriff_ExternalWeb
{
    public partial class WebForm15 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            Application.Lock();
            //Response.Write(gethitcounts());
            Label1.Text = gethitcounts();
            Application.UnLock();
        }
        public string gethitcounts()
        {
            string lastcount = "";
            try
            {
                StreamReader SR = File.OpenText(System.Web.HttpContext.Current.Server.MapPath("counter/hitcounter_webform15.txt"));              
                string getcount = null;

                while ((getcount = SR.ReadLine()) != null)
                {
                    lastcount = lastcount + getcount;
                }
                SR.Close();
                long newcount = Convert.ToInt64(lastcount);
                newcount++;
                TextWriter TxtWtr = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("counter/hitcounter_webform15.txt"));
                TxtWtr.WriteLine(Convert.ToString(newcount));
                TxtWtr.Close();
                SR = File.OpenText(System.Web.HttpContext.Current.Server.MapPath("counter/hitcounter_webform15.txt"));
                getcount = null;
                lastcount = "";
                while ((getcount = SR.ReadLine()) != null)
                {
                    lastcount = lastcount + getcount;
                }
                SR.Close();

            }
            catch (Exception ex)
            {
                TextWriter TxtWtr = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("counter/hitcounter_webform15.txt"));
                TxtWtr.WriteLine(Convert.ToString("1"));
                TxtWtr.Close();
                lastcount = "1";
            }
            return lastcount;
        }
    }

}
--------------

Any help in getting this to work OR any code examples that function to provide a simple page count would be greatly appreciated.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Is there a folder in the same directory as the .aspx file itself which is named "content"? If so, have you created the file named "hitcounter_webform15.txt" within that directory? If yes, then are you receiving any errors (or exceptions)?
The guy here has developed a custom control for the same, just give it a thought:-
http://www.codeproject.com/Articles/5912/Easy-to-use-Hit-Counter

Here is another implementation:-
http://www.codeproject.com/Articles/2542/Page-Hit-Counter-using-ASP-NET-and-JScript-NET

Author

Commented:
Kaufmed,

Thank you for the quick reply.  Indeed, there is a "counter" folder and within it, there is a file namded "hitcounter_webform15.txt".  This counter seems to function in my local machine environment and in the test server, however, when I deploy this to the production server, I receive no error message, but the database is not updated when the page loads.

ANY help would be greatly appreciated.
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Database? I thought you were writing to a file.

Author

Commented:
Kaufmed,

Please let me explain.  My requirements have changed.  In order to store historical information on website popularity (# of hits / quarter, etc.), I have been asked to write the number of hits to a SQL database table.  

My code for the *.aspx page is as follows:
----------------
<!--panel for page hit counter statistics starts -->            
<asp:Panel ID="pnl_statistics" runat="server" Visible="false">
<asp:Label ID="lblPageName" runat="server" Text="Contact_Us"></asp:Label>&nbsp;
<asp:Label ID="lblHits" runat="server" ></asp:Label>&nbsp;&nbsp;
<asp:Label ID="lblHitCounterDateDisplay" runat="server" Text="Label"></asp:Label>&nbsp;&nbsp;<asp:Label ID="lblHitCounterDate" runat="server" Text="Label"></asp:Label>
</asp:Panel>        
<!--panel for page hit counter statistics ends -->
---------------

My codebehind to support this is as follows:
--------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Mail;
using System.IO;

namespace xxxxxxxxxxxxxxxx

{

    public partial class Contact_Us : System.Web.UI.Page
    {
        string strConnStringHitCounterNew = ConfigurationSettings.AppSettings["HitCounterNew"];

        protected void Page_Load(object sender, EventArgs e)
        {
           
            //objects we will need to work with the db    
            SqlConnection conn;
            SqlCommand cmd;

            //pnl_warrants_search.Visible = true;


            lblHitCounterDateDisplay.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");

            if (!Page.IsPostBack)
            {
                //connect to the db        
                conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["HitCounterNew"].ConnectionString);

                //the sql command to increment hits by 1        
                cmd = new SqlCommand("UPDATE HitCounterNew SET HitCounter = HitCounter+1, HitCounterDate = @HitCounterDate WHERE PageName=@PageName", conn);
                cmd.CommandType = CommandType.Text;
                //update where Name is 'about_us' which corresponds to this page        
                cmd.Parameters.AddWithValue("@PageName", "Contact_Us");
                cmd.Parameters.AddWithValue("HitCounterDate", lblHitCounterDateDisplay.Text);

                using (conn)
                {
                    //open the connection            
                    conn.Open();

                    //send the query  -- To Update Hit Counter
                    cmd.ExecuteNonQuery();

                    //Another command To Store Date
                    cmd = new SqlCommand("Insert Into HitCounterNew (PageName,HitCounter,HitCounterDate) Values(@PageName,@HitCounter,@HitCounterDate)", conn);
                    cmd.Parameters.AddWithValue("@PageName", lblPageName.Text);
                    cmd.Parameters.AddWithValue("@HitCounter", lblHits.Text);
                    cmd.Parameters.AddWithValue("@HitCounterDate", lblHitCounterDateDisplay.Text);
                    cmd.ExecuteNonQuery();

                }


            }

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

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

            //select where Name is 'about_us' which corresponds to this page    
            cmd.Parameters.AddWithValue("@PageName", "Contact_Us");
            cmd.Parameters.AddWithValue("@HitCounterDate", "Contact_Us");

            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 = "Counter Pageviews: - " + rdr["HitCounter"].ToString();
                    lblHitCounterDate.Text = "HitCounter Date: - " + rdr["HitCounterDate"];
                }
            }

        }
         
 }
 }
 }
------------------

In my local machine and in our test server, this code functions as expected.  However, when I push this code to our production server, it hangs and does not write to the database (I'm monitoring the sql database table "HitCounterNew").  

I am at a loss to explain or fix the issue related to this code not functioning on the production server.

ANY HELP would be greatly appreciated.
Hi,
I have tried your code it creates multiple record with same name in the database. Which should not happen.
Instead create as SP (stored Proc) which should accept "PageName", and "Date".
The SP should check if the Page exist for the given date then update the record else insert a new record.

The SP should return the Data as well so you can avoid hitting the DB twice.

Are you able to run the above mentioned code on Production? Are you getting any error in Logs?

In your first case:
Writing to a Text of XML can be a Crash in Production servers where there are more than one server managed using Load Balancer. (very Common Scenario)
To avoid this you should write to Database.

In your Second Case:
You have many record generated for your each visit means 100 visits = 100*3 = 300 DB hits. which can be a big issue at performance point.

Author

Commented:
darjimaulik,

Thank you for your suggestions. Indeed, I am attempting to  have a page counter that writes toa a SQL database but I'm having problems not duplicating records.  

ANY sample code that could help me with this would be greatly appreciated.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial