Can I modify ASP.NET session object this way? - asp.net

Imagine that I have an instance (oEmp) of "Employee" class and I would like to store it session.
Session["CurrentEmp"] = oEmp;
If I modify a property in oEmp as follows:
oEmp.Ename = "Scott";
Am I referring to session item through above statement or just only "oEmp"?
Session["CurrentEmp"] = oEmp; //Do we still need this after any property is modified
Is that the same case, if I opted for SQL Server session state (instead of InProc).
thanks

Asp.net Session will hold the reference, so you shouldn't need to do the following:
Session["CurrentEmp"] = oEmp;
after modifying oEmp;

Session Variables are held as reference types so there is no need to update its value every time.
You object instance that you store, only the reference to that object is stored in the session variable.
Here are some link to help you find more details
http://bytes.com/topic/asp-net/answers/447055-reference-types-session
http://forums.asp.net/t/350036.aspx/1
Do asp.net application variables pass by reference or value?

I am updating my response as my understanding of session data serialisation was not correct. I am not going to delete this answer as it might help other understand how session works. I would thank #Guru for point this out.
Irrespective of session mode, session data is updated back to session object only when the request is successful. So if you have assigned a reference object to session and then update the object in the same request, the session will hold the updated information.
Refer: Underpinnings of the Session State Implementation in ASP.NET for more information

Related

Why Do we use Session() state instead of global variables in ASP.NET? what is the point?

Why Do we use Session() state object in ASP.NET to store and retrieve data throughout the session of any user? Why not use global variables instead of session()....And similarly View() state to store and access data anywhere inside a page...Why this functionality exists while we can simply store the data in a Variable and access it wherever needed? Please Clarify
One of the answers I came across is that during the occurrence of Page PostBack there may be a chance that the variables might become empty and so the data in the variables will be lost. Hence why we use states for accessing data.
You can use value of session anywhere in your application and global variables can be use on a single page. Whenever page will be refreshed value of global variables becomes empty but session value will be remain as it is.
The 3 concepts Session, View State and Global objects does the same job of saving and accessing the values.
The main difference comes in stating the scope of this value assigned to the variable. Below definition will explain you the same.
1> Global variable: The scope of global variable (declared either through a singleton pattern or application state) has a application scope. i.e; the value assigned to this variable will be accessible in all the sessions and will be same at a point of time of all sessions and in all pages. These value are stored in the .NET Framework common language runtime and is same across application.
For eg: A connection string, database name etc.
2> Sessions State: The value assigned to a session state object will have a scope only for that session (until you perform a session.abondon).
For eg: when you login to a website the website might store your login Id in a session variable. This session variable will be accessible in all the pages until you log out.
3> View state: The scope of view state is the page and subsequent postbacks. Once you navigate to a different page the values are gone. This is mainly used to store a calculated values that can used after the post back. Also, ASP.net internally uses viewstate to populate the control values after postback.
View state is a page level state management.

ASP.NET session alternative to pass object between pages

I want to pass an object between pages of my website. I know I can use session object for this.
Personally, I don't want to use any session or application or caching for this.
Is there any other alternative?
Please help.
Thanks,
Mahesh
Another alternative would be to serialize the object into a hidden field and when you post to the other page deserialize the value back to an object instance. Or yet another possibility would be to persist the object to some data store and then use an id to fetch it back.

How to save value across postbacks for a composite control without using viewstate

I have a composite control that has a couple of private fields that reference values in the cache and these private fields are called during the constructor method. Since a string key is used to identify the value in the cache, I must have a way of storing that string key in such a way that it is available at the time the control is instantiated, and I have to be able to reference it on postbacks without it changing.
In addition, this key is generated the first time the control is loaded, but it should not be changed again after that first time.
How can I accomplish this?
I have already tried saving it to viewstate, but that doesn't work because viewstate is not yet available at the time the control is instantiated.
I have tried using a private field and then checking against Page.IsPostback in the constructor and if it isn't postback, I assign a value to the private field, but on subsequent postbacks it looses it's value, and I can't reassign it in the Page.IsPostBack again because it is an autogenerated GUID.
This has got to be something folks have had to do before....
There isn't a lot of state info available during control construction at all, so this could be difficult. Is there some reason you can't move your code which accesses the Cache'ed info into the control's Init event?
I assume you can't use Session because the information stored is related to that specific request/postback. If it's not specific to that request, using Session could be a possibility - but I think you may encounter other problems trying to deal with control state so early in the lifetime.
After seeing your comment to the other answer; you should be able to move your code that checks for the cached datasource into the control's Init or even Load event, so the state will be available.
Also, incidentally; are you sure you really need to cache this data? That could end up taking up a lot of server memory.
Have you tried Session?
You can store anything you like in the session object for one particular user, maintaining the value / object between postbacks.
If you want to store on a global basis and not per ser basis, try Application
Although this isn't the best solution (rearranging your logic to fit the lifecycle model generally is), have you tried accessing the Request directly? I once really wanted to get the selected value off a DropDownList very early in the lifecycle so I could adjust some elements in the building, and I did it like this:
myDropDownList.SelectedValue = Page.Request.Form[myDropDownList.UniqueID];
So instead of waiting for the viewstate to load the server-side proxie's values, I just got it myself from the client-side control value that was passed in on the post. I probably would do things differently if I redesigned that page, but it seems to have worked out alright for now and it solved the problem I was having.

