Wrox Programmer Forums
|
ASP.NET 1.0 and 1.1 Basics ASP.NET discussion for users new to coding in ASP.NET 1.0 or 1.1. NOT for the older "classic" ASP 3 or the newer ASP.NET 2.0.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 1.0 and 1.1 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old November 2nd, 2003, 03:41 PM
Authorized User
 
Join Date: Nov 2003
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
Default Site Hit Counter

How do I correctly code a Site Hit Counter for the number of times (sessions) a page has been visited. Forgive me for moving this question to different topics. This is probably the correct one.

Reference is Professional ASP.NET 1.0, pages 610 and 611.

Development Platform is XP Professional, Version 2002, Service Pack 1; with SQL Server 2000 and IIS 5.1. I think the Web Server is the same but I can't be sure until Monday morning.

In Global.aspx.cs I've inserted the second line with intHitCount
    public class Global : System.Web.HttpApplication {
        protected int intHitCount = 0;
and:

    protected void Session_Start(Object sender, EventArgs e) {
        intHitCount += 1;
        Session["SessionHitCounter"] = intHitCount.ToString();
    }

Then in the Welcome.aspx page file I have:
<form id="Form1" method="post" runat="server">
<h3 class="title"><i>Welcome! You are visitor number</i><br>
<asp:label id="lblHitNo" runat="server" Width="129px" BackColor="#dbdbdd" ForeColor="#ef0063"></asp:label><br>
<i>since November 2003</i></h3>
</form>

and in the Welcome.aspx.cs file I have:
public class WelcomeForm : System.Web.UI.Page {
    protected System.Web.UI.WebControls.Label lblHitNo;
    protected System.Web.UI.HtmlControls.HtmlForm Form1;

    private void Page_Load(object sender, System.EventArgs e) {
        lblHitNo.Text = (string)Session["SessionHitCounter"];
    }


and this does NOT work. Strangely, it counts up to about 85 and then starts over. I've determined this by starting a fresh internet connection (on a dial-up) and fresh browser 3 times a day for about a week, while I keep trying to fix the code.




Sandra MacGregor, AKA Cryptocode
__________________
Sandy
 
Old November 2nd, 2003, 06:40 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Hi there,

If the counter looses its value after such a long time, it's probably due to IIS or the entire server restarting. Are you using an ISP or are you running your own server? Your ISP may be restarting the server (or recycle the IIS process). This will cause the Global variables to loose their values (they are initialized every time the application starts).

If this turns out to be the case, write some code in the global.asa Application_Start event that reads the counter from a text file or a database.
Then modify the Session_Start event so it not only retrieves the counter from intHitCOunt, but also updates the text file or database with the new value.

This way, you end up with durable counters that survive server / IIS restarts.

HtH,

Imar


---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.
 
Old November 2nd, 2003, 06:59 PM
Authorized User
 
Join Date: Nov 2003
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Imar,

Yes, that seems most likely and I'll do that.

Thanks a lot. BTW what is HtH?


Sandra MacGregor, AKA Cryptocode
 
Old November 2nd, 2003, 07:18 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Hope this helps.

HtH ;)

Imar


---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.
 
Old November 2nd, 2003, 11:42 PM
Authorized User
 
Join Date: Nov 2003
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Imar,

Your help is great and greatly appreciated.
I've serialized the value of the Hit Counter in Session_Start and tested it locally. It should work.
But I have to give the full path name to my hard disk.

Is there a way to tell the ISP Server to write it locally, such as referencing the IP of the app?

This is my very first .NET site, for my son's business at
www.nolimit.net currently. I'm having a ball. It's so much more fun than my regular work {embedded cryptography in some usually obscure device with no O.S). I hope to do a lot more of .NET. And having people like you volunteer to help is the best.


Sandra MacGregor, AKA Cryptocode
 
Old November 3rd, 2003, 04:22 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

What do you mean by Writing it locally? You want the server of your ISP to write it at your local server?

If that's the case, a Web service might be a great idea. The FileSystemObject in ASP, or other File methods in .NET are not designed to save info to remote servers (AFAIK, that is). By using a Web service, it's easy to pass info back and forth between your server and the ISP.

Doesn't your ISP server support database connections? Not even to a Microsoft Access database? That would make it pretty easy to save information in Start and End events so the info remains available, even when the server restarts.

Cheers,

Imar


---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.
 
Old November 3rd, 2003, 05:38 PM
Authorized User
 
Join Date: Nov 2003
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Imar,

No, I don't want the ISP server to write it on my machine. But I'm trying to run the code first on my machine to test that it works there. Aftwards I'll change addresses to the ISP. At least that's my plan.

I've serialized a small file containing the visitor number. When I use a hard-coded file address on my machine it works fine. The hard-code is:
// FileStream s1 = new FileStream("D:\\\\Robby\\NoLimitEngin\\Visitor.bin ", FileMode.Open);
But I don't know the hard address of the ISP.

So, I'm changing the hard-code to:
        protected void Application_BeginRequest(Object sender, EventArgs e) {
            // Build the Application Path to workaround Web root reference issue
            if (Application["AppPath"] == null) {
                String sAbsUri = Request.Url.AbsoluteUri;
                String sRawUrl = Request.RawUrl;

                if (Request.ApplicationPath == "/")
                    Application["AppPath"]= sAbsUri.Substring(0,sAbsUri.Length -
                    sRawUrl.Length);
                else
                    Application["AppPath"] = sAbsUri.Substring(0,sAbsUri.Length -
                    sRawUrl.Length) + Request.ApplicationPath;
            }
        }



public void DoSerial(){
    string a_path = (string)Application["AppPath"] + "/Visitor.bin";
    FileStream s1 = new FileStream(a_path, FileMode.Open);
    BinaryFormatter BinFor = new BinaryFormatter();
    BinFor.Serialize(s1, a_visitor);
    s1.Close();
}

Alas, this gets a big error "Doesn't recognize Absolute URI's. Although it looks OK to me:
"http://localhost/NoLimitEngin/Visitor.bin"

Where am I going wron n n g?



Sandra MacGregor
 
Old November 3rd, 2003, 05:46 PM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 1,110
Thanks: 0
Thanked 3 Times in 3 Posts
Default

Here is the code for old asp:
global.asa file
<SCRIPT LANGUAGE=VBScript RUNAT=Server>

Sub Session_OnStart
' This script executes when each new user comes to the site.
' Increase and save the visitor counter
'*** Read counter and increment
'On Error Resume Next
Set FileObject = Server.CreateObject("Scripting.FileSystemObject")

Set Out= FileObject.OpenTextFile (Server.MapPath ("/") + "/visitors.txt", 1, FALSE, FALSE)
visitors = Out.ReadLine
If len(visitors)=0 Then
visitors=1
Else
visitors=visitors+1
End If
Set Out = Nothing

'*** Write new counter
Set Out= FileObject.CreateTextFile (Server.MapPath ("/") + "/visitors.txt", TRUE, FALSE)
Out.WriteLine(visitors)
Session("visitors") = visitors
Set Out = Nothing
End Sub

</SCRIPT>


the counter page:
You are visitor number <% =session("visitors")%>

 
Old November 3rd, 2003, 05:59 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Well, you can try this to write to a file:
Code:
int NumberOfHits = 36; // Get counter here
string FileName = Server.MapPath("/MyCounters.txt");
StreamWriter objStreamWriter;
objStreamWriter = File.CreateText(FileName);
objStreamWriter.WriteLine("Number of Hits: " + NumberOfHits.ToString());
objStreamWriter.Close();
The Server.MapPath call will translate the "virtual path" /MyCounters.txt to a physical path, like c:\inetpub\wwwroot\MyCounters.txt for example. This will work with your ISP as well, so you don't need to know where the site is located physically.

This code just writes out the line "Number Of Hits" and the counter to the text file.

Cheers,

Imar


---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.
 
Old November 4th, 2003, 08:56 PM
Authorized User
 
Join Date: Nov 2003
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Yes - it's working!
At the bottom of www.NoLimitEng.com

My ISP confirmed the IIS and Server restarts often. This is a shared server and I was told that many users are doing "real-time" which uses more memory than they have available, and they 'cap'out, thus causing a restart.

I used the Server.MapPath and the returns the correct path on the server's hard drive. I also used the StreamWriter and that works (but I think I like the BinaryFormatter better). I also put Application.Lock and Unlock around the writing part. If that might cause a problem please let me know.

Stu9820 I don't know ASP and I already feel overloaded on how much I have to learn. I'll just stay with ASP.NET, but I am glad you responded.

Next for me is Part II - the SQL Server 2000.

Thanks both very much for your help!



Sandra MacGregor





Similar Threads
Thread Thread Starter Forum Replies Last Post
A Hit Counter, PLEASE HELP !!!!! ARD_40 BOOK: Beginning PHP4/PHP 5 ISBN: 978-0-7645-4364-7; v5 ISBN: 978-0-7645-5783-5 1 April 23rd, 2006 06:25 AM
hit counter gumgak Classic ASP Basics 2 November 2nd, 2003 12:44 AM
Hit Counter mateenmohd HTML Code Clinic 7 September 28th, 2003 07:22 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.