C# + MVC3 + Session state + Sql Azure - asp.net-mvc-3

I saw this post in StackOverflow that encouraged me to use Session State in my Azure application.
I followed this post and generated the tables, but my problem is I can't have an additional Database for that, I'd have additional costs too.
My question is: there's a way to make the Session State know that it should run in both tables, even if I don't have a specific connectionString pointing to the database ASPState?

If you need session state then I would recommend skipping the SQLAzure provider and using the AppFabricCacheSessionStoreProvider instead. It is now in production, in some of your links above it wasn't yet. I have found it pretty easy to use but there are additional costs. But if you use SQL Azure you could end up with additional costs pretty soon anyway as the database size grows.
Having said that, I am in the process of eliminating session use in my app on Azure. Make it much easier to add more server with no worries, unless your app has sessions deeply ingrained.

Related

Session: Why use mode="SQLServer"?

I'm really looking for feedback here. Why would you want to use
<sessionState mode="SQLServer" ... blaw blaw blaw....
Here, session is loaded from a database...it can allow a user to, say, recover from a power outage, where the user comes back to a web application and their current state is retrieved, if not past the session expiry time...
Why not just make up a class and load it on ResolveRequestCache and save it on UpdateRequestCache?
Why go to the trouble of perhaps even setting up a separate SQL server to use Session attached to a database?
R
Saving session information to the database adds support for using multiple web servers connected in a farm, since you then have connected and shared storage between them. So it's really just dependent on what you're looking to do. If you're going to be happy forever and ever, stick with something local that'll likely take less work to implement. If you're worried about scalability, go with something that will let you scale when you need to.

PHP Storing sessions

