how to learn best practices for state management in asp.net - asp.net

I am new in programming ,specially in web base programming. i want to learn best practices about state management techniques. I mean
when we have to create sessions?,
when to use sessions how to check null sessions? ,
when to use cookies ?
when to use hidden fields ?.
what are differences between all ?
which technique to use at certain time ?
how application may get crashes due to unsuccessful state management?.
which things we need to keep in mind about state management when we are developing the web applications...???
there so many questions . perhaps you guys known . please help me out to sort my confusion .
Thanks in advance !

http://www.thedevheaven.com/2012/05/state-management.html
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
Types of State Management
There are 2 types State Management:
Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:
a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.
b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.
c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.
d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.
e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.
Server – Side State Management
a. Application State - Application State information is available to all pages, regardless of which user requests a page.
b. Session State – Session State information is available to all pages opened by a user during a single visit.
Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.
Advantages
Advantages of Client – Side State Management:
Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.
Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).
Advantages of Server – Side State Management:
Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.
Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server

follow the links :-
Client - server difference in state management:
http://www.techbaba.com/q/858-difference+clint+side+management+server+side+management.aspx
http://www.dotnetfunda.com/articles/article61.aspx
Caching best practices :
http://msdn.microsoft.com/en-us/library/aa478965.aspx
state management Best practices :
http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx
Use state management techniques in c# :
http://www.c-sharpcorner.com/UploadFile/freelance91/ASPNETstatemanagementtechniques01012007212655PM/ASPNETstatemanagementtechniques.aspx

Sounds like you should just need to do some reading.
Pro ASP.NET - This book has a chapter about state management, but I am betting the rest of the book would be helpful to you as well since you are a beginner.
Also, MSDN has some good information about state management and when to use what.

Related

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.

Detailed and specific use of Asp.net Sessions?

Can any one help me in explaining the detailed and proper use of ASP.NET Sessions.
i read many web portals and blogs but i do not understand how to and where to use the sessions.
we create many sessions on page, for login, transfering some values from one page to another. but what is its impact on multiple users like more than 10000 users accessing the website, server transfer rate. memory storage, etc.
This may help many beginners, and also experienced person to properly use sessions in their project.
Any help is appreciated.
This is roughly how it works:
When the user visits your webpage, a session ID is set in a cookie in the user's browser. Each time the browser sends a request to the server, the browser will pass the cookie containing the session ID to the server. This allows the server to recognize the user and associate data with the user across multiple page requests (you can use sessions without cookies if you want to).
The server will by default store this data in memory. However, if multiple webservers are running the application and serving the same user, they will all need to know about the user's session data. Thus, you can configure your application to store session data using the "ASP.NET State Server" Windows service, or you can store the data in a SQL database (or you can write your own Session State Provider and store the data wherever you like). Moreover, storing the session data in memory is obviously a bad choice if you are worried your machine might crash (that obviously should worry you).
As for the "proper and detailed" use of ASP.NET sessions it is hard to say - it depends on what you are trying to achieve.
If you can help it, you should store only small amounts of data in sessions, as the combined sessions of all users visiting your website may take up quite a lot of space. Moreover, if you are using the ASP.NET State Server or the SQL Server session state stores the data you store needs to be serialized and deserialized, which will take a non-trivial amount of time for data of non-trivial size.
If what you are planning to store isn't confidential, an alternative approach might be to store the data in a cookie. That way your server will not have to worry about storing the data at all. This way you are trading memory (or disk space or whatever storage mechanism you choose) for bandwidth, as the cookie will now be part of the payload for every request.

ASP.NET caching with web services calls

Assume that you are developing a web application that shows currency
exchange rates for a bank web site. The rates are stored in an IBM
Mainframe in the bank and rates are available through web services.
Each time a user accesses the rates page, the page makes a request to
the mainframe. This generates too much load on the mainframe.
Especially most of the time the rates delivered is the same. How would
you design a caching architecture that minimises the trip to the web
service. But at the same time rates may fluctuate within the day and
if rates have changed the rates web page should not display the cached
values but make another request to the web service. How would you
design such a caching architecture and make sure it is invalidated on
rate changes? Please explain by drawing a diagram.
Can you tell me in this scenario how ASP.net will know that values are changed? what should I do?
The "Mainframe" must advertise to Web that the value has changed.
So you can, for example, implement another web service called "InvalidateCache()" that would empty the cache when called.
When the rates change, "Mainframe" would call InvalidateCache service which would empty the cache so that subsequent request to the Rate service would call Mainframe for new rates.
Following is the description:
Make a new webservice which stores just a token, that token could be anything like datetime or you can generate the token from any other algo.
When the user comes to that page on which currency rates needs to be shown, browser make a hit to that new service along with token.
If the client token matches with the server then the service returns true response otherwise false and sends the updated token too.
If response is true then the browser gets data from it's cache.
If it's false then the browser stores the updated token and calls the main webservice gets data from there and stores it in it's cache.
Whenever the currency rates changes, token in new webservice needs to be updated.

ASP.NET Maintaining Search History in an application

Recently i received an interview question.
How to maintain search day to day search history in an asp.net application?
Which one of the below would be the right choice?
1)Cookies 2) Sql Server 3) Session State
I guess the correct option could be Cookies.Please kindly share your thought.
SQL Server is the most reliable way of maintaining whatever. Cookies cannot generally be relied upon, and sessions expire and lose all data.
So the question boils down to: if you need to mainain long-term historical records, go with SQL Server. If you want to show what a particular user has searched for, go for session (or cookies, but they're somewhat size-limited).
All 3 options are acceptable in different scenarios for many different reasons - it's a softener question designed to get you thinking and talking:
(1) Cookies - for a per user / browser session provides a client-side solution (provided the user accepts / does not delete them) and you don't care that this can happen. However, this does tie the user to the browser. Useful for anonymous per-user browsing but not if your intention is to keep or query the history.
(2) SQL - guarantees history is saved server side but you would need a mechanism such as a client login to associate the history with the user and the only solution of the 3 presented that would allow you to perform any sort of historical multi-user analysis / analytics.
(3) Session state - not advisable - but arguably similar to cookies but without the caveat that cookie acceptance is required - however you introduce the timeout issue and again tie the user to the browser and limited lifetime of the information.

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