ASP.NET 4.0 Object Caching - asp.net

There are two kind of caches that need to be implemented: Global and Session Level.
The session level cache will store certain user specific data like Cart Items, user priviliges etc.
The global cache will store some data common to all the users in a subdomain.
So each subdomain will have a seperate global cache and each user(logged or not) might have a session/user specific cache.
I am thinking of using object caching features provided in 4.0 version of framework using System.Runtime.Caching. Wrapping the basic functionality inside a custom entity.
Another thing that comes to my mind is that the singleton pattern might do the trick, not sure though.
Also to keep in mind that the Website is hosted on a web farm.
Anyone can suggest how to go about this or point me in the right direction on how to implement this?

If your site is on a web farm, then you might consider using Memcached. It's a in-memopy key=>value caching. All you have to do is prefix your session-level cached objects with the sessionID.

I think you should use distributed cache like NCache where you can keep one cache for storing sessions and the second cache for storing the objects. There is a session store provider module that you can plug in with your application and it will store the sessions in an outproc distributed cache automatically. And, you can also store your objects in a key-value pair either in the same cache or different cache by using the API.
There is a free edition available for NCache that you can download and play with
http://www.alachisoft.com

Related

NHibernate SysCache storage

I am using Nhibernet with SysCache Provider for second level cache in an Asp.net MVC 4 application. Somewhere i found that SysCache use ASP.Net default cache system to store the cache items. To reduce the use of my limited RAM, i have implemented my custom cache provider which store data in MongoDB.
Now my question is, as i am using my custom cache provider using mongodb, where will be the nhibernet second level cache data stored? Is in mongodb by my custom cache provider or it still will be in RAM?
By the way, my ultimate target is, i want the NHibernet second level cache using SysCache or any other free cache provider but not want to store the cache items in RAM rather in mongodb. Please give a better suggestion to achieve it.
regard
Habib
Now my question is, as i am using my custom cache provider using mongodb, where will be the nhibernet second level cache data stored?
As you have already developed mongo's SLC and if you change settings the data will be probably in mongo ... ?
The point of caching is to provide faster way how to obtain/fetch frequent data than select them from original database.
Your approach makes perfect sense to work correctly with limited memory but I'm not sure whether it will improve the performance of your application how the point of SLC would require.
You store cached data as document/blob in mongo? Have you compare performance against original cache and w/o cache?
If your solution would be successful it requires to develop mongo's cache better than your original queries against RDBMS. This does not have to be true by default. Depends on your purpose and queries you use.

Best caching framework for asp.net application

I have an order system developed on asp.net 4 web forms. I need to store order details (order object) for a user on the cache in order to manage it till I save it in the DB.
I want to install my site at least on two server with option to scale for more in the future .
As you know , the two servers are located behind load balancer , so I need the cached order object to be shared on the both servers.
I hear about App fabric.
Any recommendation to good frameworks to do that , Hope will be simple and easy to maintain one .
Thanks in advance ...
I need to store order details (order object) for a user on the cache
in order to manage it till I save it in the DB.
If your data is not persisted, SQL Server-based Session state will work across machines on a per-user basis and can be configured with a minimum of fuss.
However, I would suggest regularly saving the order to your application database (not just the Session database) so that the user doesn't lose it. This is fairly standard practice on e-commerce sites. Unless the order process is very short, inevitably the user will want to pause and return, or accidentally close the browser, spill coffee into their computer, etc.
Either way, the database makes a good intermediate and/or permanent location for this data.

What is the difference between (Caching) and [storing] variables in session?

