Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Vs Public variables in multiuser environment

I'm using following approach to keep global variables in a separate class file so that they can be passed among few back-end classes. The problem is it's failing when the system is used in a multi-user environment. I can't opt for the "Session" approach, because admins are not ready to enable Session state on SharePoint server.

static class Global
{
        private static string id = string.Empty;
        public static string id
        {
            get { return id; }
            set { id = value; }
        }
}

If I remove the static declaration from above code, will it work properly in a multi-user scenario? What other options do I have without asking for any help from server admins.

like image 443
Ris Avatar asked Dec 06 '22 09:12

Ris


2 Answers

Do not use static for things that are per-user or per-request; static is pretty rare in a web application, but might occasionally be used for things like keeping a snapshot of the overall system configuration (preferably immutable).

So: where can we store things?

Session-state would be the obvious answer for something that is (and here's the clue) per session, but it sounds like that is not an option

Beyond that, you have basically: the http request. That means you have access to the form, the query string, and the cookies. And that's it. You don't want to store much in the cookies: it bloats every request. And "viewstate" is just evil. If regular session-state isn't viable, you could do some home-brew "session" implementation based on some cookie (suitably secured), but frankly I think you'd do well to either:

  • use the request form / query-string if all you want is an id
  • else push your admins to get session-state enabled
like image 156
Marc Gravell Avatar answered Dec 25 '22 18:12

Marc Gravell


Your static variables will be shared between all users, and will not belong to a specific user. Using static variables to keep state in a web environment is almost always a bad idea.

If you can't enable session state, a good strategy would be to:

  • Add a user specific identifier to the URL, and keep that in the URL
  • Save your state on the server in a database, based on that id

This way you are essentially re-inventing session state; but you avoid enabling Session state globally. If the state is sufficiently small, you could also encode it into the URL.

Also consider that Session state does not work well in a server farm environment, unless you store it on a shared server - this might be the reason your admins are not inclined to enable it.

like image 29
driis Avatar answered Dec 25 '22 18:12

driis