understanding Session State Mode c# - c#

I am creating a web app in asp.net mvc in my web.config I have a section called sessionState, like below
<sessionState mode="InProc" timeout="25"></sessionState>
whenever I change the mode to InProc, I can use sessions but when I changed the mode to StateServer I am not able to use sessions, after searching on google, I came to know that there are 5 types of sessionstates
InProc
StateServer
SQLServer
Custom
Off
I just want to know, in which scenario the above sessionstate can be used,

InProc - runs as part of your website / web application, always there, but only on the same server and on the same instance of the website.
StateServer - need to run this service on a machine (just press start :-)), so the session can connect to that process on that machine and can be shared between instances and servers.
SQLServer - same as stateserver, but using a SQL database for this.
Custom - any stateserver you program yourself.
Off - no session tracking.
Whilst session can make a lot of things easier for development, when you get to a multi-server deployment this becomes a hassle. So make sure to limit session usage, always being able to retrieve the session data if this is no longer available, that way you can get the best of performance using the session, whilst your app still keeps working if your session is no longer there.

Related

Debugging C# MVC3 in visual studio : can i stop session data from clearing each time i re-start debugging?

Each time when I stop debugging on localhost and start again, session data gets cleared. So, I have to log- out and log-in again to reach same point. This has become a pain because I have to go through the whole log-in process to reach the page that I was working on.
Any help on this is much appreciated.
If you're using InProc session state management (the default), then you're going to be out of luck. Whenever the IIS worker process restarts (when you start debugging), the session state is cleared. The advantage to InProc, of course, is that it runs in memory, so it's faster.
However, you could switch to using a state server or a database to manage the sessions. Those both run out-of-process, meaning they don't get cleared when IIS restarts, or when you start debugging.
See This Microsoft article for setting up a state server to manage sessions.
See This Microsoft article for setting up a SQL server for managing sessions.
Or perhaps, an alternative could be to use the #if DEBUG directive to hard-code and pre-populate a username and password during the login process? That could at least save typing time :)

IE10 and Windows 8 and ASP.NET MVC (IIS 7)

I'm having a very interesting, but frustrating issue. I have an MVC 4 site running with standard ASP.NET Authentication.
In and only in the combination of IE 10 on Windows 8, when I traverse my site and navigate to an http url from an https url (both on the same site), it is generating a different asp.net_sessionid value. In every other browser/OS combo I have tried, this does not appear to be an issue.
I have searched high and low and while I certainly have found people experiencing various authentication issues (usually regarding IIS7 not recognizing IE10 as a browser), I have not found anyone else claiming to have experienced this exact issue. More concerning, I published an 'out of the box' MVC template project and it has the same issue. I can't possibly be the only one who has run across this problem (so I hope).
Anyone else run into this? Or maybe even just have some suggestions?
Thanks
UPDATE
Okay, so there is one more important aspect. I am running this on a load balanced environment. If I push the apps to a single server and test, I have no issues.
You mention that you have had this problem in a load balanced environment, right? I assume you are using the default "In Proc" method of storing session data. If that is the case, then I think I know what could be happening. (for the sake of argument, I will assume 2 servers, but It doesn't really matter if you have more)
You are being sent to ServerA and a session is created. Because this is In Process ServerB has no idea about it. Eventually (and how that happens is a matter of how your load balancer is set up. Sticky session? Cookies? Round robin?) you will be sent to ServerB. Because that server had no idea you already have a session; a new one is created and you are given a new session ID.
So why is it happening under your exact repro steps? Well, my hunch is that given enough time and load, you would see it just navigating from /page1 to /page2. Again - this depends on how your load balancer is setup, but it could be that since you are changing protocol that triggers something and you are sent to the another server in the pool.
How can you fix it?
To start, make sure you have the same machine key in their machine.config. If you don't have access to that I think it will work in the web.config, but I haven't tried it.
Now, set up another way to store session state. In Sql Server perhaps or MySql or Postgres or wherever. If you have SQL Server that will be the easiest since the driver is built it, but if you have another datastore you will either need to build or find a library that will do it. I worked on a project where we used Postgres to store session state.
We used npgsql as the driver to conenct to the server, and built our own PgsqlSessionProvider:SessionStateStoreProviderBase and hooking it up is actually really easy
<sessionState mode="Custom" customProvider="PgsqlSessionProvider">
<providers>
<add name="PgsqlSessionProvider" type="My.namespace.PgsqlSessionStateStore" connectionStringName="connectionStringName" writeExceptionsToEventLog="true" />
</providers>
</sessionState>

InProc vs StateServer

We recently changed from using InProc to StateServer for storing Session information.
I was wondering, if it's possible to update configuration files on the website now without losing session information. As when we used InProc and updated resource files (like language files), web config files, global.asax or files in the App_Code, we found that sessions appeared to reset and received errors like
'Object reference not set to an instance of an object'
Does this change with going to StateServer? Is it safe to update these types of files without losing the session data? I have run a couple of tests on our test system, and it appears that it works OK, but I'm not 100% confident...
A simple answer to your query is YES
Further more saying...
- Using State Server, session is serialized and stored in memory in a separate process (aspnet_state.exe).
- State Server can run on another machine.
- Session is persistent, you don't need to be afraid that your session data is lost during application restarts
- When storing data of basic types (e.g. string, integer, etc), in one test environment it's 15% slower than InProc.
- The cost of serialization/deserialization can affect performance if you're storing lots of objects.
- Solve the session state loss problem in InProc mode. Allows a webfarm to store ASP.NET session on a central server. Single point of failure at the State Server.
For more refer:
- Steps for session inproc mode to state server
Yes it does. Once your session data are out-of-process it's safe to restart worker processes. You can test it by logging in to your site, making some actions that involve session update and killing the corresponding w3wp.exe process (assuming it's IIS 7+) from the task manager (or just touching web.config).

