Deploying an ASP.NET MVC in production, while users are still online - asp.net-mvc

I need to know the best practices for deploying a new version of an ASP.NET MVC application while users are still connected to it
Everytime one deploys the .dll that contains the models and controllers of the application, the application is rebooted. Also deploying the web.config (that references eventually new libraries) results in rebooting the application.
So, the question is: how do I update the application's dll or web.config without disconnecting the users from the site?

You want to use another session state option other than using in-proc so your users survive when the process recycles or system reboots.
InProc: In-Proc mode stores values in the memory of the ASP.NET worker process. Thus, this mode offers the fastest access to these values. However, when the ASP.NET worker process recycles, the state data is lost.
See ASP.NET Session State Options for more ASP.NET options and mentions of other third party session state providers.
This question also deals with possible deployment scenarios to help with the websites under load and slow app times after a pool recycle: How are people solving app pool recycle issues on deployment with large apps?
Ideally you want to be as stateless as you can, and stay away from session. Perhaps you can use a cookie for tracking the current user via forms auth for example. But you must stay away from in-proc by using distributed cache/session provider so users won't lose session state on app pool recycles.

I think the best is to deploy a new site for new sessions, and mantain existing sessions in the old one.
I feel that "The blue green deployment strategy" article linked below can be hacked with a few changes to do that (Disallow New Connections instead of issue a "drain", using sticky sessions).
https://kevinareed.com/2015/11/07/how-to-deploy-anything-in-iis-with-zero-downtime-on-a-single-server/

Related

Is there any way to work with sessions without locking on ASP.Net MVC site?

Is there any way to work with sessions without locking on ASP.Net MVC site ?
Session lock mechanism leads many problems;
When your site slow down little bit, users are start to hit "F5" on the keyboard. When they do this, requests are starting to wait each other. All those requests are hanging on IIS at "RequestAcquireState" state for session module.
If a user made a simultaneous requests this will happen. Because session module in IIS and default session provider (Or generally custom ones) has both lock mechanism.
See:
Implementing a Session-State Store Provider
Session State Providers
There is locking, because your workflow can be manipulated if you are not carefully designed your process. Been hacked is way big problem for you comparing with performance issues...
But if you designed your process for shared, semi-consistent state store, (Or simply maybe there is no need to use) can we remove locking situation from our way completely?
Yes we can remove lock from our way with "UnlockedStateProvider".
It designed for MVC and not implements .Net SessionStateStoreProviderBase because, IIS session module also has locking mechanism.
It is a simple ActionFilterAttribute provide state store for you via HttpContext.
It has also Redis provider so you can use safely in web farm, Azure or AWS.
Please take a look:
https://www.nuget.org/packages/UnlockedStateProvider.Redis
https://github.com/efaruk/playground/tree/master/UnlockedStateProvider
Note: Developed for advanced usage and not a replacement for any SessionStateProvider...

Current recommendation for enabling session in Azure Websites for Session variables and TempData?

I have a MVC3, ASP.NET 4.5 web application deployed on Azure Websites, using SQL Azure.
Currently I am using some "inproc" Session variables which I need to remove since I am going to start using multi website instances. I could just store the Session variable values in the SQL Azure DB, but I am also using TempData, which also uses Session state, "under the bonnet". Due to TempData use, I do need to implement an "out of proc" session solution.
I have seen some recommendation for using AppFabric caching, but I am unsure whether this is still current, and whether it is correct for Azure websites.
Also my development setup is on a Windows 7 machine with SQL Server 2008 R2. So a solution should be transferable with minimum pain.
There is also a "thread agility" issue with session variables, and a open source solution has been created using REDIS caching, but I have no experience of this, or REDIS. See: GitHub site
So thoughts I have are:
1) Angieslist/AL-redis custom provider, see: GITHUB link . Not entirely sure that this can be used in a Azure Websites application.
2) Appfabric. Not sure if this is relevant or current for Azure Websites.
3) SQL Azure session provider.
4) Azure Table storage.
5) Use a custome TempData provider to persist via cookies ie https://www.nuget.org/packages/BrockAllen.CookieTempData.dll/1.2.2, and then remove other session variables.
I would be very grateful for advice on a good Azure Websites session implementation mechanism which is simple. My data is pretty simple. I think I have one object which I quess I will need to serialize, probably via Json.NET
If you have more than one instance of an Azure Web Site, sticky sessions are enabled by default by the load balancer. This means that a user will be directed to the same instance (server) and that you'll be able to use session state in your app.
You may also find the Distributed Caching section (Ch 12) of this ebook helpful http://aka.ms/CloudApps_PDF

Scaling an Entity Framework Application / Multiple Apps hitting the same database?

