Avatar of Codeaddict7423
Codeaddict7423
Flag for United States of America asked on

asp.net C# hit counter

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.
ASP.NETXML

Avatar of undefined
Last Comment
Codeaddict7423

8/22/2022 - Mon
kaufmed

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)?
BuggyCoder

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
Codeaddict7423

ASKER
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.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
kaufmed

Database? I thought you were writing to a file.
Codeaddict7423

ASKER
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.
ASKER CERTIFIED SOLUTION
darjimaulik

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Codeaddict7423

ASKER
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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.