Time Difference in asp.net C# - c#

I am creating a quiz and I want to calculate the time a user spends on a particular section.I tried by calculating the difference between the page load time and the submit button click but as soon as the button is clicked the page refreshes(AutoPostBack=true) and the difference is zero. Is there a way I can calculate the time.
Below is the code for the following I am using.
protected void Page_Load(object sender, EventArgs e)
{
dtAlgebraLoad = DateTime.Now;
lblTime.Text = dtAlgebraLoad.ToString();
}
protected void btnAlgebraNext_Click(object sender, EventArgs e)
{
dtAlgebraNext = DateTime.Now;
//timeSpan = dtAlgebraNext.Subtract(dtAlgebraLoad);
Label1.Text = dtAlgebraNext.ToString();
//Cal time duration between page and button Click
}

You can store the value in Session but instead of that try to call javascript function on button click and implement the necessary logic in that function and bind the calculated difference to the label by using
document.getElementbyId("Label1")

Since web clients are very disconnected, I would store the Start Date/Time the user enters the section, then a LastActivity date on all subsequent calls when interacting with the section. This will allow you to see when the user last did something and when they started, giving you a duration, otherwise the duration may be left open ended.

Add a hidden field in aspx
<input type="hidden" runat="server" id="hdnStartTime">
I page load
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
hdnStartTime.Value = DateTime.Now;
}
}
Use hdnStartTime.Value to find difference.

Here is a pure JS solution to show the elapsed time (using jQuery to display it). Let this code run on page load. If you bind the result to an input tag, you can also post it back to the server.
The advantage is that the user always sees the currently elasped time.
var start = new Date();
setInterval(function() {
var msElapsed = new Date() - start;
var dateObj = new Date(msElapsed);
var elapsedTime = dateObj.toISOString().substr(11, 8);
$('#elapsedTimeDisplay').val(elapsedTime);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<label for="elapsedTimeDisplay">Elapsed time:</label>
<input id="elapsedTimeDisplay" type="text" readonly="readonly"/>

Try this
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
dtAlgebraLoad = DateTime.Now;
lblTime.Text = dtAlgebraLoad.ToString();
}
}

Related

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 Stopwatch Remaining at 0

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"];
}

Datepicker Value change windows phone 8

I navigated to a page where I want to be able to see the date i got from the Database and to edit that date if it is needed. When I change the date, it always go back to the date that was set by the database previously. How do I solve this. Below are my code:
private void dateData_Loaded(object sender, RoutedEventArgs e)
{
dateData.Value = DateTime.Parse(NavigationContext.QueryString["Date"]);
}
private void dateData_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
{
dateData.Value = (DateTime)dateData.Value;
}
I Think the loaded event is getting called every time you are changing the date and you are assigning the date you are getting from your querystring parameters. So try something like this And check if it works
private void dateData_Loaded(object sender, RoutedEventArgs e)
{
if(NavigationContext.QueryString.ContainsKey("Date"))
{
dateData.Value = DateTime.Parse(NavigationContext.QueryString["Date"]);
NavigationContext.QueryString.Remove("Date");
}
}

Passing session variable from page to page

I'm wondering what is my issue on passing a variable from page to page using asp.net session.
I've stripped the code down to just one text box to see whats going on. I'm just trying to take the value of a text box and display it on a confirmation page. When the button is clicked it transfers me to the second page but there label is blank. Yes my post back url is pointing to the second page.
Here is the button click:
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
}
Here is the page load of the second page:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = (string)(Session["name"]);
}
Unless I've been looking at this to long and missed something. I've already read "How to: Read Values from Session State" from MSDN.
You say that you've set the PostBackUrl to your second page. If you're going to do it that way, you need to use Page.PreviousPage to get access to your textbox. But this is the easiest way:
Firstly, leave the PostBackUrl alone. Setting the PostBackUrl to your second page means that you're telling the SECOND PAGE to handle your button click, not the first page. Hence, your session variable never gets set, and is null when you try to pull it.
This should work for ya.
And yes, you can also do this with a QueryString, but if its something that you don't want the user to see/edit, then a Session variable is better.
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
Response.Redirect("PageTwo.aspx");
}
Then in the second page (You don't REALLY need the ToString()):
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
lblName.Text = Session["name"].ToString();
}
}
EDIT -- Make sure that your button click actually gets fired. Someone can correct me wrong on this, as I do most of my work in VB.NET, not C#. But if you don't specify the OnClick value, your function won't get called.
<asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="submit_Click" />
The code you have posted looks fine, so your problem is probably with setup.
Check this link ASP.NET Session State Overview and pay particular attention to the sections on Cookieless SessionIDs and Configuring Session State.
I don't think you added the session. This is how I have done mine.
First Page
protected void btnView_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbxCheckDates.Items)
{
if (li.Selected == true)
{
lblMessage.Text = "";
string checkDate = lbxCheckDates.SelectedItem.Text;
Session.Add("CheckDates", checkDate);
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('Paystub.aspx','_newtab');", true);
}
}
}
Second Page
protected void Page_Load(object sender, EventArgs e)
{
string checkDate = (string)(Session["CheckDates"]);
//I use checkDate in sql to populate a report viewer
}
So with yours, I think you need..
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session.Add("Name", name);
}
I think what you have in the second page should work, but if it doesn't, add ToString() to it like..
lblName.Text = (string)(Session["name"]).ToString();
Let me know if this helps!
Are you doing a redirect after setting the session variable on the first page, if so you it will not work correctly (unless you know the trick). Checkout this article on making it work. Basically, the way to make this work is to the overload redirect method.
Response.Redirect("~/newpage.aspx", false);
The false parameter prevents .net from terminate processing on the existing page (that actually writes out the session state)
For Second Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value"] != null)
{
Label1.Text = Session["value"].ToString();
}
else
{
Label1.Text = "Sorry,Please enter the value ";
}
}
You can use Server.Transfer() instead of Response.Redirect()
For first page, use this:
protected void Button1_Click(object sender, EventArgs e)
{
string value = TextBox1.Text;
Session["value"] = value;
Response.Redirect("~/Sessionpage.aspx");
}

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