Using Cache ASP.NET - c#

How can I use Cache in ASP.NET which is accessible by all users not just a specific user context while having a specific key of this cache removed automatically when a user closes the browser window or expires (like a session object) ?

Cache is accessible to all users, you can set it to expire after a period of time:
Cache.Insert("key", myTimeSensitiveData, null,
DateTime.Now.AddMinutes(1), TimeSpan.Zero);
You may remove the cache entry whenever a session expires by implementing the global.asax's session end event
void Session_End(Object sender, EventArgs E)
{
Cache.Remove("MyData1");
}
See this for more details on Cache
Edited:
Regarding your question on how to react when the user closes its browser, I think that this is not straightforward. You could try javascript on the client side to handle the "unload" event but this is not reliable since the browser/client may just crash. In my opinion the "heartbeat" approach would work but it requires additional effort. See this question for more info.

You'll have to use the Session_OnEnd() event to remove the item from the cache. However, this event will not fire if the user just closes the browser. The event will only fire on the session timeout. You should probably add a check to see if the item has already been removed:
public void Session_OnEnd()
{
// You need some identifier unique to the user's session
if (Cache["userID"] != null)
Cache.Remove("userID");
}
Also, if you want the item in the cache to stay active for the duration of the user's session, you'll need to use a sliding expiration on the item and refresh it with each request. I do this in the OnActionExecuted (ASP.NET MVC only).
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Put object back in cache in part to update any changes
// but also to update the sliding expiration
filterContext.HttpContext.Cache.Insert("userID", myObject, null, Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(20), CacheItemPriority.Normal, null);
base.OnActionExecuted(filterContext);
}

Related

Redirect from Global.asax

HttpContext.Current.Response.Redirect("~/default.aspx");
When i use this code in session_end in global.asax
error to me:
Object reference not set to an instance of an object.
why?!
Session_end is not an event that gets called by the user of your application, it's something that gets called by the server when a session times out. So when you try to access HttpContext, it is null because there is no HttpContext to access (no user who is currently performing some kind of interaction with your site).
Your attempt to redirect a non-existing HttpContext will always fail no matter what you do.
When the event SessionEnd is raised the Request and then the Response are null.
HttpContext.Current.Response //this is null
This is by design: Session ends not during a request but when the session timeout
It usually (default config) happens 20 minutes after the last request.
Since there is no request there is also no response.
You need to understand better how Asp.net Session State works
Anyway if you want to redirect the user to a page if the Session is expired you can check for one of your variables stored on session:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["YOUR_VAR_NAME"]==null)
{
Response.Redirect("~/default.aspx");
}
}
Session_End is fired internally by the server, based on an internal timer. Thus, there is no HttpRequest associted when that happens. That is why Response.Redirect or Server.Transferdoes not make sense and will not work.
I hope the above information will be helpful

How do I know which user's session id has been expired (and which users are online?)

