Creating hit counter for website - c#

I am creating a website having a masterpage. I want to create a hit counter to record the number of visitor and i found a code and put it in my masterpage. The code is 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 the root directory to make the code work. The XML file is as:
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
</counter>
But every pages within my website triggers the counter whenever i visit them. Please help me modify this code to trigger the counter only one time by one visitor.
I have decided to put the code on index page only, but still every refresh and every lick to open the index (even while staying on index page) triggers the counter.

Why not just add a session? I think it's the easiest way for an XML solution, if you saved it to SQL you could 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";
}
}

You need to check the url of the page for the counter to hit the code. Try something like this
protected void Page_Load(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if(url.Contains("index.aspx")
{
this.countMe();
}
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}

You can get the solution from Global.ascx File.
Go to code behind of Golobal.ascx.cs in your application.
Declare a variable in Global.Cs File.
And Maintain a Count in 'Session_Start' Function Of Global.ascx.cs file;
write some public method to get user count
Eg:
protected void Session_Start(Object sender, EventArgs e)
{
totalNumberOfUsers += 1;
currentNumberOfUsers += 1;
}
protected void Session_End(Object sender, EventArgs e)
{
currentNumberOfUsers -= 1;
}
public static int TotalNumberOfUsers
{
get
{
return totalNumberOfUsers;
}
}
public static int CurrentNumberOfUsers
{
get
{
return currentNumberOfUsers;
}
}

In addition to using "Session" as in prospectors example, due to the possibility of synchronization issues , don't forget to lock the DataSet before use.
private static readonly object LockObj = new object();
private static DataSet dataSet = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Counted"] == null)
{
lock (LockObj)
{
dataSet.ReadXml(Server.MapPath("~/counter.xml"));
dataSet.Tables[0].Rows[0]["hits"] = (1 + int.Parse(dataSet.Tables[0].Rows[0]["hits"].ToString())).ToString();
dataSet.WriteXml(Server.MapPath("~/counter.xml"));
dataset.clear();
}
Session["Counted"] = "true";
}
}

Related

A little help in asp.net C# jumping from method to method

My problem is that I can get from page_load to show_books function
but I cant get from show_books to book_detail.
Every time I try to fire book_details it gets me to page_load.
my code is this:
protected void Page_Load(object sender, EventArgs e)
{
//Here I create dynamic linkbuttons that calls datashow
lnk_button.Command += new CommandEventHandler(book_show);
}
protected void book_show(object sender, EventArgs e)
{
//Here I show all books from a category
//and I create dynamic linkbuttons that calls book_details
book_button.Command += new CommandEventHandler(book_details);
}
protected void book_details(object sender, EventArgs e)
{
//and Here I show the details of each book
}
I'm sorry if my question is annoyingly newbie
but I would like some help .
I just started to learn asp.net
well i don't understand why you need to do this,but code below works,hope it helps
protected void Page_Load(object sender, EventArgs e)
{
//Here I create dynamic linkbuttons that calls datashow
lnk_button.Command += new CommandEventHandler(this.book_show);
lnk_button.CommandName = "testClick";
lnk_button.CommandArgument = "1";
lnk_button.ID = "11";
lnk_button.Text = "blah";
book_button.Command += new CommandEventHandler(this.book_details);
book_button.CommandName = "testClick2";
book_button.CommandArgument = "2";
book_button.ID = "22";
book_button.Text = "blah2";
}
protected void book_show(object sender, EventArgs e)
{
//Here I show all books from a category
//and I create dynamic linkbuttons that calls book_details
book_button.Command += new CommandEventHandler(this.book_details);
book_button.CommandName = "testClick2";
book_button.CommandArgument = "2";
book_button.ID = "22";
book_button.Text = "blah2";
}
protected void book_details(object sender, EventArgs e)
{
//and Here I show the details of each book
}
public void book_show()
{
book_details() ;
}
public void book_details()
{
}

Defining and adding value to variable from session-variable

