Using HttpContext.Current.Application to store values - asp.net

We have an ASP.NET page running on .NET Framework 4.0.
At the moment we store some values that should be available during the entire lifteime of the application in HttpContext.Current.Application["keyToTheValue"].
Is this the wrong place to store values, that we need for an indefinite time,
or how can we configure the application to not recycle those values?
Oh, important to notice: We actually run the page in integrated mode, maybe this has some influence on the Application caching.

If your data is sensitive then store it in your DB for using it lifetime..it it's not that much sensitive then use persistent Cookies and set it's expiration period to max...

There's nothing wrong with using the Application object, but if you want to persist your data even in the event of an application close (which is bound to happen sooner or later), you might be better off storing your values in a database.

It depends on the data, and environment, but for simple data using the application for global values is probably fine. You should look at the System.Web.Caching namespace for more advanced scenarios. Also, if you are in a web farm or cluster of some sort, you may need to roll your own global data store so you can share it across multiple servers.

There is no issue in storing your data in Application.But it has limitation that it reset with the reset of IIS.
So use it according to your scenario.

Related

asp.net web application, where is a good place to store and reuse values that change frequently?

I have a requirement to create a high performance asp.net web application. The page when requested needs to pull in some financial rates, these rates originate from a legacy system where directly calling it with each page load would result in a substantial performance loss.
My initial idea was to have a cached version of the rates sitting in SQL server and pull from there. This way when rates do change the legacy system can call a web service which can update this SQL table.
Still I wasn't happy leaving it like that - this would mean a lookup to SQL with each page request.
I started thinking about using a global variable. To hold the rates. But then I was left wondering how the legacy system is going to update the asp.net web application global variable value. This could get tricky.
So what is the best approach given performance is key. I'm thinking that call to SQL server might not be a bad idea, since it will be a straight table select. But then again - maybe there is another way to do this which is better?
Thanks in advance....
You can cache using SqlCacheDependency. So no need to worry about updating data. Once your data is changed in the database, it will reset the cache and then next request will rebuild the cache.

In ASP.Net web farm is database dependent Caching a good approach?

I was looking at using data caching with database dependency for a web farmed ASP.Net app. So each web server in the web farm would automatically refresh its Cache value as soon as the database value changes. This would appear to keep all Cache values across the web servers synchronized. Does this sound like a good idea or I am missing something?
No. It does not mean all servers will refresh once the value in the db refreshes, unless you use something like SqlCacheDependency. Take a look # the following link for that: http://www.asp.net/web-forms/tutorials/data-access/caching-data/using-sql-cache-dependencies-vb
Otherwise the mechanism simply involves looking into the database and taking the value from there. There might be sql jobs which might refresh the value. Hence it is different from above.
Note: for SqlCacheDependency you need to use MSsql 2005+ server.
The other tecnique would be to employ the use of web hooks in your solution...

When building composite controls and using session, can they conflict with host application?

I wrote a composite web control that is used in several web applications. If I use sessions variables, for example HttpContext.Current.Session("MyProgramMemberId"), do I run the risk that the host site might have also defined that same session key name?
I'd like to hear of your experiences if you had a problem with this. It would be a bonus if you have website reference that you trust.
Thanks!
I can't say that I have any actual experience with this (mainly because I wouldn't do this), but yes it's absolutely possible that you could have a collision with another session variable named the same thing in the hosting web application.
What I would suggest is removing the reliance on the session variable, and instead use a ViewState variable instead. These are more isolated to specific instances of your control, and therefore should not conflict with each other. Of course there are considerations based on what you need to store, you would want to be careful trying to store large objects, lists, dictionaries, as well as sensitive information in the viewstate (which ends up being transmitted to the client). But based on your sample code, it looks like it's a simple Id property which is small and (usually) not sensitive.
It also depends on how you setup your website. If you are re-using the control in different web applications but on the same site it should not be an issue. If you are re-using them in the same application this would be a design issue.
If you are asking if you need to be worried if your session names will collide if you go to a shared host you will not need to worry. The thing you will have to worry about is if you are storing your session InProc. If you are storing your values InProc and your site is load balanced there could be issues as the balancer chooses different servers to serve your content.