How would a static variable work in a web farm?

I have a static class with a static dictionary to keep track of some stats. Is this approach viable in a single and multi server environment?
Not in a multi-server environment. Unless the dictionary isn't the .Net dictionary, but one that works against a database or some other outside storage. Also in a single server environment you should remember the Dictionary will be emptied with every IIS refresh.
No, a static variable in memory in one server won't be visible or synchronized with other servers.
Since you mention "keeping track of stats", what many multi-instance server farms end up doing is post-processing locally gathered data into an aggregate view of activity across all the servers. Each server accumulates stats in memory for a short while (a few minutes), then writes the data from memory to a log file on the local file system. Every few hours or daily a batch process copies the log files from each server in the farm to a central location and merges all the log records together to form one collection of data. One useful byproduct of this might be consolidating user activity across multiple servers if a user's web requests were served by different servers in the same farm (load balancing).
Depending on the volume of data, this batch processing of log data may itself require quite a bit of computational power, with multiple machines crunching different subsets of the server logs, and then those intermediates getting reduced again.
Google Sawzall is an example of a very large scale distributed data processing system. I believe Sawzall is (or was) used at Google to process server access logs to detect fraudulent ad click patterns.
No, it's not viable in a web farm multi-server environment.
Storing Session State in an ASP.Net Web Farm
Allowing Session in a Web Farm? Is StateServer Good Enough?
Fast, Scalable, and Secure Session State Management for Your Web Applications
ASP.NET Session State
Session-State Modes
The State Mode options are:
InProc mode, which stores session state in memory on the Web server. This is the default.
StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
Custom mode, which enables you to specify a custom storage provider.
Off (disables session state)
Normally, this is what you would use Application state for.

ASP.NET Session Abandoning Unexpectantly

For some reason, the session is abandoning unexpectantly, and wreaking havoc in our application. We've had the app setup to use Session and have been using it for several months with no problems. Now, as we add additional content and store additional info in it, the Session is dumping well before the 20 minute timeout than its supposed to. I'm at a loss for the reason why... could it be because we may be adding a lot of data in the Session (not sure of exact size)? This is my local machine after all (Win 7, using IIS, ASP.NET 4.0, 4 GB RAM).
Or could there be other reasons for this occurrence? Any thoughts?
Thanks.
ASP.Net sessions are stored in the cache. If you are running out of memory then it will be dumped. You need to store the session in a database or other storage to keep it. I'll try to find a relevant link. Sessions are not meant to store tons of data!
Here is a link explaining how to use out-of-process sessions. Basically the idea is that, by default, ASP.Net/IIS will use in-process sessions (which are fastest) but are also limited by the power/storage on the server running IIS. The alternatives are to use a session state farm or a SQL server to store sessions. These are a bit slower but offer more flexibility. You will need to take into account the ability to serialize sessions into your decision.
Here is an excerpt from a book I've been reading (Programming Microsoft ASP.NET 3.5 by Dino Esposito):
Why Does My Session State Sometimes Get Lost?
When the working mode is InProc, the session state is mapped in the memory space of the AppDomain in which the page request is being served. In light of this, the session state is subject to process recycling and AppDomain restarts. As we discussed in Chapter 2, the ASP.NET worker process is periodically restarted to maintain an average good performance; when this happens, the session state is lost. Process recycling depends on the percentage of memory consumption and maybe the number of requests served. Although the process is cyclic, no general consideration can be made regarding the interval of the cycle. Be aware of this when designing your session-based, in-process application. As a general rule, bear in mind that the session state might not be there when you try to access it. Use exception handling or recovery techniques as appropriate for your application.
In Knowledge Base article Q316148, Microsoft suggests that some antivirus software might be marking the web.config or global.asax file as modified, thus causing a new application to be started and subsequently causing the loss of the session state. This holds true also if you or your code modify the timestamp of those files. Also, any addition to or removal from the Bin directory causes the application to restart.
Note: What happens to the session state when a running page hits an error? Will the current dictionary be saved or is it just lost? The state of the session is not saved if, at the end of the request, the page results in an error—that is, the GetLastError method of the Server object returns an exception. However, if in your exception handler you reset the error state by calling Server.ClearError, the values of the session are saved regularly as if no error ever occurred.
I'm assuming you are using Session state in-proc. If this is the case then the most common reason of losing your Session is that the corresponding Application Pool recycles. Go check IIS settings on Application pool and set up Event log entries for such events. You'll find the settings in: "Advanced settings" of your app pool -> "Recycling" -> "Generate Recycle Event Log Entry". Set them all to true and see if it will give you the reason of your Session State loss.
Also if you change data on given sites a lot then it will eventually trigger app pool recycling.
More ideas on app pool recycling:
http://blogs.msdn.com/b/johan/archive/2007/05/16/common-reasons-why-your-application-pool-may-unexpectedly-recycle.aspx

Categories