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

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.

Related

Is there a way to prevent content caching or scraping from an API?

Imagine the following situation. I have an API and a developer builds an application that retrieves new content from it on a daily base. She stores this content and provides this data to all the instances of an app she developed. In this way these apps do not have to call the API directly.
Is there a way to prevent this and force the apps (and therefore the end users) to use the API and not only the application on the server.
I found many questions about how to cache API data but not how to prevent that. I am fairly new to this, so maybe I am overlooking something or maybe it is not possible to prevent this.
Thank you in advance!
Assuming you are using Apigee for API-management, you have some options. First, consider the options available to you contractually, if this is that sort of business relationship and you can impose certain API behavior with a business partner through a contract.
Separate from the legal side of things, we remember that you control your API and the credentials you issue for use by your API clients. You cannot though control, practically, what a client developer does with the credentials you issue: she could promise to embed the credentials in the mobile apps' API client, but change her mind and use it centrally, and then design her mobile client to call into her central cache. If though you really insist that only mobile app clients should be calling your API and not a hub/cache server, then you could consider applying constraint policies on your API (within the Apigee proxy, such as Access Control). For instance, you could blacklist your partner's hub/cache server IP address, although that is weak security at best. Or, you could apply a constraint that only clients with certain identifying User-Agent strings (mobile OS, client) are allowed to connect to your API. Or use GeoIP filtering to allow only clients from certain regions, if that applies to your use-case.
Finally, depending on the data model, you might be able to rate-limit such that a bulk cache becomes impractical: if your edge-client use-cases is to fetch a single record, but a cache would have to hold thousands of records, then you could impose a per-client rate limit (Quota policy) which is no bother to individual mobile clients, but makes the work of a hub/cache server untenable.

Manage ASP.NET state on website for mobile devices

I have taken over development on an ASP.NET web forms app that is 100% designed to be used on mobile devices. Currently, the app makes very heavy use of session variables. The mode is default.
<sessionState timeout="600"></sessionState>
It won't surprise you that the app is buggy, and much of it's problems have to do with session data being lost, or, the entire session being lost.
Just some overview of the app in general:
No sensitive (security risk) data is stored in the session
The data in the session is small, but mission critical. No huge objects. Just a few INT's (Id's, etc), some strings, etc.
We have to assume that the user's bandwidth will be low, and that connectivity will be spotty
The data is unique per user
One of my suggestions to management about how to make this app better is to stop using Session variables and to use something else instead. I'm of the opinion that switching to cookies to store all of this data is a better way to handle this. I'm aware that some users may disable cookies (even on their mobile devices), but if that's the case, we can simply inform them that to use the site, they need to turn cookies back on.
I thought about using query strings, but simply from a programming stand point (building links, etc) query strings are a pain to work with.
I've come to this conculsion after reading this MSDN article about the various ways to persist State data, and each of their pro's and con's:
https://msdn.microsoft.com/en-us/library/z1hkazw7.aspx
My question here is: Are cookies the best alternative?
Cookies are limited in size and aren't really the best place if you've lots of variables. Also people don't like cookies, so may restrict them.
The ViewState is a great place to store data though. This is sent as a postback from your web forms and can be used to store reasonable amounts of data. For example if your application uses several pages to complete a process (e.g. ordering something), then you can persist data in the ViewState and this will be available when the page is posted back.
Used in the right way, the ViewState is very effective.

ASP.NET 4.0 Object Caching

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

Session sharing issue

I am facing an issue when we are using multiple tabs since its sharing the same session. Any alternatives to this? Can we create a unique session when someone uses the tab or CTRL+N.
It's a Java EE/Struts2 enterprise application if this matters.
This is a problem all server-centric web applications face, it's not specific to Java EE. The problem is that most browsers store cookies on a per-user basis, not per tab. Also, this behaviour is not generally transparent to the user, adding to the confusion. A few solutions I can think of (although none of them is really satisfactory):
Host the application under more than one URI. This way, any browser will store cookies independently, and consequently, you have one session per application version.
Propagate session IDs through a different mechanism, e.g. through the URI. This, however, has a few caveats - it exposes the session ID to the user, it makes for ugly URIs, and it forms a security risk (session hijacking and such) when users copy-paste or bookmark the current URI (because they then store the session ID in the link).
Propagate session IDs through hidden fields inside the page. This solution probably requires you to rewrite part of the built-in session handling, and it loses the session ID when your page contains links to other pages within your application.
For Firefox, there's an add-on called "cookie pie", which allows users to have independent cookie stores for some or all tabs. Downside is that users have to actively enable it, and working around the tab problem becomes the user's responsibility. Also, it doesn't work under all circumstances (e.g., google finds your active login regardless).
Avoid using session state, and use other mechanisms to preserve state between requests. Like passing session IDs through hidden fields, this breaks under certain circumstances.
Make the application fully client-centric, that is, program the entire interface in javascript and communicate with the server through ajax calls. This way, you won't depend on the browser's cookie implementation at all. Chances are you'll have to rewrite substantial amounts of code though, assuming your application is basically working already.
There is no simple way to achieve this that I know of.
The usual way to fix this is to change the app so that it can deal with users using multiple tabs (if possible).
There are several workaround ideas for how to "disable" the old window if the user presses Ctrl+N while walking through a multi-step form, but you'd have to give more detailed information for ideas on that.
Usually a browser instance is treated as a single user/entity for session tracking purposes. Especially if you are using cookies to track the sessions. I am not sure that I like the idea of allowing different tabs to have different sessions. It feels unintuitive for web based applications. All IMHO, of course.
That said, if you want to change this you will have to come up with a custom implementation. Perhaps you can generate and attach different session ids to the URL for different tabs. Never tried this myself so do not know how easy or difficult it will be.

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