What is the difference between (Caching) and [storing] variables in session???
These are two different concepts with a different purpose (although their implementation may share some common infrastructure).
The purpose of caching is to improve performance, by eliminating the need for redundant server-side processing between requests. Caching can happen at the database level (e.g. by storing query results), the page level (by storing fully rendered HTML pages), or the page-component level (by storing HTML snippets). Caching can also be specific to the user and other parameters. An application that serves stock portfolios might cache its pages per user so that one user is not accidentally served another person's portfolio from the cache.
The purpose of session variables is to add state to web applications (the HTTP protocol is inherently stateless and there is no other way of keeping data around between requests).
If by caching you are specifically referring to the System.Web.Cache class, then the key difference between this and Session is that Cache is global to the application whereas Session is specific to a user.
Caching is a general term covering many possible implementations and options.
One such implementation is the Session variables in IIS, with the addition constraint of it being user specific (or user session specific, to be exact).
Others implementations can be the Application variables, browser cache, caching proxy servers, special caching software that sits between an application server and database and even CDNs (content delivery networks).
See the wikipedia article about cache.

ASP.NET In a Web Farm

What issues do I need to be aware of when I am deploying an ASP.NET application as a web farm?
All session state information would need to be replicated accross servers. The simplest way would be to use the MSSQL session state provider as noted.
Any disk access, such as dynamic files stored by users, would need to be on an area avialable to all servers. Such as by using some form of Network Attached storage. Script files, images and html etc would just be replicated on each server.
Attempting to store any information in the application object or to load information on application startup would need to be reviewed. The events would fire each time the user hit a new machine in the farm.
Machine keys across each server is a very big one as other people have suggested. You may also have problems if you are using ssl against an ip address rather than a domain.
You'll have to consider what load balancing strategy your going to go through as this could change your approach.
Sessions is a big one, make sure you use SQL Server for managing sessions and that all servers point to the same SQL Server instance.
One of the big ones I've run across is issues with different machineKeys spread across the different servers. ASP.NET uses the machineKey for various encryption operations such as ViewState and FormsAuthentication tickets. If you have different machineKeys you could end up with servers not understanding post backs from other servers. Take a look here if you want more information: http://msdn.microsoft.com/en-us/library/ms998288.aspx
Don't use sessions, but use profiles instead. You can configure a SQL cluster to serve them. Sessions will query your session database way too often, while profiles just load themselfs, and that's it.
Use a distributed caching store like memached for caching data, and ASP.Net cache for stuff you'll need alot
Use a SAN or an EMC to serve your static content
Use S3 or something similar to have a fallback on 3.
Have some decent loadbalancer, so you can easily update per server, without ever needing to shut down the site
HOW TO: Set Up Multi-Server ASP.NET Web Applications and Web Services
Log aggregation is easily overlooked - before processing HTTP logs, you might need to combine them to create a single log that includes requests sent to across servers.

ASP.NET State Management in appropriate situations

