How to cache user's profile info (update when profile changed)? - c#

I have a UserInfo object that is generated on each page_prerender event. This object is generated from the db and contains general info and permissions info. Since this object is always the same for each user - unless the user updates his profile - I'd like to cache it.
Does anyone know how I would do so per user (as each user of the web app has a different userinfo object) and get the new values into the cache when a profile is updated.
Any help is great! thanks!

Store the object as a session object in the session start event
this.Session["UserInfo"] = myUserInfo;
Update this object when the user updates there profile.

May be it worth to add issue a cookie for each user. If you will stop the application the session may be lost

Related

Creating unique sessions per user on Webforms ASP.net

We are currently developing a simple system on ASP.net which are going to be used by users simultaneously. What I want to happen is to get each users' Name (or any other useful info) from a SQL table every time they log in to the system and use this data all throughout (Note: this data should be unique per user).
Now my question is, what is the proper approach on this kind of scenario to give unique variable/session per user? And what if I want to make this variable a global one?
Sample Scenario: A doctor logs in to the system and the code behind gets his name from the table and prompts the data on the homepage - "Welcome Doctor John!" (assuming his name is doctor John. Another user logs in to the system, gets his name and prompts respectively, now the conflict arises if the first user - John, refreshes the page and this is the conflict that I want to avoid.
Any article that I could read on with regards the matter? Any help would be much appreciated.
Disclaimer: I am still a beginner when it comes to ASP.net so my apologies for such simple question.
Session is where you will keep this information. It will be unique for each user. Read more about it at: ASP.NET Session State Overview
Just remember, that Sessions are maintained on Server for each user. They are costly. So if you keep too much data in your session then you may end up claiming more resources on the server.
Consider the following example where you retrieve your UserInfo in an object from Database.
UserInfo userInfo = GetUserInfoFromDB();
To Store information in Session:
//once user is authenticated
//store session
Session["UserInfo"] = userInfo;
To Retrieve information:
UserInfo currentUserInfo = Session["UserInfo"] as UserInfo;
if(currentUserInfo != null)
{
//info found
// assign lable Text currentUserInfo.UserName etc
}
You may see: Exploring Session in ASP.NET - Code Project
Just use the Builtin Session Management. It is unique to the user.
The Session Management stores, by default, a cookie at the users browser
to identifiy them. Only a Session Id is stored at the users browser and the other information, in your case the name, is stored on the server. You can define a Session Database for example if you have multiple webservers and want a single point to store the data.
If you have a single webserver it is very easy to use out of the box.
Set a Session variable.
Session["UserName"] = yourUsernameVariable;
Retrieve a Session variable.
var userName = Session["UserName"];
Here are some tutorials.
A Beginner's Tutorial on ASP.NET State Management
Exploring Session in ASP.NET
ASP.NET Session State Overview

ASP.NET Kill Session By Id

My application has a control of User Permissions, because not all users can access full website. At this moment, all those permissions for an specific user are stored in his session, 'cause It would be a problem for me to search at Database every Post Back.
The problem is that when I remove a permission, user can still access the page, and only when he closes the browser, the update take effect.
Is there a way to Kill an specific Application Session by the ID, forcing user to Log in again?
"Is there a way to Kill an specific Application Session by the ID, forcing user to Log in again?"
No. You can only access the Session object of the user doing the current request (i.e. yourself), not other users Session objects.
So, you need to store the id of the user somewhere else, for example in a static collection. When the user makes the next request you can check if the id is in the collection, and update the permissions or log out the user.
Another alternative would be to keep the permission objects of all currently logged in users in a static collection as well as in their Session variable. That way you would be able to change the permission object without accessing the Session object of that user.
Using static variables in a web application of course comes with the usual precautions. As multiple threads can access it, the access has to be synchonised. Also, as Alexei Levenkov pointed out, if you have multiple servers you have to keep the data synchonised between the servers.
You can write Session.Abandon(); or Session.Clear();
or Session.SessionID[int index];
store the particular user session value in this and then use Session.Abandon(); and Session.Clear();
For killing a particular session try using Session.Remove("key");
To remove a particular piece of Session, then use Session.Remove(), like this:
Session.Remove("YourKey");
Note: This removes the value and the key from Session, while you may see people use Session["YourKey"] = null; that will only remove the value, but leave the key. This may or may not be what you want, but just wanted to point out the distinction.

Options for storing user information while logged in

What are some options in regards to maintaining user data while they are logged into my mvc4 site? I am building off of the Internet Application template and right now I am using User.Identity.Name to get the logged in user's username that they used to login with. I'd like to be able to also store and access several other pieces of information about the user across every page on the site. Can I still use User.Identity somehow and apply other attributes to it? I started building a ProfileModel that I could pass to views, but then I don't believe I would be able to pass other models to those views, not sure.
I'm open to suggestions as far as persistent user data, and thank you for any help.
EDIT 1: When I say persistent, I mean while they are logged in, the data itself is already stored in an external database, so I won't be doing any writing of this information, simply pulling it from the database, then holding onto it for the duration of them being logged in.
You'll want to leverage Session for that. Consider the following code:
Session["Profile"] = profileObj;
or maybe you just want to store a string:
Session["SomeSetting"] = value;
What you need to store in Session is unclear, and effectively irrelevant, you can store anything. You can access the Session from any Controller.
Then later on you can get the value out like this:
var profile = Session["Profile"];
// if the profile variable is null then it doesn't exist in Session yet
In response to #AaronLS, Session lasts the duration of the IIS session that's created when the user first accesses the site. Do keep in mind that these sessions are reset if inactive for a period of time (I believe the default IIS timeout is 20 minutes) so you'd want to leverage the null return value to know that you need to redirect the user to the login page to login again.

Profile variables in asp.net tracking session with login control?

I have been making a web site with a cart in asp.net using visual studio 2010. My question is concerning the Profile variable and Login Control.
I followed a pretty straight forward tutorial to add a cart to my site.
1: Shopping Cart Example
As you can see in the shopping cart tutorial, the author used a Profile to keep track of the cart.
When I was making this, I had expected the cart to stay the same with each different user login since we were using a profile and not a session variable. Fortunately, the cart would in fact reset as I logged in as different users with the login control.
So my question is, how is the Profile keeping track of the cart for each user. I'm almost certain that the login-control does not set a session variable, so I don't think the Profile object is auto-detecting a different user from the login-control... is it?
Please help me understand this, the author isn't quite clear.
Thanks a lot!
Basically the way it works is by using the authentication information to identify the user. So when a request comes in from an authenticated user the framework uses the username (typically in the form of an authentication cookie) to load the profile information into the current request.
In the case of the example you provided because the author is using <anonymousIdentification enabled="true"/> which allows for profile information to be available for anonymous users as well.
When an anonymous user makes a request, the AnonymousIdentificationModule module creates a GUID and writes it into a persistent cookie named .ASPXANONYMOUS. This GUID will act as the username for the purpose of the ProfileProvider.
the important part of the code that brings together the cart and the Profile is at the very end (happens behind the scenes for every login):
void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)
{
ProfileCommon anonymousProfile = Profile.GetProfile(e.AnonymousID);
if (anonymousProfile.SCart != null)
{
if (Profile.SCart == null)
Profile.SCart = new ShoppingCartExample.Cart();
Profile.SCart.Items.AddRange(anonymousProfile.SCart.Items);
anonymousProfile.SCart = null;
}
ProfileManager.DeleteProfile(e.AnonymousID);
AnonymousIdentificationModule.ClearAnonymousIdentifier();
}
You can read about Profiles etc on MSDN - for example: http://msdn.microsoft.com/en-us/library/ewfkf772.aspx
This is not quite entirely true about session. Sessions are used in a way to store certain information about logged in users. However information about logged in user (as set by asp:Login control after successful login) is also stored in a principal which you can access from HttpContext.Current.User object. Another location where information about users is stored is in the cookie named .ASPXAUTH cookie. So there are couple of locations from which user information can be retrieved. But Profile will rely on an object of type IPrincipal. As for the anonymous users, Peter Mourfield gave you a good answer so I will not repeat his words.

How to display a page only for the first time in asp.net

I am developing an application using Asp.Net.My question is whether there is any solution to display a page only for the first time.i.e when the user logs in for the first time it should ask to change the password but when the user logs in after changing the password it should not display the changepassword page instead it should redirect to another page.I have used session variables to do this but after the session expires its again showing the change password page.Can anyone help me to solve this problem.
You should take a flag parameter in database as per user and set the flag on first login. If it is set then don't display the page.
Since the lifetime of the flag for showing this page is tied to the lifetime of the user entity, you have to keep it as a property of the user entity.
In other words - save it as a flag in the database where you keep the user details.
A common approach for this issue is to store the "user is logged-in" flag as a cookie, rather than in session state. The built-in ASP.NET membership system works that way, for example, using the concept of a "ticket."

Categories