how to store a list of objects in session - c#

i want to store a list of objects in session
List<ContentQueueLog> inactiveContent = GetInActiveContent(this.userID, this.visitorID);
when i store this list in sesssion it is stored but while trhying to get it
its null
i am storing sessions in sql
someone hinted me about serialization
but i cudnt get it
need some explaination

If you are using an out-of-process storage for the session such as SQL Server or state process you need to decorate the objects that you intend to store in session with the [Serializable] attribute because they need to be transmitted over the wire and saved as a binary representation. Later when you try to read them from the session ASP.NET will fetch this binary representation over the wire and deserialize them back to the original object.

Related

how to convert viewstate to session state?

I have created the view state. i want to use the view state in different pages.Is is possible to access the view state in different pages?
else can move the view state in session object in asp.net c#. how to do that?
i want to use the view state in different pages
Answer: Then There is no Need to Use ViewState.You Should Use Session as Per Your Question
What is ViewState
View State is one of the most important and useful client side state
management mechanism. It can store the page value at the time of post
back (Sending and Receiving information from Server) of your page.
ASP.NET pages provide the ViewState property as a built-in structure
for automatically storing values between multiple requests for the
same page.
What is Session
Session provides a facility to store information on server memory. It
can support any type of object to store along with our own custom
objects. For every client, session data is stored separately, which
means session data is stored on a per client basis
You can Easily Convert Session to ViewState
if(Session["Key"]!=null)
Viewstate["Key"] = Session["Key"];
or Vice Versa
if(Viewstate["Key"]!=null)
Session["Key"]=Viewstate["Key"]
Viewstate is equal to hidden field value. This is available to current page only where viewstate is defined and used. If you want to read those data in other pages it won't be available.
You need to store those values to session ,wherever you have done ViewState["key"]= "value". And you mean to access key in other pages. Viewstate is saved as encoded value in hidden field whereas session value is stored in server memory.
e.g. Session["key"] = "value".
Session is used for multiple pages
while viewstate can only be use to one page
How to convert session to viewstate.
Viewstate["ABC"] = Session["ABC"]
but for multiple pages you need session.

storing an object in session

I need to save a few things in the session. At the moment, I'm using InProc session on my development machine but I want to deploy using SQL server session and then Azure's AppFabric session.
I created an object that contains several properties, all primitive types. I'm handling the read of session like this:
SessionObject TheCurrentSession =
HttpContext.Current.Session["UserAppSession"] as SessionObject;
Basically, I'm wrapping session variables in an object that's serialized and deserialized each time the session loads and saves.
I'm wondering if it would be better to store each property in its native format and have the wrapping object read/save each of its properties in the session as a native type.
So for example, I'd have a method called RecreateSession like this:
public class SessionObject
{
public void RecreateSession()
{
this.SessionObjectProperty1 =
HttpContext.Current.Session["SessionObjectProperty1"];
this.SessionObjectProperty2 = ...;
this.SessionObjectProperty3 = ...;
}
}
I think doing so would prevent the serialization/deserialization process and could make the values accessible directly in other parts of the code (ie. an HTTP module).
Is it worth it to change my session implementation? What are the best practices for this?
Thanks for your suggestions.
Is it worth it to change my session implementation?
Only if it makes it easier for you to use.
What are the best practices for this?
You pretty much are already doing them. Creating a single object to hold several related properties (that are likely to be used together) and storing it in session instead of a bunch of separate session properties makes sense.
I always created a custom object in which each Property refers to a particular session item... I think its the best option.

How to define Variable similer to Session variable in ASP.NET

I want to define a variable or object like session, to stored data about each user, and i want to access this object in many pages,
could u please tell me if there is a way.
thanks
You have onlyy a few choices, really. URL parameters, hidden form inputs, cookies, session (be careful in a load-balanced scenario) or just store/retrieve stuff from a database. RaveDB is bloomin' brilliant for this because it's so fast and document-based.
You can store data in a cookie and then in your codebehind parse the specific cookie into something like a System.Collections.Generic.Dictionary
But you should use sessions.
Edit
IF if's a KeyValuePair<String,TValue> you can set Session[kvp.Key] = kvp.Value;, if not Session["KVP"] = kvp;
If u really don't want to use session use Database mind that this is a slow method...
i've had a few situations where I wanted to minimize/eliminate session storage (due to users being on a horrible wifi connection). to handle this situation I used an encrypted query string with only their ID in the string. in the base page I would decrypt the string and pull information I needed from the database. This information would be populated into objects that I defined and since the objects were in the base page I could access the information from any pages that inherited it.

Session instead of viewsate

