Static Session Class and Multiple Users - c#

I am building a class to store User ID and User Role in a session. I'm not sure how this class will behave when multiple users are on the site at the same time. Does anyone see a problem with this?
public static class SessionHandler
{
//*** Session String Values ***********************
private static string _userID = "UserID";
private static string _userRole = "UserRole";
//*** Sets and Gets **********************************************************
public static string UserID
{
get
{
if (HttpContext.Current.Session[SessionHandler._userID] == null)
{ return string.Empty; }
else
{ return HttpContext.Current.Session[SessionHandler._userID].ToString(); }
}
set
{ HttpContext.Current.Session[SessionHandler._userID] = value; }
}
public static string UserRole
{
get
{
if (HttpContext.Current.Session[SessionHandler._userRole] == null)
{ return string.Empty; }
else
{ return HttpContext.Current.Session[SessionHandler._userRole].ToString(); }
}
set
{ HttpContext.Current.Session[SessionHandler._userRole] = value; }
}
}

The code you posted is the exact replica of some code we have here.
It has been working fine for 2 years now.
Each users access is own session. Every request made to the server is a new thread. Even though 2 request are simultaneous, the HttpContext.Current is different for each of those request.

You'll get a new session for each connection. No two users will ever share session. Each connection will have its own SessionID value. As long as the user stays on your page (doesn't close the browser, etc.) the user will retain that session from one request to the next.

This will work fine for mutiple users accessing your application as there will be different sessionid generated for all deffrent users accessing application concurrentely. It will work in similar way if you have defined two different session variables in your system.
It will be like wrapping tow session states using static wrapper class SessionHandler.

Related

replacement for static variable

I am developing an ASP.NET MVC 4 application. userMenus is a static variable that is loaded every time a user logs in.
public class MenuCL
{
public static List<UserMenu> userMenus = new List<UserMenu>(); // the static variable
}
public class UserMenu
{
public decimal MenuID { get; set; }
public string MenuName { get; set; }
public string Controller { get; set; }
public bool Permission { get; set; }
}
I use that static variable to check whether or not the logged in user has permission to a menu/controller in a custom authorize filter.
It works fine when a single user is logged in, but when two or more users are logged-in, it's all messed up, I mean the error page("you don't have access to this page") is displayed to a user that has permission to the menu/controller.
Only now I realized it's the static variable that is causing all the trouble, after I read this :
The static variables will be shared between requests. Moreover they will be initialized when application starts, so if the AppDomain, thus application gets restarted, their values will be reinitialized.
So I need a replacement for this static variable. Anyone has any suggestion?
You can still use a static field which is a property that provides access to a session variable.
public static List<UserMenu> UserMenus
{
set
{
Session["UserMenus"] = value;
}
get
{
return Session["UserMenus"] == null ? new List<UserMenu>() : (List<UserMenu>) Session["UserMenus"];
}
}
In order to get this working on a web farm which uses a session state server (or sql server), you need to put [Serializable] attribute on top of UserMenu.
I don't think, this way you need to modify your code very much.
My question is, why do you want to use static variable? Do you want to share the values across the application? In this case you can better use session.
Updated
Assume lst as a non static List of UserMenu. Then you can use the following method to store it in session and get it bak whenever you want.
To store
Session["usemenulist"] = lst;
To get it back
try
{
lst = (List<UserMenu>)Session["usemenulist"];
}
catch
{
}
Note
If you are getting the values from the database lo load it to the List for the first time, then you can query database to get it from the database whenever you want, instead of storing it in the session. (This is another option apart from Session, you may try this way also if you want.)

Best practice to store temporary information

When my user in the students Role login to the system, he can select various classes that he's enrolled. I already have a filter that'll redirect him to the select class page so he must select a class to access the system, and change it anytime he wants and the whole system's context will change.
As for now, i'm storing IdClass in the session variable, using the code below, and the system uses it to filter all the related queries and functions, like showing all the lessons from the current class. My question is: is this a good practice? Is this right or is there any better and efficient way? I'm trying to follow patterns.
[Serializable]
public sealed class Session
{
private const string SESSION_FOO = "STUDYPLATFORM_GUID";
private Session()
{
this.IdClass= 0; // Construct it to 0 so it evaluate as there's no Class selected.
}
/* This is the session's public IdClass that
i can get and set throughout the application. */
public int IdClass { get; set; }
public static Session Current
{
get
{
if (HttpContext.Current.Session[SESSION_FOO] == null)
{
HttpContext.Current.Session[SESSION_FOO] = new Session();
}
return HttpContext.Current.Session[SESSION_FOO] as Session;
}
}
}

dealing with static list