Static variable across multiple requests

In order to improve speed of chat application, I am remembering last message id in static variable (actually, Dictionary).
Howeever, it seems that every thread has own copy, because users do not get updated on production (single server environment).
private static Dictionary<long, MemoryChatRoom> _chatRooms = new Dictionary<long, MemoryChatRoom>();
No treadstaticattribute used...
What is fast way to share few ints across all application processes?
update
I know that web must be stateless. However, for every rule there is an exception. Currently all data stroed in ms sql, and in this particular case some piece of shared memory wil increase performance dramatically and allow to avoid sql requests for nothing.
I did not used static for years, so I even missed moment when it started to be multiple instances in same application.
So, question is what is simplest way to share memory objects between processes? For now, my workaround is remoting, but there is a lot of extra code and I am not 100% sure in stability of this approach.
I'm assuming you're new to web programming. One of the key differences in a web application to a regular console or Windows forms application is that it is stateless. This means that every page request is basically initialised from scratch. You're using the database to maintain state, but as you're discovering this is fairly slow. Fortunately you have other options.
If you want to remember something frequently accessed on a per-user basis (say, their username) then you could use session. I recommend reading up on session state here. Be careful, however, not to abuse the session object -- since each user has his or her own copy of session, it can easily use a lot of RAM and cause you more performance problems than your database ever was.
If you want to cache information that's relevant across all users of your apps, ASP.NET provides a framework for data caching. The simplest way to use this is like a dictionary, eg:
Cache["item"] = "Some cached data";
I recommend reading in detail about the various options for caching in ASP.NET here.
Overall, though, I recommend you do NOT bother with caching until you are more comfortable with web programming. As with any type of globally shared data, it can cause unpredictable issues which are difficult to diagnosed if misused.
So far, there is no easy way to comminucate between processes. (And maybe this is good based on isolation, scaling). For example, this is mentioned explicitely here: ASP.Net static objects
When you really need web application/service to remember some state in memory, and NOT IN DATABASE you have following options:
You can Max Processes count = 1. Require to move this piece of code to seperate web application. In case you make it separate subdomain you will have Cross Site Scripting issues when accesing this from JS.
Remoting/WCF - You can host critical data in remoting applcation, and access it from web application.
Store data in every process and syncronize changes via memcached. Memcached doesn't have actual data, because it took long tim eto transfer it. Only last changed date per each collection.
With #3 I am able to achieve more than 100 pages per second from single server.

ASP.NET Masters: What are the advantages / disadvantages of using Session variables?

