In my web application I am using sessions for storing the user specific data for persisting the data in between the postbacks.
I would like to know the difference between storing the data in sessions as
Session["selectedItem"] = somevalue;
and
Session["UserName"]["SelectedItem"] = somevalue;
where I have a session named Session["UserName"] which stores the name of the user who is logged in.
If i just go into more depth lets say if there are 2 users one logs into firefox and other internet explorer, will there be any conflict if i store the value in the first way meaning the session data is overwritten or shared, and this conflict would be resolved if i use sessions in second way.
Is there any noticeable difference in the way session variable is stored between these 2 session implementations or are they just identical ?
Data stored in a session is, per definition, stored against a specific user - and it will work regardless of whether your user has been authenticated or not (if your user is anonymous the server will still set a cookie in the user's browser with a unique id for the user's session).
The session object provides a simple one-dimensional collection for storing data, meaning that you can only store data in the session by providing a single key, e.g.
Session["myKey"] = myObject;
Of course, if myObject is an array or another collection then you can reference elements within myObject like this:
Session["myKey"][0];
Session["myKey"]["anotherKey"];
Sessions are unique per user, so there's no need to key your Session variables by user.
The session is generally tied to a particular browser through cookies and is isolated from other sessions.
Hope following points clear your doubts
You will get a new session/session ID when using different browsers
If you are using the same browser (tabs or multiple instances) and your session is set to use cookies, by default cookies will be shared among all tabs and/or instances of a browser
If you want a different session when using the same browser you will need to use cookieless sessions.
Related
Regarding a clock in/out site. When user A logs in it shows his check in/outs. then user B logs in. When A refreshes the page, he gets B's Check in/outs.
I am probably doing this wrong because iam storing the username in a public variable when ever the user logs in server side, c#, too check for a lot of other permissions on the site, through different pages.
if (publiclasses.isValid == true)
{
publiclasses.unilogin = UserNametextbox.Text.ToString();
publiclasses.Checkifmissinglogout();
Response.Redirect("checkin.aspx");
}
How do i save the user in a different way that always keeps it "unique" and not just overrides the old one stored?
Using a public variable will be shared across all user sessions and it introduces concurrency issues, all of this assuming it is static.
To separate it, you have to use sessions.
ex:
Session["unilogin"] = UserNametextbox.Text.ToString();
You have to make sure you use the session variable in any piece of code you reference the current public variable
You need to implement some kind if identity for your users. There are loads of ways to do this, but it depends on the exact ASP.NET variant which will be best for you. Most web applications use cookies for this.
Basically when user A signs in they get a cookie that says they are A. Every subsequent request they make will have that cookie attached and you can get which user they are from it.
At its very simplest this is very easy:
// In sign in POST back
Response.Cookies.Append("user", username);
// In further pages:
string username = Request.Cookies["user"];
However, this will make it very easy for B to pretend to be A - it isn't secure. The built in .NET methods will create an encrypted cookie that's much more secure.
In my application every time a user lands on my website I check that user with it's session ID and make a insert(with all the details ip,browser etc) into the database if its a different session ID.
string sessionId = HttpContext.Current.Session.SessionID;
if (objDB.checkDuplicate("session", "sessionId", sessionId))
{
// code to make insert in database
}
But when checking database I am getting multiple inserts from same IP at the same time.
Can anybody explain why this happens?
NOTE : SESSION of the user is different so checkDuplicate() works fine but how can a user have a different session ID at the same time? (or such a sort span of time)
Most probably it's multiple people sharing the same connection over a router or proxy server.
More reasons (being behind router/proxy is most likely one) to have different session Id for same IP
restarting browser will make new session Id for the same user (as long it is set in session cookies)
opening separate browsing session (i.e. normal vs. private for IE, depending on configuration and browser tabs may be treated as separate sessions)
different users on the same computer
Another set of reasons for different session Id is based on failure to set persist session cookie between requests:
I think if there is no writes to ASP.Net session state cookie can be regenerated on every request (need to verify)
cookie could be disabled (rare, but possible)
cookie can be blocked (i.e. lack of P3P policy for pages/images in IFrame) or some other policy in browser
There are valid reasons to get multiple browser windows for the same sessionId for the same user (tabs in same "browser session", "open in new window/tab" with Ctrl+click ). You as site creator have to decide if you want to try to enforce "single session = single window" policy or deal with potentially multiple windows opened in the same session. There is no reasonable way I know to detect case when same session Id is used in different tabs, especially if you have to support GET requests (otherwise you can dump some addition ID into hidden field).
I am reviewing some web code and I am not exactly sure how ASP.net session state works. Any helps would be gratefully appreciated.
If a User object is saved to the session state during login, and User.FirstName and User.LastName is set. If other web pages retrieve the user object from the session and set the FirstName to something else is that persisted on other web pages? Or, do you need to re-add the user object back to the session once it has been modified? Thanks
Session is persisted on the server, but tracked via the client. I repeat - via the client.
In most cases, sessions are tracked with cookies. So using your example, when User object is saved to Session:
Session["UserInfo"] = new User { FirstName = "Joe", LastName = "Bloggs" };
A cookie will be sent to the client with a unique identifier. This cookie is passed along to all further HTTP requests from this client/browser unless it expires.
If another user comes along (from a different machine) for the first time, Session["UserInfo"] will be null.
An alternative to cookies is "cookieless-session" - where instead of using a cookie to store the session identifer - the identifier is tacked onto the URL.
So the answer is no - other web pages (e.g other clients/machines/browsers) will not have access to this information.
If you want information shared between different clients from the web server, use Cache.
However given the context of the question (User information), it is valid to store this information in the Session, as it is only relevant to a particular user (shouldn't be shared).
An alternative a lot of people use instead of sticking the User info in the session, is to put it in a generic principle which get's attached to the Forms Authentication ticket.
Up to you which road you choose.
This should help you get your head around Sessions in ASP.Net
http://www.codeproject.com/KB/aspnet/ExploringSession.aspx
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net
Any changes you make to the object are persisted.
i want to create a global session which will stay active until and unless we manually kill it. how to do this in asp.net with c#
what i am doing is
HttpContext.Current.Session["UserID"] = someValue;
but in this way the session is lost after some time.
You can set the timeout in web.config under system.web -> sessionState -> timeout. Not sure if you can have an infinite session though.
Also, you might be interested in the Application object which stores things in the "application's session" instead of the user's. Comes to my mind because you speak of a "global" session.
What's the application for this? Sounds like you're actually trying to use the session as a persistent storage, which will however only seemingly work even if you manage to set timeout to never or 5 years or whatever - because sessions will be "timed out" once the application is restarted. You might still get around that, but you might be better off looking for real persistence solution like a database. I may be totally off guessing your application for that of course.
Store the data in the Application state rather. It will stay there till you remove it, or the app dies/recycles/ends.
Usage:
HttpContext.Current.Application["Foo"] = "bar";
As nicolas78 says use session timeout configuration property to control the session expiry after user inactivity. In case, you are facing a requirement where session should be active as long as browser is open, there are two ways -
Use cookie to store some token and then re-construct your session state using the token if session gets expired. For example, user details can be recovered from user store if user id is stored in token. At worst, you may have to move your entire state to the database.
Keep the ASP.NET session state but keep it alive by firing AJAX requests from browser. I would suggest to fire such request after n/3 interval where n is your session timeout (ensuring at least three requests are made so even if two gets lost or falls on edges, one gets through).
Perhaps you're after profiles?
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
Profiles live beyond the session and are usually used to store per-user settings that the user can edit, such as their contact details and application preferences.
Profiles can be used with both anonymous and authenticated users. When an anonymous user signs in, their anonymous profile can be migrated into an authenticated profile (i.e. one that is attached to their user name).
Good walkthrough here: http://quickstarts.asp.net/quickstartv20/aspnet/doc/profile/default.aspx
What is the difference between a Session and a Cookie?
What circumstances should each be used?
Sessions
Sessions are stored per-user in memory(or an alternative Session-State) on the server. Sessions use a cookie(session key) to tie the user to the session. This means no "sensitive" data is stored in the cookie on the users machine.
Sessions are generally used to maintain state when you navigate through a website. However, they can also be used to hold commonly accessed objects. Only if the Session-state is set to InProc, if set to another Session-State mode the object must also serializable.
Session["userName"] = "EvilBoy";
if(Session["userName"] != null)
lblUserName.Text = Session["userName"].ToString();
Cookies
Cookies are stored per-user on the users machine. A cookie is usually just a bit of information. Cookies are usually used for simple user settings colours preferences ect. No sensitive information should ever be stored in a cookie.
You can never fully trust that a cookie has not been tampered with by a user or outside source however if security is a big concern and you must use cookies then you can either encrypt your cookies or set them to only be transmitted over SSL. A user can clear his cookies at any time or not allow cookies altogether so you cannot count on them being there just because a user has visited your site in the past.
//add a username Cookie
Response.Cookies["userName"].Value = "EvilBoy";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(10);
//Can Limit a cookie to a certain Domain
Response.Cookies["userName"].Domain = "Stackoverflow.com";
//request a username cookie
if(Request.Cookies["userName"] != null)
lblUserName.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
sidenote
It is worth mentioning that ASP.NET also supports cookieless state-management
Cookie is a client side storage of your variables. It stored on client machine by browser physically. It's scope is machine wide. Different users at same machine can read same cookie.
Because of this :
You should not store sensitive data on cookie.
You should not store data that belongs to one user account.
Cookie has no effect on server resources.
Cookie expires at specified date by you.
Session is a server side storage of your variables. Default, it stored on server's memory. But you can configure it to store at SqlServer. It's scope is browser wide. Same user can run two or more browsers and each browser has it's own session.
Because of this :
You can save sensitive data in session.
You should not save everything in session. it's waste of server resources.
After user closes browser, session timeout clears all information. (default is 20 minutes)
A cookie is an identifaction string stored by a server (who has a domain) in the browser of the user who visits the server/domain.
A session is a unit of maybe variables, state, settings while a certain user is accessing a server/domain in a specific time frame. All the session information is in the traditional model stored on the server (!)
Because many concurrent users can visit a server/domain at the same time the server needs to be able to distinguish many different concurrent sessions and always assign the right session to the right user. (And no user may "steal" another uses's session)
This is done through the cookie. The cookie which is stored in the browser and which should in this case be a random combination like s73jsd74df4fdf (so it cannot be guessed) is sent on each request from the browser to the server, and the server can assign and use the correct session for its answers (page views)
The cookie allows the server to recognize the browser/user. The session allows the server to remember information between different page views.
Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit.
Its possible to have both: a database primary key is hashed and stored in a lookup table: then the hash is stored on the client as a cookie. Once the hash cookie (hahhahaha :) is submitted, its corresponding primary key is looked up, and the rest of the details are associated with it in another table on the server database.
The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not. This difference determines what each is best used for.
A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie.
Session is a server side object,
which transfer or access data between page call.
Cookies is a object which is client side/client machine which store some text information of browser and server.
There appears to be some confusion regarding what a session cookie is.
Firstly, when we are talking session cookies - it has nothing to do with ASP.Net sessions. Likewise, session cookies have nothing to do with server side processes or caching.
A session cookie is nothing more than a cookie that expires when the browser session expires. To create a session cookie - don't put an expiration date on it. Doing this stores the cookie in memory and is disposed of when the browser is disposed.