How can i keep a data table thorough out my page? - asp.net

Hii,
I have a data table, and this datatable will be dynamically manipulated. After certain manipulation at the end we will populate that to the database. Which state mechanism can i use for this to retain. I have tried both Session and ViewState but ViewState can't use with AJAX rich appplications. Session will be clear after the user session. i can't afford both these difficulties. Does any other mechanism to keep the datatable through out the page.

You can use Application variables if you need to persist state between users or sessions.

Have you considered storing your Session state in SQL Server? This would avoid the timeout of the session in IIS.

Have you considered using the ASP.NET runtime cache?
Cache["Foo"] = bar;
This cache is kept in memory and "lives" as long as the host application does.

Related

Rethinking user controls and sessions

Throughout my application I generally use a lot of server/user controls (both ASCX and VB server controls) that work with update panels. These controls regularly make updates to both themselves and the applications database. A common control I might have is a control similar to a gridview. To persist data across update panel's update I will store the dataset (a list of objects) in a session and read/write to is as needed.
I've recently come to a point, though, that the memory needed to do this on a given page is exceeding the memory allocation on IIS. As such, I need to start thinking about how I can redesign these controls.
Is there a better solution to persisting data across partial postbacks than using sessions? I don't have the options to use any other session types, other than inProc (no db session or server farm session). Would using caching of these datasets be a better option?
Thanks for any advice
jason

Do session variables work differently during development?

I'm building a website with ASP.NET MVC3. When a user signs in, I pull their display name from the database and store it to a session variable:
Session["DisplayName"] = user.Display;
Then in _Layout.cshtml I use it to display at the top of each page:
<span class="user">#(Session["DisplayName"] as string)</span>
This works fine when I start debugging the website then log in, but if I then rebuild my server and begin debugging again, my browser remains logged in but the Session variables are cleared. This leads to a bunch of empty spaces where my display name should be.
Is this a side-effect of rebuilding the server, and not something I need to worry about in deployment? Is there a way to invalidate logins every time I rebuild, so that I avoid this issue? Or is there a better way to store this user data, other than a Session variable?
Is this a side-effect of rebuilding the server, and not something I
need to worry about in deployment?
Oh no, that's something that you absolutely should worry about. As you know ASP.NET session is by default stored in server memory. And when the AppDomain is recycled (which could happen at absolutely any time) by IIS all your session is gone. For example IIS could bring down the AppDomain after a certain inactivity on the application. Or after certain CPU or memory usage thresholds are reached. If you want to be able to reliable store something in the ASP.NET session you could offload the storage off-proc and store this session either in a dedicated session server or SQL. But honestly, I have seen many people moving ASP.NET Session to SQL Server and regretting it. What's the point? You already have this information in SQL Server :-) I once used this and regretted it so much.
Personally I never use ASP.NET Session in my applications. If you need to persist such information as the display name and avoid hitting the database at each request you could store it in the User Data section of the Forms Authentication cookie. So here's the idea: when the user successfully inputs correct credentials, you manually create a FormsAuthenticationTicket and populate its UserData property with whatever information you want to be available about this use on each request and then emit the authentication cookie. Then you write a custom Authorize attribute in which you decrypt the cookie, fetch the User Data and store it as a custom IIdentity making it available on each request.
Store usernames in cache (Cache[string.Format("DisplayName_{0}", User.Id)] = User.Username), cookies or move session to SQL Server instead of InProc
I would create a static helper method that gets username by user id. If it finds cached value, it will use that, if not, get value from db, store it in cache and return.
public static string GetUsername(int UserID)
{
string cacheKey=string.Format("DisplayName_{0}", UserID);
if (HttpContext.Current.Cache[cacheKey]==null)
{
// Retrieve user name from DB
string Username=Repository.GetUserName(UserID);
HttpContext.Current.Cache[cacheKey]=Username;
}
return HttpContext.Current.Cache[cacheKey].ToString();
}
There are better ways, but to address your specific issue your auth timeout and session timeout are not the same, you need to handle the case specifically when one will timeout before the other. See my post here:
How can I handle forms authentication timeout exceptions in ASP.NET?

Where is ViewState stored?

