ASP.NET Stopwatch Remaining at 0 - c#

So, as part of an assignment I am trying to roughly calculate the time taken for a transaction to be reviewed and completed in an ASP.NET Web Forms project using CSharp.
In my ASPX page, I am showing the details of the objects in the cart.
And there is a button which confirms the checkout and completes it.
What I need to calculate is the time since the page loaded, till the checkout was confirmed.
Here there are two events: page_load and checkoutbutton_click
So in the code behind file I am
public partial class CheckoutReview : System.Web.UI.Page
{
public Stopwatch sw = new Stopwatch();
protected void Page_Load(object sender, EventArgs e)
{
sw.Start();
//... code
}
protected void checkoutbutton_click(object sender, EventArgs e)
{
//...code
sw.Stop();
// in the database i am then storing the elapsedMilliSeconds of the stopwatch
}
The problem however is that with this code the elapsed time is remained 0 all the time.
If I put the same stopwatch however in the checkoutbutton_click() the stopwatch works fine.
Can someone kindly explain what I am doing wrong here?

Each time the page is posted back to the server, a new instance of the class CheckoutReview is being created... so what you're seeing is the time between the creation of the class on the post-back and the event handler.
You have to remember that each request to the server (whether it's the original page request, or a post-back) is an individual call to the server. Things like Session and ViewState exist to allow you use data between those requests.
I would recommend you store the current time in the ViewState of the page on the initial load, and then check the TimeSpan difference in the event handler...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Only store on first visit to the page
ViewState["pageLoadTime"] = DateTime.Now;
}
}
protected void checkoutbutton_click(object sender, EventArgs e)
{
TimeSpan diff = DateTime.Now - (DateTime)ViewState["pageLoadTime"];
}

Related

How to Delay Calling a function After full page loaded on aspx with c#

Below is my simple source code, I'm just trying to call that function after page load, but what is happening right now is: it calls that function before page load. Page loads for 5 seconds and, after that, it displays label execution.
protected void Page_Load(object sender, EventArgs e)
{
display();
}
void display()
{
Thread.Sleep(5000);
Label3.Text = "done";
}
You should read this document about ASP.NET Page Life Cycle. It actually says what you are trying to do is not possible.
Every code you write in the server side is going to run before the browser renders the page. That means you can not call a function after the browser renders the page, unless you use other approach.
The simplest way you can achieve this is using Javascript and an Ajax call or by using a Timer, which opens a new thread different from the main execution thread. Although, I do not recommend open new threads, because you will lose the control over the execution flow and in a webpage you could end having hundreds of open threads.
Below Code is Working
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Interval = 2000;
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label3.Text = "done";
}

Why can't I get the value from textbox?

I've just started learning ASP.NET and I'm facing a problem with getting textbox values. I want to do a simple calculator with only 4 basic operations but what happens is that after I click the + sign and click Go, I see that I didn't store the first number at all. Second number is fine though. Here is a sample of my code.
public partial class deafult : System.Web.UI.Page
{
public TextBox output = new TextBox();
public double temp,tempAdd, calc;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
tempAdd = Convert.ToDouble(output.Text);
output.Text = String.Empty;
}
//User enters another number after clicking Add button then clicks Proc
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
calc = tempAdd + temp;
output.Text = calc.ToString();
}
}
I debugged and tempAdd is always 0 but I get the number in temp. temp variables and calc is defined public.
You essentially have the problem with all of your variables being re-initialized on load of the page. Unlike winforms, web is stateless.
There are ways of persisting state between refreshes, however. The most obvious choice for your application would be to only go to the server once with the both values and what you want to do with them. ie One button click.
However, for personal edification, it may be worth looking up ViewState. This allows you to store values in an array of sorts and retrieve them even after a refresh.
There are also Session and Application level arrays in ASP.NET that work in similar ways.
Every time you call the page (by events) all your properties is initialized.
Try to do all your logic in one event or store your properties in manager / service / db.
In web (Asp.Net) on every postback properties will get cleared, try to use ViewState or Session variables to hold these values. Refer Asp.Net State Management concepts from MS.
Hope this may help you.
Web controls are State less so you should user session sate to hold the first value then do your stuff...
Ex:-
protected void btnAdd_Click(object sender, EventArgs e)
{
Session["tempAdd"] = output.Text;
output.Text = String.Empty;
}
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
string oldval=Session["tempAdd"] != null ?Session["tempAdd"].ToString() :"";
if(oldval!="")
tempadd=Convert.ToDouble(oldval);
calc = tempAdd + temp;
output.Text = calc.ToString();
}