I'm trying to make a script that checks, if a user has the right age before joining a team. If the user age doesn't match the team age, the script should stop at this page, and require the user to click the button "BackToLastPageBtn" go back to the previous page, which uses a variable called "BackToLastPage", which gets its value from 'Session["currentUrl"]', before it is reset at Page_load.
The problem is, that it tells me the value is null, when clicking the button.
I don't know why it is null, when i add the value to "BackToLastPage", BEFORE resetting Session["currentUrl"]. I hope someone can tell me, and guide me in the right direction.
The CodeBehind - script
public partial class JoinTeam : System.Web.UI.Page
{
//Defining Go back variable
private string BackToLastPage;
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Adding value to go back variable from sessionurl
BackToLastPage = (string)Session["CurrentUrl"];
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
if (ClassSheet.CheckIfUserAgeMatchTeamAge(BrugerId, TeamId))
{
ClassSheet.JoinATeam(BrugerId, TeamId);
if (BackToLastPage != null)
{
//Uses the new savedUrl variable to go back to last page.
Response.Redirect(BackToLastPage);
}
else
{
Response.Redirect("Default.aspx");
}
}
else
{
AgeNotOk.Text = "Du har ikke den rigtige alder til dette hold";
}
}
else
{
//Not saving last page. Need to find solution.
Response.Redirect("Login.aspx");
}
}
//NOT WORKING...
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//Go back button
//Response.Write(BackToLastPage);
Response.Redirect(BackToLastPage);
}
}
Since you are setting session["CurrentURL"] to null in page_load. When the event is fired it no longer exists. Below is code that i got it working. I had to cut some of your code out since i dont have the definition of all your classes. Private properties do not persist through postbacks. If you wanted it to work the way you have it, you should save the previoius url in a hidden field on the page itself.
Page One:
protected void Page_Load(object sender, EventArgs e)
{
Session["CurrentUrl"] = Request.Url.ToString();
Response.Redirect("~/SecondPage.aspx");
}
Page Two:
private string BackToLastPage { get { return (Session["CurrentUrl"] == null) ? "" : Session["CurrentUrl"].ToString(); } }
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
if (Session["brugerId"] != null)
{
//CUT CODE OUT DONT HAVE YOUR DEFINITIONS
Response.Write("brugerid was not null");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//YOU SHOULD SET THE CURRENT URL TO NULL HERE.
string tempUrl = BackToLastPage;
Session["CurrentUrl"] = null;
Response.Redirect(tempUrl);
}
You can also try this, Store the return url in a hiddenfield and only set it if it is not a page postback:
Markup HTML:
<form id="form1" runat="server">
<div>
<asp:Button ID="btnOne" runat="server" OnClick="BackToLastPageBtn_Click" Text="Button One" />
<asp:HiddenField ID="hfPreviousUrl" runat="server" />
</div>
</form>
Code Behind:
private string BackToLastPage //THIS WILL NOW PERSIST POSTBACKS
{
get { return hfPreviousUrl.Value; }
set { hfPreviousUrl.Value = value;}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)//THIS PREVENTS THE VALUE FROM BEING RESET ON BUTTON CLICK
BackToLastPage = (string)Session["CurrentUrl"];
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
Response.Write("brugerID was not null");
}
else
{
//REMOVED FOR TEST PURPOSES
//Response.Redirect("Login.aspx");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
Response.Redirect(BackToLastPage);
}

Session variables set - Page_Load method C#

I tried to link default1.aspx and default 2.aspx.
What I'm trying to do is to display calculated results in default1.aspx when clicking confirm button in default2.aspx.
I run the codes but it doesn't work really.
How can I fix this?
I wrote the codes in default1.aspx below:
protected void confirmBookingButton_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("RoomBookingMain.aspx");
Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
}
and then I wrote other codes in default2.aspx like:
public partial class RoomBookingMain : System.Web.UI.Page
{
static int nbBookingInt = 0;
static int totalRevenueInt = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
bookingNbLabel.Text = nbBookingInt.ToString();
totRevenueLabel.Text = totalRevenueInt.ToString();
string confirmBooking = (string)(Session["confirmBooking"]);
if ((string)(Session["confirmBooking"]) == "confirm")
{
nbBookingInt += 1;
totalRevenueInt += int.Parse(Session["totalBooking"].ToString());
Session["confirmBooking"] = "no current booking";
}
}
Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
Response.Redirect("RoomBookingMain.aspx");
Assign Session before Response.Redirect(). Redirect method will stop the execution at that point.
If you need to pass the data only to next page and if no secure data is involved you can use QueryStrings.

Use a variable in different classes in webforms c#