There are 6 techniques to manage states in ASP.NET 3.5 (as far as I know).
(1) View State
(2) Cross Page Posting
(3) Query String
(4) Session State
(5) Application State
(6) Cookies
Can anyone give me some appropriate examples of situations where I should use these techniques?
For example:
(*) Session State: Personalization, Buy Cart, etc.
(*) Cookies: Saving User Credentials, etc.
There's a lot of factors that can influence this, so I won't comment on all of them. But here are a few pointers:
ViewState - This is useful when you'll be posting back to the same page frequently (something you're practically forced into doing by ASP.Net Webforms). How useful it is exactly changes depending on what kind of app you're building. For public internet sites, it should be used very sparingly. You may even want to turn it off by default. For local intranet sites, it's a great tool — especially for the fewer, heavier, webforms pages.
Query String - Use this to store state that you need to allow the user to bookmark a page or process and come back to much later. Even then, you might want to keep it down to some kind of hash that you can use as a key in a database lookup to avoid a really huge url (though hashes have their own problems). Also, a lot of users like to fiddle with your query string directly, so it can be dangerous to put too much here. It's easy to accidentally expose data to users who aren't supposed to see it this way.
Application State - Remember that this is shared by all users, so use appropriately. Things like view counts can go here.
Cookies - Don't use cookies to store user credentials. They're just plain unencrypted text files. Use cookies to store a key into the session (even here you can and should now use cookie-less sessions) and simple personalization settings that will be specific to that user and browser. For example, my monitor size at work is different from home, and so putting display size/layout settings into a cookie is nice because the settings stick for each computer, but it isn't going to compromise my security any if someone else reads that information.
Now I want to highlight this concept from the "Query String" section:
you might want to keep it down to some kind of hash that you can use as a key in a database lookup
Again, hashes have their own problems, but I want to point out that several items on my list talk (including Query String) about uploading data from the client web browser to the web server: ViewState, Query String, Cookie, and Cross-Page Post. You want to minimize the data that you move from client to server. This concept applies to all of these, and for several reasons:
Pulling data from the client is slow for public internet sites. Even broadband connections typically cripple the bandwidth available for upload. 512Kpbs (still a typical broadband upload rate in many areas) is nothing when compared to the Gigabit Ethernet (or faster) connection that likely sits between your database and your web server. As much as you might think of a database query as slow (and it is), it's still likely a much better way to go than waiting for the same data to arrive from the client.
Keeping the data on the server is cheaper, because you don't pay for the bandwidth required to push it to or from the client, and bandwidth often costs as much or more than your server hardware.
It's more secure, because if done right even when a client's computer or connection is compromised all the hacker has access to initially is a hash key that likely expires by the time he can decrypt it. Of course, if done wrong he can use that key directly immediately, so you still need to be careful.
So for most things, what I recommend is to start out by keeping a database key in the Session and then have code to easily pull what you need from a database based on that key. As you experience bottlenecks, profile to find out where they are and start caching those pages or controls, or keep that data/query result in the session directly.
State management option
View state:
Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.
Control state:
Use when you need to store small amounts of state information for a control between round trips to the server.
Hidden fields:
Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue.
You can use a hidden field only on pages that are submitted to the server.
Cookies:
Use when you need to store small amounts of information on the client and security is not an issue.
Query string:
Use when you are transferring small amounts of information from one page to another and security is not an issue.
You can use query strings only if you are requesting the same page, or another page via a link.
Server Side Management Options
Application state
Use when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session state
Use when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Profile properties
Use when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application.
Database support
Use when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.
Not sure if you mean the Cache object by Application State.
The Cache object is a great way to manage application wide state, e.g. to record source and count access to your website (to prevent DDOS attacks for example).
(3) Query String
(4) Session State
(5) Application State
(6) Cookies
1. Viewstate
Disclaimer: Use as little as possible. Good point is to always have each state reachable by an url, if possible.
F.e. Paging should use the URL (so /url/?p=2 instead of storing the page in Viewstate)
Use to persist control state between page-cycles.
F.e. Store the selected item in a checkbox, so you can determine whether it has changed.
2. Cross Page Posting
Don't. See the disclaimer for viewstate. Use the URL for this, or store the data in a session / cookie / profile if loads of properties need to be kept around.
Major downside of CPP is that the user cannot use the 'Back' and 'Forward' buttons in it's webbrowser. When a user clicks the back button it wants to undo everything on that page and retry the last one. When using CPP to click them through a wizard; this behavior is not possible without a lot of 'Are you sure you want to resend blablablabl'.
3. Query String
Use alot. Every visible state that a page could reach should be accessible by URL. People with screenreaders will thank you for this. And by using the query string there is no need to use javascript-only solutions.
/url/?page=2 // when doing paging, don't use postback for this
/url/?tab=advanced-search // when having tabs on top of your page
etc.
4. Session state
Use this for short-living objects, that only make sense this time the visitor visits your site. For example:
Which step of a certain wizard was reached
Pages a user had visited before
Small objects you want to put in cache, but that are user-bound
Don't use sessions but profiles for things like:
Preferences
Selected language
Because those things also make sense the next time the user visits your site.
5. Application state
Never. Use ASP.NET cache, or memcached, or any caching framework for this.
6. Cookies
Session ID, Profile ID for authenticated users; user preferences for anonymous users (everything listed in the second list under 4.).

Resources