I have found many questions here about storing values in viewstate, but haven't found a good answer.
I have a situation when i retrieve large amount of data from database. Then i filter and manipulate the data according to my needs (so it is a preety heavy process). Then I put the result inside a list of custom class. For example lets say this class will be Person
List<Person> persons = new List<Person>();
private void FillPersons()
{
//Call to webservice
persons = ws.GetPersonsList();
//Do all kind of custom filtering
//Manipulate the data
}
Now the whole FillPersons() method is a heavy process that returns pretty small amount of data. And unfortunately it can't be moved to SQL and the heaviness is in the process, but that is not the point.
The point is that i need to reuse this data on the page between post backs.
Right now in order to spare the additional call to FillPersons() I mark Person class as serializeable and store the list in the viewstate, that works fine except the fact that the page becomes 1mb size because of the viewstate. According to what i have read, it is not so acceptable approach i.e. it is not secure and it blows the source code making the page heavy etc. (second is what most concerns me)
So it leaves me with a session. However session is persisted not only between postbacks, but much after it, even when user leaves the page. Or worst- the session will end before user decide to postback. So finding the best time span for session lifetime is mission impossible.
My question is what is the best practice to reuse "datasets" between postbacks?
What you guys do in such cases?
Thanks.
PS: hidden fields etc. is not an option.
You can store this kind of data in the Cache. It is application wide, so depending on what you add use the key accordingly.
var key = UserID + "_personList";
Cache.Add(key, personList, null,
DateTime.Now.AddSeconds(60),
Cache.NoSlidingExpiration,
CacheItemPriority.High,
null);
Note that you can never assume that the data is in the cache (it might have been flushed) so always check if it returns null and than refill it.
Viewstate is not a good way of storing large objects. As you mentioned your page size will get bigger and every postback will take lots of time.
I would suggest using cache. By using cache your list wont be saved there till end of session and you can set how much time it should be stored there. For caching you may use HttpCache or some distibuted caching system like AppFabric or MemCached . This nuget package will help using these cache systems.
this link will help how to configure AppFabric.
I should edit with some code to make it more helpful.
https://bitbucket.org/glav/cacheadapter/wiki/Home
var cacheProvider = AppServices.Cache; // will pick cachadapter using web.config ( can be Http, Memory, AppFabric or MemCached)
var data1 = cacheProvider.Get<SomeData>("cache-key", DateTime.Now.AddSeconds(3), () =>
{
// This is the anonymous function which gets called if the data is not in the cache.
// This method is executed and whatever is returned, is added to the cache with the
// passed in expiry time.
Console.WriteLine("... => Adding data to the cache... 1st call");
var someData = new SomeData() { SomeText = "cache example1", SomeNumber = 1 };
return someData;
});
Other than a cache (good idea by Magnus), the only other way I can think of is to keep the results of your heavy operation stored in the database server.
You mention that it takes a lot of time to retrieve the data. Once done, store it in a purposely established table with some type of access key. Give that key to the browser and use it for pulling what pieces you need back out.
Of course, without knowing the full architecture it's really hard to give a solution. So, in order of preference:
Store it back in the database with a unique key for this user.
Store it in a remote cache
Store it in a local cache
Under no circumstance would I store it in the page (viewstate), cookie (sounds too big anyway), or in session.
Have you considered using ASP.NET caching?
You should choose a key that will suite your exact needs and you will have your data stored in the server memory. But keep in mind cache is application specific and is valid for all users.
If the data you process is not often changed, the processing algorithm doesn't depend on user specific settings and it is not critical to always have the latest data maybe this is the best option I can think of.
Store your filtered collection on disk in a file. Give the file the same name as a key you can store in viewstate. Use that key to retrieve the file on postbacks. In order to keep the file system from filling up, have two folders. Alternate the days for which folder you save the files to. That way you can wipe out the contents of the folder that is not being used that day. This method has extremely good performance, and can scale with a web farm if your folder locations are identified by a network path.
I think personlist is a shared object. Does everyone use the same list? You can store on Application.
Application["PersonList"] =persons;
persons = (List<"Person">)Application["PersonList"]
Or you can Store on Static class.
public static class PersonList { public static List<"Person"> Get {get;set;} }
You should write this code to Application_Start on Global.asax file
PersonList.Get = ws.GetPersonsList();
And you can get List by using this code
persons = PersonList.Get;

How do I cache a dataset to stop round trips to db?

I am creating a search results page in C# in an ASP.NET 1.1 page. In my data layer I have a DataSet that stores the result of a plain old ADO.NET stored procedure call. The DataSet has two DataTables and I'm using a DataVIew to filter and sort the columns.
I only want to fill the dataset once, and then work on the DataTables and derived DataView until the page is unloaded.
How best should I cache the DataSet in my DAL so that it is filled only PageLoad? Do i put it in a Cache object, a static member variable, a property...I don't have any fancy entity models or ORM, this is .NET 1.1. Thanks in advance.
Will your DAL be used by any other applications? If not then you can imbed the caching of the DataSet in the Cache or Session depending on what features are need of the storage.
Session will be specific to the user and get cleaned up when the user's session expires which means the data might be around a lot longer than required. More info on Session
Cache is nice because it will auto expire (use sliding expiry if the search data will not change often) and you can store the search criteria with it so that other users can leverage the search as well which will save you calls to the DB by multiple users possibly. Multiple user's being able to access this data is a big advantage over using Session. More info on Cache
If you plan to use your DAL in other apap, you might want the application to do the caching itself.
You just need a wrapper like:
// Consider this psuedo code for using Cache
public DataSet GetMySearchData(string search)
{
// if it is in my cache already (notice search criteria is the cache key)
string cacheKey = "Search " + search;
if (Cache[cacheKey] != null)
{
return (DataSet)(Cache[cacheKey]);
}
else
{
DataSet result = yourDAL.DoSearch(search);
Cache[cacheKey].Insert(result); // There are more params needed here...
return result;
}
}
there are ORMs that work with .net 1.1, but if you don't want to use them, I would recommend either populating something in the Cache so that you can expire it if needed and re-get the data. You could also put it into the session (if the data is user specific) or application (if it is not) objects.
If this is per user data don't cache a large amount of data putting it into session or similar, you are seriously hindering the ability of your site to scale. Consider how the amount of info in memory grows as you add more users, and then what happens when you need to use more than a single site server.
Instead modify the procedure so you can only retrieve the page of data that you need to show.
If this is data that is used for all users, definitely cache it. You can use the asp.net Cache for that.

Categories

Resources