Can I store a Scripting Dictionary in a session variable?

I have a classic ASP site where I create a dictionary when the user logs in and then stores that dictionary in a session variable like so...
dim objDict
set objDict = server.createobject("scripting.dictionary")
' processing here to fill dictionary
set session("user") = objDict
That all works fine and dandy but when I navigate to another page and try to access a value from the stored dictionary like this...
session("user").item("id")
I get the following error...
error '80020009'
Can anyone tell me if I'm accessing the stored dictionary incorrectly? Is storing the dictionary object in a session variable a bad/wrong thing to do?
Thanks
The error you are getting is a remote procedure call error. I can't explain why you get this error or why extracting into a local variable fixes it.
However I can tell that its really bad idea. When you store an object such as this in the Session object you create an affiliation between the current thread executing the script and the session. As result all subsequent requests for that session must now be handle only by this specific thread. If that thread happens to be busy handling someone elses request the sessions request is queued even if there are plenty of available work threads that could be used. Hence storing an object in the Session can significantly damage the scalability of the app.
I'd also question the wisdom of storing a Dictionary in something which is already a dictionary?
Why not just user :-
Dim userID : userID = Session("user_id")
Where anything you would normally have stored in the "user" dictionary, such as "id", would simply have the prefix "user_" and stored direcly in the Session?
Have you tried in your code doing something like the following when you want to access it?
Dim objDict
Set objDict = session("user")
Response.Write objDict("id")
Try that and see if it works. I wouldn't think this would be necessary but Classic ASP wasn't exactly the most robust language. What you want to do should be workable, since the Session object simply stores objects.

Data Class in ASP.Net

I am a VB.net winforms programmer attempting to build an ASP.Net app. I use data classes(objects) through reflection in most of my vb projects and was trying to adapt it to ASP.net using the VB code behind. I have a webpage that serves as an add/edit page for contact info. I instatiate my class which grabs the contact data from the data base then I have a process that loops through the controls on the form and matches up with a property in the data class. I can display data no problem. When I edit data and click the submit button my code calls a then loops through the controls on the form again and matches the control to the property of the data class to update the property of the class. However, my data class is no longer valid. I know web programming is different then winforms but I can't seem to get over the hump on this one. Is this the wrong way to go about this? Is my data class only available on the server side? Do I just reinstantiate the initial class and then loop through the propeties and change what the user changed and then call the update method (see redundant)? How can I get data class into a session object (I made an attempt in the past but was under tight deadlines and had to abandon it, maybe I need to revisit it?)?
Thanks
If you decide to keep some of your data in Session, you owe it to yourself to look at this post. Your code will be much cleaner and easier to maintain.
Yes, you need to reload the data class from the database as one option, or use an alternative approach. The reason is web is stateless, so all local variables are destroyed then the server side page unload process occurs. This means that in between requests, you need something to store your data.
You can read/write an object via the Session colleciton, as so:
Session["A"] = myobj;
myobj = (ObjType)Session["A"];
And so session stores an object for a specific user. Alternatively, cache stores application level data, so one instance of an object is available to all users (where session is unique to each user). You can make cache unique to a user by appending a user ID to the cache string.
var o = Cache.Get("A");
if (o != null) { .. }
Cache.Add("A", o, ...);
And so these mechanisms help you temporarily retain data.
You need to save your data class somewhere, usually in a session variable, otherwise it goes away as soon as the page gets sent back the user. Or else you need to recreate the data class again upon posting.

Resources