How to create a timer for counting reservation time in asp.net? - asp.net

I've created a hotel room reservation website. Assume that a person who wants to reserve a room has 30 mins time to do that and after 30 mins the site would stop the reservation session for him; during this reservation he would pass several web page for filling the information.
Is there any way to create a timer which can calculate 30 mins during SEVERAL PAGES?

A timer would always get re-initialized when the user would reload the page after submitting the page unless you are having a Single page application.
Another simple way would be to store a cookie with the date time value when the user started filling in the forms (or what so ever is the initial stage). You can create it this way,
// Set the cookie
HttpCookie cookie = new HttpCookie("date");
// Add the value
cookie["dateValue"] = DateTime.Now.ToString();
// Add the cookie
Response.Cookies.Add(cookie);
Then you can check this cookie and (after successful casting to DateTime object) you can check whether user has some time in his 30 minutes trial period or whether he is late. You can get the cookie on the server-side using this code,
// This check would minimize one error
if(Request.Cookies["data"]["dateValue"] != null) {
var time = Convert.ToDateTime(Request.Cookies["data"]["dateValue"]);
} else {
// Maybe cookie got removed.
}
This way you can set this functionality in your ASP.NET web application.

Related

stop or pause counting user's session duration depending on Visibility API

I'm using userId feature on google analytics to track users event.
I want stop or pause user's lifetime (or maybe it is called session duration time), depending on:
(<any>document).addEventListener('visibilitychange', function () {
if ((<any>document).hidden) {
// sendEvent : hidden
// stop or pause counting user's session
}
else {
//sendEvent : visible
// sendEvent : continue lifetime time counting on same session
}
}
To resume I don't want count time user is on site if user is hidding the page, i want consider it as he's is not on site.
You need to send a hit to Google Analytics with session control parameter set to end. I suppose detecting a document 'blur' event and sending a relevant hit to analytics would work for you.
Here is the doc on session control https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sc

Asp .net session variables update by thread is not getting reflected in Session

In my page1.aspx i am generating a report from database by using thread.
//on button click
Hashtable ht = (Hashtable)Session["ReportParam"];
ReportThreadClass rth = new ReportThreadClass(ht);
Thread thread = new System.Threading.ThreadStart(rth .Run);
thread.Start();
In my thread class's rum method i am updating values in Hashtable that how many pages i have created.
//in thread' method
public virtual void Run()
{
int pagecount=0;
while(done)
{
//loading data from DB and generating html pages
ht["Total_Pages"] = pagecount;
}
}
At my Page2.aspx i am reading values from Session Variable
Hashtable ht = (Hashtable)Session["ReportParam"];
int TotalPages = (int) ht["Total_Pages"];
When i run above code in InProc mode every thing is working fine i am getting updated values from session.
Because every thing is stored in static variable, and ht is referenced by Session so it automatically get updated in session (HashTable not needed to reassign it to session back).
But when i run code in State server (OutProc mode) It need to store session data in different process by Serializing Hash-table.
But the value of Total_Pages is not getting updated in Page2.aspx even after Thread run completely.
So is there any event or method which get fired to store all updates in session variable to State-Server , if yes then pls tell me . if not then pls suggest me some idea to get updated value in page2.aspx.
I would explictely SET and GET SessionState like so:
In your thread Run
// no complex object like hastable, just a plain value...
Session["pageCount"] = pageCount;
In your page2.apsx:
var pageCount = (int) Session["pageCount"]??0;
The reason your report thread is not updating it's session value when using out-of-proc sessionstate is because the session has no way to detect the hashtable has a changed value, therefor it doesn't update the underlying storew with the serialized version of the hastable. When you explicity store one immutable object it will persist one it's value changed;
As the session might already be gone when your thread finishes a begtter option is to get hold of a reference to SqlSessionStateStore and call SetAndReleaseItemExclusive. Ultimately you might want to have an overloaded SessionStateProvider that can handle your scenario.
In Out Proc Mode Session is saved after some event so if your thread is updating your session variables then it won't persist in storage.
If u are using Inproc Mode then session store in Static Dictionary so if your thread updating it, u will get updated value to any page.
So u have two solutions for this situation
Use inProc mode
Maintain a dictionary in your thread class with key as Session id and value is your hash-table, So if page2.aspx wants to read value of hash-table then it will pass his session id to method and which will return required value.
Less efficient but I'd probably just ping the database for the page count on Page2.
Or create a separate session value for the page count on Page1, at the same time as doing everything else. (EDIT: Nevermind the second part, that's what Rene suggested below).

Can ASP.NET session remember objects?

I start my question from an example. I think it will be more simple.
What i want to do, is send REQUEST_1 from my Android device to asp page, which is waiting for JSON request, for example {"Year":2012}. Page takes this json string, and saves it to the object (example arraylist).
After a minute, I send REQUEST_2 to the same ASP page with data: {"Command","WhatIsCurrentYear"}, and I then want to get response: {"Year",2012} (which should still be stored in the arraylist).
Is there a chance to do this?
Session has a property Session.TimeOut. Session expires after the time expires. By default in asp.net session Timeout time is 20 mintues Also if user closes the browser session also expires if it's mode is InProc ( Cookies or without cookies ). In InProc session provider IIS could recycle the application pool at any moment (period of inactivity, certain CPU/memory thresholds are reached, ...) without warning voiding the contents of this session.
Variables are initialized on every post back, so if previously you had saved data in an array list object it is lost. To save data during postbacks you can use ViewState.
I created a class for accessing the session
public static IPerson User
{
get
{
if (HttpContext.Current.Session == null || HttpContext.Current.Session[UserConstant] == null)
return new Student();
return (IPerson)HttpContext.Current.Session[UserConstant];
}
set
{
HttpContext.Current.Session[UserConstant] = value;
}
}
You can replace IPerson with whatever object you want.

Asp.net Membership Logged in Users list

I used following in my application to find the list of logged in user. It gives the list of logged in user but when i close the browser and clear the browser history, it shows the user isonline status true. Please can any one tell me where i am wrong?
When User signIn am validating user and redirect to url,
if (user != null)
{
if (Membership.ValidateUser(user.UserName, txtUserPassword.Text))
{
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
}
}
List of logged in user code
MembershipUserCollection allUsers = Membership.GetAllUsers();
MembershipUserCollection filteredUsers = new MembershipUserCollection();
bool isOnline = true;
foreach (MembershipUser user in allUsers)
{
// if user is currently online, add to gridview list
if (user.IsOnline == isOnline)
{
filteredUsers.Add(user);
}
}
MembershipUser.IsOnline is not a very accurate check of whether or not a user is online. From the MSDN, a user is determined to be online:
if the current date and time minus the
UserIsOnlineTimeWindow property value is earlier than the
LastActivityDate for the user.
This means the user could log in and then log out 10 seconds later and still be considered online.
So in your case you were logging in, checking the count, logging out, closing the browser, clearing cache, etc., but the user's LastActivityDate still fell within the assumed window described above. What you can do is:
shorten the time window (which can produce some unwanted side
effects)
when logging the individual out, update their LastActivityDate to a
time that would make the above check invalid (e.g., the current time
UserIsOnlineTimeWindow)
update the LastActivityDate manually at certain key points (e.g.,
if your site is bookstore, maybe updating the LastActivityDate when
they add an item to the cart)

how to display something one time every hour in asp.net?

how to display something one time every hour in asp.net ?
example for show messeage in Begining hour one time only?
i use for asp.net ajax timer control?
protected void Timer1_Tick(object sender, EventArgs e)
{
MessageBoxShow(Session["playsound"].ToString());
Session["playsound"] = 1;
}
but alway null?
---------------------------
Message from webpage
---------------------------
Object reference not set to an instance of an object.
---------------------------
OK
---------------------------
Sounds like your session might have timed out. If, between AJAX calls, your session expires on the server, then the ToString invocation may be operating on a null reference:
MessageBoxShow(Session["playsound"].ToString());
This would appear to coincide with what the AJAX client script is attempting to tell you.
This could also be the result of Session["playsound"]; being uninitialised.
The default session expiry duration for ASP.NET is 20 minutes, which you should be mindful of if you're executing an hour long timer.
You can use the
window.setInterval
method
It calls a function repeatedly, with a fixed time delay between each call to that function.
intervalID = window.setInterval(func, delay[, param1, param2, ...]);
Read more info
window.setInterval
On the client?
The only way I know to do this is via a javascript timer.
One way of doing this could be to have an session variable with NextTime to show the item on the page. If its null one could display the item now (or get the NextTime scheduled). On every page refresh, if the current time is after the Next Time, show the item and reset the NextTime session variable to the next Hour.
This would only work if the user is navigating the site and the page is being refreshed.
You can use the javascript variable window.name which keeps its value between page refreshes.
You could store a 'last checked time' in there and compare it with the current time.
If the user navigates to another site and that site clears this variable then your back to square one.
An easy answer would be to use a small cookie to store the original time and then query it every so often (~5 min?) this way the session won't run out and you're not SOL if the user leaves the page (if that's what you want).
DISCLAIMER: I haven't really dipped my toes into AJAX yet even though I've been programming ASP.net all summer, so excuse me if this isn't possible.

Resources