i creating website having masterpage. want create hit counter record number of visitor , found code , put in masterpage. code as: markup code:
<%@ control language="c#" autoeventwireup="true" codefile="counter.ascx.cs" inherits="counter" %> <asp:label id="lblcounter" runat="server"></asp:label>
code behind - c#:
protected void page_load(object sender, eventargs e) { this.countme(); dataset tmpds = new dataset(); tmpds.readxml(server.mappath("~/counter.xml")); lblcounter.text = tmpds.tables[0].rows[0]["hits"].tostring(); } private void countme() { dataset tmpds = new dataset(); tmpds.readxml(server.mappath("~/counter.xml")); int hits = int32.parse(tmpds.tables[0].rows[0]["hits"].tostring()); hits += 1; tmpds.tables[0].rows[0]["hits"] = hits.tostring(); tmpds.writexml(server.mappath("~/counter.xml")); }
an xml file in root directory make code work. xml file as:
<?xml version="1.0" encoding="utf-8" ?> <counter> <count> <hits>0</hits> </count> </counter>
but every pages within website triggers counter whenever visit them. please me modify code trigger counter 1 time 1 visitor.
i have decided put code on index page only, still every refresh , every lick open index (even while staying on index page) triggers counter.
why not add session? think it's easiest way xml solution, if saved sql have more logic involved.
private void countme() { if(session["counted"]==null){ dataset tmpds = new dataset(); tmpds.readxml(server.mappath("~/counter.xml")); int hits = int32.parse(tmpds.tables[0].rows[0]["hits"].tostring()); hits += 1; tmpds.tables[0].rows[0]["hits"] = hits.tostring(); tmpds.writexml(server.mappath("~/counter.xml")); session["counted"] = "yes"; } }
Comments
Post a Comment