I have create a permission object that stores userId, Groups user is in and user´s permissions. This is a public class
I also need to have a static object that stores a list of those permissions objects that if a administration changes anything in the permissions all changes apply immediately for every logged user
I have a couple of questions:
Should I create this static object when the first user logs in or there is a mechanism a should use to create that list before the first user log-in (For instance when we start our app on IIS)?
Would it be easy to remove the item list for a specific user when it log-out?
This is a system requirement that permissions settings take effect as soon as the administrator make changes.
Edit 1:
public class permissionTemp
{
public static Guid userGuid { get; set; }
public static string[] grupos { get; set; }
public static string[] permissoes { get; set; }
}
public static class security
{
public List<permissionTemp> userPermissionSet { get; set; }
}
Think about a singleton, so you do not worry about creation time:
Singleton:
public class Permission
{
private Permission()
{ }
private static Permission _instance = null;
public static Permission Instance
{
get
{
if(_instance == null)
{
_instance = new Permission();
}
return _instance
}
}
Now you can have access to the same instance with
Permission.Instance
The object is created at the first access. So in the private constructor you can add your code to read the permissions fom database.
You can use the Application_Start method in the global.asax to run some code when the website starts for the first time. This will run before the first request is processed.
You can use the Session_End method in the global.asax to remove the item from the list. Also you can do it at the same time where you execute FormsAuthentication.SignOut (if you use Forms Authentication).
Note: I would use some locking mechanism to prevent multiple simultaneous access to the list. An alternative place to store the list would be in the WebCache. This is used by all users, so if it is updated by person x, next read from person y will be the updated version.
First of all i recommend to avoid creating static object for storing such sensetive information and also if any user has closed browser without clicking "Log out" then object will not be removed for that particular User.
Still if you need to do this to meet your requirement you can create it in that object in Applciation Start Event on Global.asax file when application start first time.

So, when one user logs in to my application, all current users become that user

I'm trying to figure out which part of my program is causing this error.
I have multiple pages that all inherit from PageBase. They get their user profile from PageBase. This is the function that gets their user name from PageBase:
uiProfile = ProfileManager.FindProfilesByUserName(CompanyHttpApplication.Current.Profile.UserName)
In the CompanyHttpApplication I have
public static CompanyHttpApplication Current
{
get { return (CompanyHttpApplication)HttpContext.Current.ApplicationInstance; }
}
and
public CompanyProfileInfo Profile
{
get
{
return profile ??
(profile =
ProfileManager.FindProfilesByUserName(ProfileAuthenticationOption.Authenticated,
User.Identity.Name).Cast
<CompanyProfileInfo>().ToList().First());
}
private set { profile = value; }
}
Unfortunately I did not write this section of the code and the programmer who did it is no longer on the project. Is there any one that can explain to me why, when another user logs in (while I am using the application), I become that user?
HttpContext.Current.ApplicationInstance is globally shared. It is not per user. Thus, you have a shared profile that is immediately overwriting whatever you originally set when your new user logs in.
The Application instance is shared across every request — the application level.
You want the Session level — each user gets their own instance.
Use HttpContext.Current.Session instead of ApplicationInstance.
(Code below renames original, and adds a property, to be more clear. Feel free to adjust as necessary.)
public static CompanyHttpApplication CurrentApplication
{
// store application constants, active user counts, message of the day, and other things all users can see
get { return (CompanyHttpApplication)HttpContext.Current.ApplicationInstance; }
}
public static Session CurrentSession
{
// store information for a single user — each user gets their own instance and can *not* see other users' sessions
get { return HttpContext.Current.Session; }
}

c# stateserver maintains session between machines

I am sure that I have made some painfully obvious blunder(s) that I just cannot see. I am hoping one of you can set me straight.
I my session management is working perfectly except that if a user on one machine enters data, a user who starts a session on another machine will also retreive the session information from the first. Not so good. :(
I call my sessions like this:
UserInfo userinfo = UserInfo.Session;
My session mgt class uses this:
static UserInfo userInfo;
static public UserInfo Session
{
get
{
if (userInfo == null)
{
userInfo = new UserInfo();
userInfo.ResetSessionTime();
}
return userInfo;
}
}
I read and write the data like this. I realize that I could serialize the entire class, but it seems like a lot more overhead to serialize and deserialize an entire class each time the class is called as opposed to just grabbing the one or two items I need.
Decimal _latitude;
private String SessionValue(String sKey, String sValue, String sNewValue)
{
String sRetVal = "";
if (sNewValue == null)//not wanting to update anything
{
if (sValue == null)//there is no existing value
{
sRetVal = (String)System.Web.HttpContext.Current.Session[sKey];
}
else
{
sRetVal = sValue;
}
}
else
{
System.Web.HttpContext.Current.Session[sKey] = sNewValue;
sRetVal = sNewValue;
}
return sRetVal;
}
public Decimal Latitude
{
get { return SessionValue("Latitude", _latitude); }
set { _latitude = SessionValue("Latitude", _latitude, value); }
}
Thanks for your help
1) You're using statics for your UserInfo, which means that a single instance of this class is shared among all requests coming to your web server.
2) You're not only storing values in the session (which isn't shared among users) but also in an instance variable, which in this case WILL be shared among users.
So the value of _latitude is causing you this issue. A simple solution is this:
public class Userinfo
{
public Decimal Latitude
{
get { return System.Web.HttpContext.Current.Session["Latitude"]; }
set { System.Web.HttpContext.Current.Session["Latitude"] = value; }
}
}
A better, more testable version would be:
public class UserInfo
{
private HttpSessionStateWrapper _session;
public UserInfo(HttpSessionStateWrapper session)
(
// throw if null etc
_session = session;
)
public Decimal Latitude
{
get { return _session["Latitude"]; }
set { _session["Latitude"] = value; }
}
}
In the second instance, within a request you just construct a new instance of the HttpSessionStateWrapper (using the current Session) and pass it to the UserInfo instance. When you test, you can just pass in a mock Wrapper.
No matter what, the UserInfo instance shouldn't be shared among sessions and it should write and read directly from the Session. Don't try to prematurely optimize things by keeping local versions of your session values. You aren't saving any time and you're just opening yourself up to bugs.
This happens because you store your user info in a static field. Static instances are shared between all requests, and lives the entire lifetime of your application.
In other words, all your users will get the same UserInfo instance from UserInfo.Session.
To fix this you could:
Serialize the whole class into session. I don't know which other properties you have, but I would guess it would not be too much of an overhead.
Create an instance of UserInfo per request, so that the user always reads from a new instance, which in turn will refresh it's values from Session.

Categories

Resources