Where is a ViewState Stored? Is it stored in Server or Client Side?
I have a huge data which should be stored for some process. I was using Session. But when moved from one page to another im not able to clear the session. So I thought of implementing ViewState. But when running with huge amount of data ViewState is throwing error?
How can I resolve this?
Viewstate is stored on page it self in encoded form. You can't access the viewstate in client side in a direct manner. You need to know the encoding/decoding algorithms to fetch the valuable data from this viewstate in clientside code.
You can use hidden variable to store data that will be used only on that page. Hidden variables are accessible from client side and server side code.
You can use Cache or session to store datatable (large data). They will have good performance as compare to ViewState.
The Cache is always using the machine's memory, the Session uses what has been configured:
In a web farm the Session can be local (which works only if affinity is set), or remote (state server or database, or custom), but the cache is always local.
So, storing a DataTable in the cache will consume memory, but it will not use serialization.
PS: storing a DataSet instead of a DataTable will change almost nothing.
Refer Cache Implementation
The ViewState is not stored on either side, it's send back and forth between the server and the browser on every request and response, so it's not a good idea to put a huge amount of data in ViewState.
ViewState is stored where you tell it. By default, this is in a hidden field on the page sent to the client.
ASP.NET can also store ViewState inside the Session, i.e. on the server, if you tell it to.
Save large amount of data in view-state slowdown your site.
Use query string to fetch fresh copy from database on each page rather than save whole information from previous page.
View State Information stores in hidden fields.
Information travels between server and client in this hidden fields.
For asp.net control,.. by default .net implements view state for all its control, thats why a textbox value does not lost when we click on a button of that page.

asp.net server side viewstate without sessions

So I've done my best to minimize my viewstate on my ASP.net ajax application, http compression, disabling viewstate in hidden fields, but would like to go further. So after researching it seems that there are two approaches
a) use the ASP.net 1.x way which uses LoadPageStateFromPersistenceMedium
b) or use the ASP.net 2.x way SessionPageStatePersister
So B doesn't look good because if I understand it correctly the viewstate would be linked to the session id, and since my session can expire for any number of reasons I want don't want this.
So what's the best approach to saving viewstate on the server that does depend on sessions?
If it's LoadPageStateFromPersistenceMedium and uses hidden fields, then how do I inject a hidden field with a random id into a page?
How do I determine when it's time to clear viewstate files on the server?
I think you should seriously consider the Session option. It's optimal on resources and even if the Session expires if your Auth mechanism is alighed to session timeout it's not an issue.
http://professionalaspnet.com/archive/2006/12/09/Move-the-ViewState-to-Session-and-eliminate-page-bloat.aspx
As a fallback you could implement a Page base that puts the Session ID into the ViewState, checks it on postback and if it's different than does some action to recover.
The only other option you have would be to create your own PageAdapter that uses the DB or some other data store.
How about trying Flesk ViewState Optimizer?
Has several options including storing in session, in database, etc.

What is the difference between ViewState,Application and Session of a Page?

Please anyone explain me the difference between ViewState,Application and Session of a Page ?
Quick one liners - if you want more detail, just ask
ViewState is the variable that holds the current state of the page, which is held in a hidden field in the page (used frequently)
ApplicationState is a variable you can store values in during the life off the application (may get cycled periodically, and without your knowledge) (used less-frequently)
Session is the variable you can write to that will persist from the moment they hit your site until they close the browser. (barring any timeouts). (used frequently)
A great article :
How to Choose From Viewstate, Session, Application, Cache, and Cookies
Some good discussion about the difference between Session and Viewstate : Session Vs ViewState
Session state is saved on the server.
Session state is usually cleared after a period of inactivity from the user.
Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
Can be persisted in a Database, useful for Web Farms / Web Gardens.
Is Cleared when the session dies - usually after 20min of inactivity.
ViewState is saved in the page.
The view state is posted on subsequent post back in a hidden field.
Is sent back and forth between the server and client, taking up bandwidth.
Has no expiration date.
Is useful in a Web Farm / Web Garden
SESSION Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.
VIEWSTATE Variables are stored in the browser (not as cookies) but in a hidden field in the browser. Also Viewstate can hold only string data or serializable objects.
When we use view state to design a web application it retains it's state consistently, in it's current position. If we use session then it does not retain it's state, so when we refresh the browser it starts from the initial page.

Resources