I am developing an online chess game. After a user presses the login button, I save userid in a session variable:
Session["userID"] = userId.Text;
After assigning the variable, the user is transferred to another page.
There is a possibility more then one user is online at a time. Let say three user are online at a time and in session variable one user contain "1" userId, next contain "2" and so on.
If one of the user's Session Id expires for some reason, how do I know which user's session expired?
The reason is I want to show the other users that this particular user is not online anymore.
How do I know which user session variable expired?
You can subscribe to the SessionStateModule.End event:
public class KyuApplication : System.Web.HttpApplication
{
public override void Init()
{
SessionStateModule session = Modules["Session"] as SessionStateModule;
if (session != null)
{
session.Start += new EventHandler(Session_Start);
session.End += new EventHandler(Session_End);
}
}
private void Session_Start(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Session_Start");
}
private void Session_End(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Session_End");
}
}
Example from: http://johnllao.wordpress.com/2009/06/05/session_start-and-session_end-event-from-custom-httpapplication/
The reason is I want to show the other users that this particular user is not online anymore.
You approach is unnecessary. The Asp.Net membership framework provides this functionality for you so you don't have to build it yourself. You can use MembershipUser.IsOnline to do this for you.
Example from MSDN:
MembershipUserCollection users;
public void Page_Load()
{
users = Membership.GetAllUsers();
if (!IsPostBack)
{
// Bind users to ListBox.
UsersListBox.DataSource = users;
UsersListBox.DataBind();
}
// If a user is selected, show the properties for the selected user.
if (UsersListBox.SelectedItem != null)
{
MembershipUser u = users[UsersListBox.SelectedItem.Value];
EmailLabel.Text = u.Email;
IsOnlineLabel.Text = u.IsOnline.ToString();
LastLoginDateLabel.Text = u.LastLoginDate.ToString();
CreationDateLabel.Text = u.CreationDate.ToString();
LastActivityDateLabel.Text = u.LastActivityDate.ToString();
}
}
Here are some additional blog posts that discuss this in more detail and describe how to set it up:
http://dotnetslackers.com/articles/aspnet/tracking-user-activity.aspx
http://blog.dreamlabsolutions.com/post/2009/07/13/ASPNET-Membership-Show-list-of-users-online.aspx
Session data is meant to be private to the user and is not meant to be accessible to the rest of your application (that is, outside the user's context). That means that doing what you want using the session is going to be hard and awkward.
A better alternative would be to track user activity in a separate datastructure and keep that in the web server's memory (using a static variable or the System.Web.Caching namespace) or in the database.
For every user you can save session information in remote storage (database for example) with expiration date (that must be MORE than the session expiration date from application configuration) and userID binding and after user is making some action in your application you can change the expiration date by adding some value. So that in this case you always have the list of not expired sessions, controled by you.
With Session variable - you can see session information just about the current request from the client. So that using just this variable you sure can't see other users' sessions, that would be just unsecure.
You can use the SessionStateModule.End Event to catch that.

ASP.NET sessionID will not update

I click on refresh button which should restart session:
protected void btnRefresh_Click(object sender, EventArgs e)
{
HttpContext.Current.Session.Abandon();
HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
mycookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(mycookie);
LblSessionID.Text = HttpContext.Current.Session.SessionID+
" test btnRefresh_Click";
LblIsNewSession.Text = Session.IsNewSession.ToString();
}
But when the button is clicked, the SessionID value in LblSessionID still displays the old value but another label LblIsNewSession will show it as true for IsNewSession. The LblSessionID will then reflect the actual SessionID value when I use asp.net control (like dropdown) that has autopostback="true" and from there SessionID sticks around.
I do use global.asax
Any idea why LblSessionID isn't behaving as it should and is waiting for next postback to start reflecting actual value?
When I launch the web application, the problem is the same - LblSessionID show different value and then change after first postback and stays the same from there.
That's the way it works - If you Abandon the session it won't reflect that until the next Request. It makes sense if you think about it...
Say you have a user that accesses your site and gets a Session ID of 123 (not reflective of an actual value, I know). When you click your button to get a new Session ID, the user's request is from the old Session, and that is the value that is reflected during that Request. Once the session is reset (or abandoned or whatever), the user gets a new Session ID of 321 and subsequent Request's will then reflect that new session ID.
SessionId is not reliable unless you actually store something (anything) in the session.
try
Session.RemoveAll();
Session.Clear();
It is not your code, it is a documented behavior:
"The Abandon method sets a flag in the session state object that indicates that the session state should be abandoned. The flag is examined at the end of the page request. Therefore, the user can still use session objects after you call the Abandon method. As soon as the page processing is completed, the session is removed."
(source: http://support.microsoft.com/kb/899918)
The Abandon() method flags the session collection for clearing at the end of the request, it does not actually clear it immediately.
You can either call the RemoveAll() or Clear() methods for instant deletion of the objects, or issue a Response.Redirect call to the page itself and re-test for the existence of the data.

Is this possible to clear the session whenever browser closed in asp.net?

In my asp.net application, i want to clear the session whenever my browser closed or my tab (if my browser containing multiple tabs)closed.
Please guide me to get out of this issue...
Short version, No.
There's no solid way of a server detecting if the client has closed their browser. It's just the nature of web development's asynchronous pattern.
Long version, if it's really, really important to you;
Put a bit of javascript in the page that sends a regular post to your website in the background and set up a serverside agent or service that disposes of the sessions if it doesnt receive these regular "heartbeat" signals.
You can put a javascript postback onto the page's unload() event but dont rely on it, it doesnt always fire.
This happens by default whenever you close your browser, and that's not just for ASP.NET. It's for most server-side programming languages that have a session state. Basically, any cookie that is added that doesn't specify an expiration date, will be deleted when the browser is closed.
Where this doesn't apply, is when you close a tab, which is something you will not have any control over because the tab close event will not get sent back to the Web server.
You can try to do that with javascript. Check it at:
http://www.codeproject.com/Tips/154801/How-to-end-user-session-when-browser-closed
Alternatively you can check you previous session state on every new browser opening and can Session.clear() or Session.abandon() the previous session.
this will make sure that every time you start application you will get new session.
use BasePage in your .net application.
Check the session.sessionid on basepage load.
More Inforamtion how to detect new session in basepage. BasePage.Session.Link
Hope this helps
regards
Shaz
public class BasePage : Page
{
protected string mySessionId;
private CurrentUser _currentUser;
public CurrentUser _CurrentUser
{
get { return ((CurrentUser)HttpContext.Current.Session["myCurrentUser"]); }
set { _currentUser = value; }
}
protected override void OnLoad(EventArgs e)
{
if (Session["myCurrentUser"] != null)
{
if (_CurrentUser.ProUser)
{
mySessionId = Session.SessionID; // it means New Session
}
if (!mySessionId.IsNullOrDefault() && mySessionId != Session.SessionID)
{
Session.Abandon(); //Abandon current session and start new one
}
}
}
}
I think cookies can better meet your requirement here for session management.
it means that session data should not be stored on the server and
should be with your call, so that you don't have to worry about
clearing the data on server.
Yes.First of all Browser automatically clear session when browser is closed. you can try to capture browser close or tab close event in browser using javascript function like on before unload and on unload. Mostly onbefore unload event captures browser close event in chrome, Firefox, IE 11.
You can use Session_End event of Global.aspx
//For Specific Session
Session.Remove("SessionName");
//All the Session
Session.Abandon();

How can I handle forms authentication timeout exceptions in ASP.NET?

If the session has expired and the user clicks on a link to another webform, the asp.net authentication automatically redirect the user to the login page.
However, there are cases when the user does not click on links to other webforms. For example: edit link in gridviews, when using AutoCompleteExtender with textboxes and the application attempts to get the information, and basically, in every case when a postback is done and the event is not automatically handled by the asp.net authentication.
What is the best way to handle these exceptions?
UPDATE: I have just modified the question title: forms authentication timeout, instead of the initial session timeout. Thanks for making me aware of this difference.
UPDATE: I have just created a new question with the specific problem I am facing: How to handle exception due to expired authentication ticket using UpdatePanel?. Surprisingly, I have not found much information about it. I would really appreciate your help.
This is why many systems include timers on the page to give approximate timeout times. This is tough with interactive pages. You really need to hook ajax functions and look at the return status code, which is a bit difficult.
One alternative is to use code based on the following which runs early in the page lifecycle and perform an ajax redirect to a login page. Otherwise you are stuck trying to intercept the return code from ajax and in asp.net where the ajax is done 'for you' (ie not a more manual method like jQuery) you lose this ease of detection.
http://www.eggheadcafe.com/tutorials/aspnet/7262426f-3c65-4c90-b49c-106470f1d22a/build-an-aspnet-session-timeout-redirect-control.aspx
for a quick hack you can try it directly in pre_init
http://forums.asp.net/t/1193501.aspx
Edit
what is wanted are for forms auth timeouts, not session timeouts. Forms auth timeouts operate on a different scale than session timeouts. Session timeouts update with every request. Forms auth tickets aren't actually updated until half of the time goes by. So if you have timeouts set to an hour and send in one request 25 minutes into it, the session is reset to an hour timeout, the forms auth ticket isnt touched and expires in 35 minutes! To work around this, sync up the session timeout and the forms auth ticket. This way you can still just check session timeouts. If you don't like this then still - do the below and sync up the timeouts and then parse the auth ticket and read its timeout. You can do that using FormsAuthentication.Decrypt - see:
Read form authentication cookie from asp.net code behind
Note that this code requires that upon login you set some session value - in this case its "UniqueUserId". Also change the login page path below to fit yours.
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
//Only access session state if it is available
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
//If we are authenticated AND we dont have a session here.. redirect to login page.
HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authenticationCookie != null)
{
FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(authenticationCookie.Value);
if (!authenticationTicket.Expired)
{
if (Session["UniqueUserId"] == null)
{
//This means for some reason the session expired before the authentication ticket. Force a login.
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx", true);
return;
}
}
}
}
}
If you're using Forms Authentication, the user will be redirected to the login page when the Forms Authentication ticket expires, which is not the same as the Session expiring.
You could consider increasing the Forms Authentication timeout if appropriate. Even to the extent of using a persistent cookie. But if it does expire, there's no real alternative to redirecting to the login page - anything else would be insecure.
One way to deal with Session timeouts is to use Session as a cache - and persist anything important to a backing store such as a database. Then check before accessing anything in Session and refresh if necessary:
MyType MyObject
{
get
{
MyType myObject = Session["MySessionKey"] as MyType
if (myObject == null)
{
myObject = ... get data from a backing store
Session["MySessionKey"] = myObject;
}
return myObject;
}
set
{
Session["MySessionKey"] = value;
... and persist it to backing store if appropriate
}
}
If you're using a master page or a base page, I would add some logic to one of the events in the page lifecycle to check whether the session is new:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.IsNewSession)
{
//do whatever you need to do
}
}

Categories