I have a application that has been programmed with MVC/EF Code First. It does a lot of server side processing and is pretty resource intensive.
I know how to set up load balancing, but, I want to know if scaling an EF application is as simple as provisioning a new server, deploying the application and pointing to the DB cluster - or are there any issues I will face with regards to multiple EF applications hitting the same database server?
I can't seem to find any advice/guides for this and I am worrying I made the wrong choice by choosing EF over something simpler/more straight forward!
... issues ... regards to multiple EF applications hitting the same database server?
Rewind a bit to the fact that your application is an ASP .NET MVC based application. Having multiple instances of it is probably going to raise the spectre of state management.
MSDN has a pretty good introduction to why this is an issue:
HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.
Alternatives to session state include the following:
Application state, which stores variables that can be accessed by all users of an ASP.NET application.
This point is an extremely common way of storing state, but breaks down when there's multiple instances of an application involved (the state is "visible" to only one of the instances).
Typically this is worked around by using either the StateServer or SQLServer value of SessionStateMode. The same article provides a pretty good summary of each option (emphasis mine).
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.
If your application is stateless, this is a moot point.
I am worrying I made the wrong choice by choosing EF
As far as issues with multiple instances of your application accessing a database go, you're going to have issues with any sort of data access technology.
Here's the basic scenario: let's say your application sends welcome emails to users on a schedule.
Given the table Users:
UserId | Email | WelcomeLetterSent
-------+-----------------+------------------
1 | user#domain.com | 0
And some psuedo-code:
foreach (var user in _context.Users.Where(u => !u.WelcomeLetterSent))
{
SendEmailForUser(user);
user.WelcomeLetterSent = true;
}
_context.SaveChanges();
There's a race condition where both instance one and instance two of your application might simultaneously evaluate _context.Users.Where(...) before either of them has the chance to set WelcomeLetterSent = true and call SaveChanges. In this case, two welcome emails might get sent to each user instead of one.
Concurrency can be an insidious thing. There's a primer on managing concurrency with the Entity Framework over here, but this is only the tip of the iceberg.
The answer to your question? It depends on what your application does :)
On top of that, I ideally want to build some "extra" support applications that hook in to the same DB... and, I am just not sure how EF will handle multiple apps to the same DB....
If your application can tolerate multiple instances of itself accessing one database, then it's usually not a stretch to make these "support applications" play nicely. It's not much different whether the concurrency is from multiple instances of one application or multiple applications with one instance each.

Maintaining state in Asp.Net MVC website

I'm currently designing a new website built on MVC and I wonder what is the right way to manage state.
The state should contain the userId and some structs of the user info, and should be kept during the whole session of the user while he's logged in (across http requests)
The important criteria:
1) Support scalability
2) Performance
The easy way is to use the Session object, but it doesn't support scalability. If different requests during the session go through different IIS servers, the session won't be kept. Although I've heard of load balancing tools which route all requests of a single session through the same machine, I'm not sure that it's a good practice to rely on it (isn't it?)
Another option that I've read about, is keeping the state data in special state servers which are running a RAM DB (like Cassandra for Linux or Redis for Windows). But it seems to me an overkill at this stage of the development.
Do you have any other suggestions?
I would like to start with something simple at the moment, but keep the design ready for a more advanced solution at the future.
Any best practice or code/design suggestions will be appreciated.
Thanks,
Edi.
(1) Use Sql Server to Store Session State
(2) Use Memcached as a Session State Provider
(3) Cook up your own solution using Caching on an external caching provider: look into using something like the ServiceStack Caching Framework. Using this, you can use Redis, Memcached, Azure or AWS to handle caching.
Next, create a KeyFactory to handle generation of keys for specific items. The item keys would include the UserId (which you would always have from FormsAuthentication UserId (assuming that you are using FormsAuthentication). Then store any Session data for the user in the cache. Using this approach you are using Caching in place of Session, and the cache can be shared across multiple servers.
Note: you can have different approaches regarding clearing out the user's data whenever they begin a new session. Potential approaches include:
Include the user's session start dateTime in the cacheKey, and auto-expire entries when they are no longer fresh
Clear out all potential entries for a user when they begin a new session
If you are using .NET 4.5 and dependent on the type and amount of information you are keeping on users you may want to look at using claims to store information about the user. In .NET 4.5 all Principals inherit from ClaimsPrincipal. ClaimsPrincipal already uses claims to store the user name, roles and other information. You can create your own service to transform claims, which will allow you to add additional information to the Principal user.

bulk create user accounts to asp.net mvc3 membership tables in production environment

In dev environment I am using the ASP.NET configuration tool in Visual Studio to create a few users for testing. As I movel closer to QA and Production, I'm wondering what is the best way for me to automate the creation of a large amount (1000's) of users after application deployment.
I have a csv with all the usernames and passwords, roles etc. and I wan't to avail of the encryption and password salting security that is built in. I do not want to manually "Register" all these users.
I'm just not sure if this is something I can do (or instruct a db admin to perform for me).
Does anyone know of a way to achieve this?
Any assistance would be greatly appreciated.
Regards
The simplest solution would be to set up a "CSV Upload" form. The CSV would be processed by an MVC action calling Membership.CreateUser in a loop.
Probably, the performance of this will be good enough.
There's a few ways that I know of approaching a batch processing problem on an ASP.NET site.
Because of the wonky way an ASP.NET site's application pool can get recycled, batch processing is usually done on an external process.
Windows service
One way is a separate windows service, which gets the new excel and pumps that data in, and has a timer which keeps going around. I've seen this used often, and it is quite a pain, because it takes extra work to make it easily deployable.
Update ASP.Net membership from windows service
CacheItem
Second way is to use CacheItems and their expiration timers to do batch processing, what you do is you define a cache object with a long timer, and when that expires and the Removed-callback gets called, you do your database work. This is good because it deploys with your ASP.NET site, and you have your code in one logical place.
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
Workflow Foundation
Third way, is to make a workflow foundation service. That service gets a call from your ASP.NET site, which instantiates a WF service, that does some db work with your excel file, and then it goes into a while-loop with a delay of a month in it. This is good, because it is not tied to the lifespan of your ASP.NET application pool - you get more control, and this logic can be separated into a different IIS hosted WCF service.
http://msdn.microsoft.com/en-us/library/dd489452.aspx
Integrating with data is always a pain though, remember that the solution that gives you the least work and least chance of failure when deploying is the best solution.

Resources