I am stack in something simple i think.
I have the following code:
public void Button1Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "text/xml")
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
DataSet ds = new DataSet();
ds.ReadXml((Server.MapPath(filename)));
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
StatusLabel.Text = "Only xml files are accepted!";
}
}
public void Button2_Click1(object sender, EventArgs e)
{
}
What i want is the user the execute this code in button2
DataSet ds = new DataSet();
ds.ReadXml((Server.MapPath(filename)));
GridView1.DataSource = ds;
GridView1.DataBind();
My problem is that the variable filename is not available outside
public void Button1Click(object sender, EventArgs e)
Thanks in advance for your help!
Chris
you can persist the variable in the page ViewState like this:
private string fileName
{
get { return ViewState["fileName"] != null ? (string)ViewState["fileName"] : String.Empty; }
set { ViewState["fileName"] = value; }
}
Save the filename into Session or ViewState while uploading a file.
public void Button1Click(object sender, EventArgs e)
{
..
string filename = Path.GetFileName(FileUpload1.FileName);
...
Session["filename"]=filename;
}
Code in Button2 click handler,
public void Button2_Click1(object sender, EventArgs e)
{
if(Session["filename"]!=null)
{
string filename=Session["filename"].ToString();
DataSet ds = new DataSet();
ds.ReadXml((Server.MapPath("~/" + filename)));
GridView1.DataSource = ds;
GridView1.DataBind();
}
Actually here you can have huge amount of variants:
You can get this value from file upload control, juts simply using same method as it was used in Button1Click:
string filename = Path.GetFileName(FileUpload1.FileName);
More correctly, is to store in ViewState as it was told before.
If you want to use this in other pages, just save this to session.

How to add item to Repeater control manually

First of all:
_ddlOptions is drop down list
_selectedOptions is repeater control
and it's just provisional code of my final control.
What I want to do is to get data for _ddlOption on !IsPostBack. There is Add button that enables user to move selected drop down item to repeater control.
It the following way of updating Repeater.Items correct? I found many solution of adding/removing elements manually using DataSource, but here my DataSource is null, as I set it only on !IsPostBack.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_ddlOptions.DataSource = new[] { 1, 2, 3 };
_ddlOptions.DataBind();
}
}
protected void OnAdd(object sender, EventArgs e)
{
var list = new ArrayList(_selectedOptions.Items);
list.Add(_ddlOptions.SelectedItem);
_ddlOptions.Items.RemoveAt(_ddlOptions.SelectedIndex);
_selectedOptions.DataSource = list;
_selectedOptions.DataBind();
}
If you only need to fetch data once and you're going to use viewstate, get the data first time you need it, store it in VS and get it from VS for all future PostBacks.
Example:
public List<int> Data
{
get
{
if (ViewState["Data"] == null)
{
// Get your data, save it and return it.
var data = new List<int> { 1, 2, 3 };
ViewState["Data"] = data;
return data;
}
return (List<int>)ViewState["Data"];
}
set
{
ViewState["Data"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData(Data);
}
}
private void BindData(List<int> data)
{
_ddlOptions.DataSource = data;
_ddlOptions.DataBind();
}
protected void OnAdd(object sender, EventArgs e)
{
var existing = Data;
existing.Add(_ddlOptions.SelectedItem);
_ddlOptions.Items.RemoveAt(_ddlOptions.SelectedIndex);
Data = existing;
BindData(existing);
}
I didn't test this - and its only my first thought but you can build on it from here.
Patrick.
Looks good to me. You just may want to move the decalration for your list outside the onAdd method. As you have it I think it will be reinitialized every time the add button is clicked, so you'll never have more than the currently selected item in your repeater.
You can use a DataAdapter to fill a table in a DataSet.
DataSet ds = new DataSet();
using (SqlConnection conn = YourConnectionFactory.GetConnection())
{
SqlCommand objComm = DBHelper.CreateStoredProc("YourStoredProcedure",
conn);
SqlDataAdapter adapt = new SqlDataAdapter(objComm);
adapt.Fill(ds, TableName);
conn.Close();
}
DataTable dt = ds.Tables[0];
for (int a=dt.Rows.Count-1; a>= 0; a--)
{
// check and insert as necessary
}
YourControl.DataSource = ds;
YourControl.DataBind();
You can also do something like this then,
like rebind Taken from: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx:
Dim values As New ArrayList()
values.Add(New PositionData("Microsoft", "Msft"))
values.Add(New PositionData("Intel", "Intc"))
values.Add(New PositionData("Dell", "Dell"))
Repeater1.DataSource = values Repeater1.DataBind()
Repeater2.DataSource = values Repeater2.DataBind()

Categories

Resources