Which way would be the most effective way of storing a session in php (for login or user-related data)?
Would the best thing be a database or using the built in $_SESSION in php?
which one would be the most effective when it comes to a larger website and speed in general?
this is a very bad question because its not defining a single answer but ill go ahead and try to suit your needs
first there will be a checking so if username doesnt equal one on the data base
or the email and do propper error checking once you can check for usernames in the database and are succesfully creating functions for that
you need to have a user login ,,if credentials were truthfull then
session_start();
function logged_in()
{
return (isset($_SESSION['user_id'])) ? true : false;
}
if ($login === false)
{
$errors[] = 'Wrong username/password combination';
} else
{
$_SESSION['user_id'] = $login;
header('Location: index.php');
exit();
try this series is highly recomended
https://www.youtube.com/watch?v=9kyQGBABA38&list=PLE134D877783367C7 youll be done watching it in two days but will have a good foundation on this issue
i hope i helped
There is absolutely no reason to believe the built-in PHP mechanism is slow or bad. It is writing to files, which is perfect for single-server scenarios that about 90% of websites make use of, it is thoroughly tested and works. The inner workings do use compiled C language for the best possible performance with this storage.
Whatever you do yourself must either be implemented in PHP, which is slower, or you have to get into the business of creating PHP Session Save Handlers in C.
So if you really get into having a multi-server setup with a loadbalancer in front, and no stickyness configured, only then do you need a session storage that is accessible from all the webservers. There are plenty of solutions already existing:
Memcached - when the memcached extension is installed, there is also the memcached session save handler.
You can also try the Zend Session Cluster that comes with Zend Server.
And you can try to code your own session handler, but you must make sure that you do proper locking! Otherwise concurrent requests will overwrite each others session data. That is where most code I have seen so far fails, even mature frameworks like Symfony 2 still do with non-native storage.
PHP takes care of locking itself only if the internal session save handler is used (and coded correctly), so effectively only one script can run per session id. All others are stopped at the call to session_start().
If you think that none of the existing save handlers will fit your requirements, then you have to implement something yourself, but your question does not sound like you are already accustomed to clustered webserver environments.
Regarding "What is most effective"? Effective or efficient? Or performant? Or fastest? Nobody will know if you cannot name the numbers to measure! And how to measure.
And even if that would be known, there simply is no way of knowing beforehand. Just think about someone saying "Use a database, this is always faster", and then you end up with a bad provider in a shared hosting system with an overloaded database system that delivers absolutely no performance, and you are like "no way is this database any faster than files" - and you are right. For the same reason, saying than NOT using databases is faster is a lie also.
Measure The Performance! Change something and see if it is faster. If it is, stay there, and go back otherwise.

How does windows azure websites handle session?

I was investigating one of the new offerings in windows azure. Specifically "Websites" and i'm not able to find anything about how it handles session data. Does anybody know? I moved the slider up to 2 instances and it all seems to "just work", but I would feel better about using it if I knew for sure it was sharing session data (or not?)
If you'd like to learn more about the architecture of Windows Azure Web Sites, I would suggest watching this session from TechEd 2012 Windows Azure Web Sites: Under the Hood
You have some options to solve this problem
sql solution
table storage solution
memcache solution
Sql is the classic solution. Sql handles all sessions with classic sql requests.
Table storage works wonders (in my experience). It's really easy to scale and really simple to implement (just a few lines of code on your webconfig).
Memcache solution is the best solution. Azure provides a cluster of "cache servers" to store session (or other serializable objects). It's really easy to scale and works really really fast. I am using this solution on my production environments with 0 problems and a really good performance results.
In order to implement Memcache, you just need to add those lines on your web.config:
<configuration>
<configSections>
<section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere"/>
<!-- more config sections here -->
</configSections>
<dataCacheClients>
<dataCacheClient name="default">
<hosts>
<host name="YOUR_NAME_HERE.cache.windows.net" cachePort="YOUR_PORT_HERE"/>
</hosts>
<securityProperties mode="Message">
<messageSecurity authorizationInfo="YOUR_KEY_HERE">
</messageSecurity>
</securityProperties>
</dataCacheClient>
</dataCacheClients>
<!-- more configurations here -->
Summary
If you don't care about the costs and you wish to archieve best performance possible, go for memcache solution. If you need to keep your costs really low, go for table storage.
Since the linked video above is quite out of date, I thought I would share what I was able to find regarding sessions on Azure.
Azure makes use of Application Request Routing.
ARR cleverly keeps track of connecting users by giving them a special cookie (known as an affinity cookie), which allows it to know, upon subsequent requests, to which server instance they were talking to. This way, we can be sure that once a client establishes a session with a specific server instance, it will keep talking to the same server as long as his session is active.
Reference:
https://azure.microsoft.com/en-us/blog/disabling-arrs-instance-affinity-in-windows-azure-web-sites/.
Are you targetting ASP.NET 4.5?
If you don't explicitly configure any providers with 4.5, it will default to using the ASP.NET Universal Providers which are now included in Machine.config. So it will be using a SQL Session State provider by default. I would expect it to use a local DB, though, so I'm not sure how it would be sharing the state.
You could test it by opening up some sessions, then taking the number of instances back down to one and see if some sessions lose state or not.
The load balancer could be using session affinity, in which case, you might not notice if it's not sharing session state.
How many web roles do you have? If you keep it to 1 you should be ok, but you can read the details here about how multiple web roles are going to create the same session state problems you'd encounter if you were running a web farm... When running a web farm an option is keeping session state in your db. So as you can imagine, if you needed to run multiple web roles then you could lean on sql Azure (though Table Storage is really cool, and likely a great fit for something like session state)
But to more directly answer your question, you can use multiple web roles to distribute processing load, and a web role is just a "front-end web application and content hosted inside of IIS". So again, if you're only using one web role then your app probably is working just fine. But just be aware that if you ever need to scale your web roles out, it will bork your Session persistence up.

Guidance for storing state in a database for a web application

I have some questions here and here the management of state in an ASP.NET MVC3 application. One of the answers mentions that an option for this is to simply store the state of each step in the database.
I was wondering if anyone had any advice on how this is usually achieved as I had some thoughts when this was first suggested to me.
Invalid entities
Consider a multi-step form (wizard) that has 3 steps. I could save each step in the database to maintain state but a user could close the web application midway through the process leaving my database containing entities that are in an invalid state.
To overcome this I could add a field to the table which indicates if the wizard has been completed. Any inconsistent items could be reviewed on a periodic basis and automatically deleted if required e.g. if any invalid entities are found in the database at the end of the day they will be automatically deleted.
The problem with this is that I have to add fields to the tables to store metadata about the application. Every table that stores information that is entered in a multi-step form needs to have these fields. This seems wrong to me somehow. One solution might be to create a specific table for managing this rather than polluting each entity table with metadata.
Intermediary database
I thought of having a database that sits in between my application and the 'real' database.
The intermediary database would have tables that stored the state information for each 'step' and only when the last step was completed would this information be transferred over to the 'real' database (and the temporary data deleted from the intermediary).
This also sounds similar to one of the session state options offered by ASP.NET already so personally I think this would be a waste of time.
Use in other application (E.G. Desktop)
At this moment in time my application is purely web based, but I have plans for having desktop programs that can interact with the same database. If the database has a load of meta-data used by the web application for storing state my desktop application is going to need to be aware of this in order to avoid any errors (I.E. my desktop application would need to know that it has to set an entity state as 'valid' so that the web application does not delete the entity at the end of the day because it thinks it is invalid).
Summary
So does anyone have any information or tips on how to best use a database for storing application state?
Is the database option that common?
Is it suitable for large applications with a lot of entities?
Are there any performance implications?
Edit
Just to be clear, I am aware that other options exist for managing state in an ASP.NET MVC application (TempData, cache and session) but I am specifically interested in information about using a database to manage state.
Please refrain from down-voting anyone that has mentioned the other options as my original question may not have been clear about this.
Why not store data in a session state? You just need to come up with a mechanism that would allow you to uniquely identify and store items in the session state.
To start with, you can use InProc session state mode. As the system grows, you can look into storing your session state on a state server or on a SQL server.
This is a hard one to answer, but basically, I'd see two routes.
If the data in a given step in the wizard is logically right, and meets all the constraints you've imposed, you could write it to your "main" database. For instance, if you've got a multi-step process for managing orders, and step one is to create a customer record if one doesn't already exist, write the customer record to the database when the user completes the form.
This means that if the user goes away, closes the browser or whatever, the data will be there when they come back - which is probably what they expect.
If the data in a given step is NOT coherent, does not meet constraints etc., use session state to manage it until it's ready for writing to the database. Session state in MVC is a bit of a pain, and you should use it sparingly - it makes it hard to write unit tests.
The purpose of session state is to store data that is relevant to the user session, but that isn't (yet) intended to go into the database.

What are the benefits of a stateless web application?

It seems some web architects aim to have a stateless web application. Does that mean basically not storing user sessions? Or is there more to it?
If it is just the user session storing, what is the benefit of not doing that?
Reduces memory usage. Imagine if google stored session information about every one of their users
Easier to support server farms. If you need session data and you have more than 1 server, you need a way to sync that session data across servers. Normally this is done using a database.
Reduce session expiration problems. Sometimes expiring sessions cause issues that are hard to find and test for. Sessionless applications don't suffer from these.
Url linkability. Some sites store the ID of what the user is looking at in the sessions. This makes it impossible for users to simply copy and paste the URL or send it to friends.
NOTE: session data is really cached data. This is what it should be used for. If you have an expensive query which is going to be reused, then save it into session. Just remember that you cannot assume it will be there when you try and get it later. Always check if it exists before retrieving.
From a developer's perspective, statelessness can help make an application more maintainable and easier to work with. If I know a website I'm working on is stateless, I need not worry about things being correctly initialized in the session before loading a particular page.
From a user's perspective, statelessness allows resources to be linkable. If a page is stateless, then when I link a friend to that page, I know that they'll see what I'm seeing.
From the scaling and performance perspective, see tsters answer.

Resources