ASP.NET get count of logged-In User

I would like to display number logged-In users count in my page. I implemented this using Application Variable, but the problem is its not decreasing the count when user close the browser.
First i opened the web application using IE the count became 1, then i opened the app using firefox the count became 2. When i close any one of the browser the count not getting decrease.
void Application_Start(object sender, EventArgs e)
{
Application["UsersCount"] = 0;
}
void Application_End(object sender, EventArgs e)
{
}
void Session_Start(object sender, EventArgs e)
{
if (Application["UsersCount"] != null)
{
Application.Lock();
Application["UsersCount"] = ((int)Application["UsersCount"]) + 1;
Application.UnLock();
}
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["UsersCount"] = ((int)Application["UsersCount"]) - 1;
Application.UnLock();
}
Any other way to achieve this?
Thank you.!
This is not so simple to implement. To be logged in doesn`t actually necessary mean that user doing something. You should set some timeout (probably the same as auth cookie life-time) and check the last activity mark of each user. Special DB table is good for that, but if you want quick and dirty solution:
You can keep IDictionary<Guid, DateTime> which you will update on each request. Guid is for UserID, DateTime for the last activity. On each request (probably somewhere in MasterPage code behind) you update this dictionary with current DateTime. Then you can check count of IDs with DateTime less than timeout.
IDictionary<Guid, DateTime> userActivityLog = Application["UserActivityLog"] as IDictionary<Guid, DateTime>;
DateTime timeout = DateTime.Now.AddHours(-1); // one hour timeout
int loggedCount = userActivityLog.Count(x => x.Value > timeout);

How to refresh browse from thread ? C#

I have an application that populates a grid with information from a SELECT. After all the filling, I gather a playlist (songs) and reproduce in the same sequence. After this whole process, I need to run it again. I've used the TimerPicker LOAD_PAGE to give a 1 in 1 minute, but can not run from time to time. I need to force a page_load at the end of execution of the process.
protected void Page_Load(object sender, EventArgs e)
{
LoadGrid();
Thread thrPlayMusic = new Thread(ThreadPlayMusic);
thrPlayMusic.Start();
}
public void ThreadPlayMusic()
{
music.PlaySound();
}
My application is ASP.NET.
Could someone help me?
You can use Response.Redirect(Request.RawUrl) or Server.Transfer() to "refresh" the page.
So for your case, use join:
protected void Page_Load(object sender, EventArgs e)
{
thrPlayMusic.Start();
thrPlayMusic.Join();
Response.Redirect(Request.RawUrl)
}

System.Threading.Timer example to run and display seconds until you click a button

I am having some issues creating an asp.net page using C#
When you first click a button it starts the display of seconds via a label control.
When you click the button again the seconds stop.
Currently my code does just prints 0 and stops:
System.Threading.Timer Timer;
bool endProcess = false;
int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
Timer = new System.Threading.Timer(TimerCallback, null, 10, 10);
Label1.Text = i.ToString();
i++;
}
private void TimerCallback(object state)
{
if (endProcess == true)
{
Timer.Dispose();
return;
}
}
public void Button1_Click(object sender, System.EventArgs e)
{
endProcess = true;
}
You must set the label.text=i.toString(); in timecallback function not in page_load
For this to work in ASP.NET, you should not use System.Threading.Timer, because this runs on the server side and you need to have the client side updated periodically. You have afew options for a WEB based application.
Keep in mind that you do not push UI updates to a web browser, the web browser needs to pull or request the update. So, a naive solution would be to have the browser periodically do a postback to the web server to get the updated text for the label. Not a good solution, but I share this as the basic premise of the concept.
I think the best option would be to this entirely on the client side using a javascript timer and updating the DOM element with the new value. Take a look at the second and third example on this page
http://www.w3schools.com/js/js_timing.asp

Categories

Resources