I've done a search on this subject already, and have found the same data over and over-- a review of the three different types of sessions. (InProc, Sql, StateServer) However, my question is of a different nature.
Specifically, what is the advantages/disadvantages of using the built in .NET session in the first place?
Here is why I am asking: A fellow .NET developer has told me to NEVER use the built in Microsoft Session. Not at all. Not even create a custom Session State Provider. His reasoning for this is the following--that if you have the Session turned on in IIS it makes all of your requests happen synchronously. He says that enabling session degrades the performance of a web server.
His solution to this is to create a session yourself-- a class that stores all values you need and is serialized in and out of the database. He advises that you store the unique ID to reference this in a cookie or a querystring variable. In our environment, using a DB to store the sessions is a requirement because all the pages we make are on web farms, and we use Oracle-- so I agree with that part.
Does using the built in Session degrade performance more than a home-built Session? Are there any security concerns with this?
So to sum it all up, what are the advantages/disadvantages?
Thanks to all who answer!
My experience has been that the session is a good means of managing state when you use it appropriately. However, often times it's misused, causing the "never ever use the session" sentiment shared by many developers.
I and many other developers have ran into major performance issues when we mistakenly used the session to store large amounts of data from a database, so as to "save a trip." This is bad. Storing 2000 user records per session will bring the web server to its knees when more than a couple of users use the application. Session should not be used as a database cache.
Storing an integer, however, per session is perfectly acceptable. Small amounts of data representing how the current user is using your application (think shopping cart) is a good use of session state.
To me, it's really all about managing state. If done correctly, then session can be one of many good ways to manage state. It should be decided in the beginning on how to manage state though. Most often times, we've run into trouble when someone decides to just "throw something in the session".
I found this article to be really helpful when using out-of-process modes, and it contains some tips that I would have never thought of on my own. For example, rather than marking a class as serializable, storing its primitive datatype members in separate session variables, and then recreating the object can improve performance.
Firstly, you colleague is implementing his own DB backed session management system, I do not see what advantage this has over using built in session state stored on a database (MS SQL is the default, there is no reason not to use Oracle instead).
Is his solution better than the built in one? Unlikely. It's way more work for you for a start. Here's a simple illustration of why. Let's say you use cookies to store your ID, how do you cope with a user who turns off cookies? If you are using ASP.Net's session state there's no problem as it will fall back to using the query string. With your colleagues idea you have to roll your own.
There is a very valid question as to whether you shold have session state at all. If you can design your application not to need any session state at all you will have a much easier time scaling and testing. Obviously you may have application state which needs to live beyond a session anyway (simple case beign user names and passwords), but you have to store these data anyway regardless of whether you have session state.
The MS implementation of Session State is not evil in and of itself... it is how some developers use it. As mentioned above, using the built-in session state provider means that you don't have to reinvent the security, aging, and concurrency issues. Just don't start jamming lots of garbage in the session because you're too lazy to figure out a better way to manage state and page transitions. Session doesn't scale really well... if each user on your site stuffs a bunch of objects in the session, and those objects take up a tiny bit of the finite memory available to your app, you'll run into problems sooner than later as your app grows in popularity. Use session in the manner for which it was designed: a token to represent that a user is still "using" your site. When you start to venture beyond that, either because of ignorance or laziness, you're bound to get burned.
You should be judicious in your use of Session, since multiple requests to the same Session object will usually be queued: see "Concurrent requests and session state" http://msdn.microsoft.com/en-us/library/ms178581.aspx.
Note that you can set EnableSessionState to ReadOnly to allow concurrent read access to session state.
This queuing is a good thing, as it means developers can use Session without being concerned about synchronization.
I would not agree with your colleague's recommendation to "never" use Session and I certainly wouldn't consider rolling my own.
First, a browser will only make two requests, to a given hostname, at a given time. For the most part these requests are for static content (JS files, CSS, etc). So, the serializing of requests to dynamic content aren't nearly the issue that one might think. Also, I think this may be confused with Classic ASP, where pages that use Session are definitely serialized, I don't believe this is the case with ASP.Net.
With ASP.Net session state (SQL mode, state server, or custom) you have an implementation that is standard, and consistent throughout an application. If you don't need to share session information this is your best bet. If you need to share information with other application environments (php, swing/java, classic asp, etc.) it may be worth considering.
Another advantage/disadvantage is that there has been a lot of developer focus on the built-in methodology for sessions with regards to performance, and design over rolling your own, even with a different provider.
Are there any security concerns with this?
If you roll your own you'll have to handle Session Fixation and Hijacking attacks, whereas using the built-in Session I think they are handled for you (but I could be wrong).
the home made session as you have described is doing nothing different "SQL" state of .Net sessions and in my experience i dont think session degrades your performance in anyway. building your own session manager will require putting in several other plumbing tasks along - security, flushing it out, etc.
the advantage with in-built sessions is its easy to use with all this plumbing already been taken care of. with "SQL" mode you can persist the session data in database thus allowing you to run your app on web-farms without any issues.
we designed a b2b ecommerce app for fortune 57 company which processes over 100k transactions a day and used sessions [SQL mode] quite extensively without any problems whatsover at all.
Correct me if I am wrong:
The primary advantage of storing Session state in a db, e.g., SQL Server, is that you are not consuming memory resources, but instead storing it to disk in a db.
The disadvantage is that you take an IO hit to retrieve this info from the database each time you need it (or maybe SQL Sever even does some magic caching of the data for you based on recently executed queries?)
In any event, this the price an IO to retrieve the session info from a db per trip to the web server seems like a safer strategy for sites that encounter a lot of traffic.

Resources