I wanted to use some data from one page to another. General solution is to use Session (most of recommends). My boss don't like sessions and he suggested me to do same work by using C# Property in common class as below
public static long parentId { get; set; }
and set it one one page as
Common.parentId = "any value";
and use it on other page like
string anyVariable = Common.parentId
and it worked. We get rid of session expiration as well. But why most of people recommend session. Is property another state management thing?
If you are going to store some data using simple static property you must understand that it will be shared among all your users. Sessions are not for this. But I don't see any reasons not to use sessions if you want to store user data somewhere.
In my project it is very convenient, especially when we use SQL-server to store sessions - we can update our website without any losing users' sessions data.
You can check all possible ways to hanle sessions for example here http://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.100).aspx
Related
First I want to say sorry for my bad english. It is not my primary language.
Anyway. I am currently working on a project were you have your own profile and stuff. I am already done with my login form and it is working fine, and when I log in it sets my user id from the database as a session named UserID to indicate that I am logged in.
Now, what I wanna ask is, what is the best way to get all my user information from my database in to global strings. So if I for example wanna write the firstname of the logged in user, I can simply do something like this:
Response.Write(UserFirstname);
Any suggestions? Or is there any smarter way to do this?
Thanks in advance, Jens Kvist
Your best bet is to use encapsulation and a custom object. Read your database into a custom object and then use the individual properties of that object in your example.
Encapsulation Tutorial
There are a lot of ways to do this. Using encapsulation correctly will make sure that, whatever route you take, you do it in a way that won't make you regret it later.
Also, it looks like you're using ASP.Net Web Forms (judging by 'Response.Write'). That's completely valid but you may want to looking into ASP.Net MVC (here). Razor can make your life much easier. Make sure it is applicable to your situation, of course.
public class CustomObject
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
}
CustomObject newObject = new CustomObject();
newObject.PropertyOne = DatabaseString;
newObject.PropertyTwo = DatabaseString;
Then Later:
Response.Write(newObject.PropertyOne);
Create a class that retrieves/saves the data from session variables. Or use the identity classes in .net
I am building a web application. The authentication will be managed by the website, that is not my concern. What i need to store is the UserID in some place.
Once they open the application I will be able to get their UserID. I was previously using a Session variable to store this. Can I create a class say:
static string _UserID;
public static string UserDetails
{
get
{
return _UserID;
}
set
{
_globalValue = \\value from webpage;
}
}
and use UserDetails._UserID instead of assigning it to a session variable?!
The website's session server is not very reliable so I thought I could use this way.
Will this work?
I learnt from the answers that the variables will be overwritten for each user which is not what I want!!
Will it be the same scenario if i create an instance of this class in handler and assign the UserID to it??
are there any other way where I can make its scope limited only to one user i.e UserID with which I login should be same and if new user login to the application it must not be overwritten?? what is the disadvantage of using this method??
Is this method good if I use only one page and assign the object in the launch of the applciation ??
Static variables persist for the life of the app domain. So the two things that will cause your static variables to 'reset' is an app domain restart or the use of a new class.
The main problem is that static variables are shared across ALL USERS, and that is dangerous in your case that you pretend to store an UserID inside it. If you want to store
per user sessoin ID you should use Session
You can find more info here:
Lifetime of ASP.NET Static Variable
static filed will be shared between all users that means you would overwrite it for everyone. If you do not want to store it in Session you may store it in cookie (encrypted if security is important).
My goal here is to properly assign a session and retrieve the value stored in that session.
When users come to my first page, a Default.aspx page, I set the session in the code behind.
HttpContext.Current.Session["permissions"] = "Super";
However, I am unable to access this section in a Data Access Class in another file. Am I doing something wrong, or does anyone know a correct way of accessing an already set session from a C# class?
I try to access the session using the same syntax:
String permission = HttpContext.Current.Session["permissions"].ToString();
I am pretty sure , that you can always override this situation. What you are trying to do is not considered a good design principal.
what you can do is to pass the CurrentUser and/or his/her role to the data class by populating a custom property on that class. Within that class you can use the value of this property to work on the user's role.
let me know , if this helps you.
For code samples , you can always look at this SO question
How to access session variables from any class in ASP.NET?
I have looked at this question first: retain value after page refresh. But it seems like it doesn't work with collections because the ViewState only store one value. I need to use the collection because I do not know how many instances of object the user will create. Therefore, the ViewState is not an option. I also tried using static variables but it stores the values for longer than I need it (I found the explanation for this here: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/3664cd62-46c7-4098-88a7-c09647673096).
I would massively appreciate your help.
Often using Session state is better for lare objects, but you can store any serializable objects in the ViewState too ( http://msdn.microsoft.com/en-us/library/ms972976.aspx ).
Note: please avoid using storing data in static properties in ASP.Net as the values are shared across all requests. Note on note - HttpContext.Current is not really static objects (per-request object).
You could store the List<> instance in the client session on the server side. Then on each request you will have access to the list in the session.
However, you should still be able to use viewstate, as long as the items in your List<> are serializable.
You should consider the amount of data being exchanged between the browser and web server when using viewstate. If your items are not unreasonably large and you will not have too many of them in the list then viewstate might not be unreasonable.
The code might look something like this.
private ArrayList GlobalList
{
get
{
return ViewState["GlobalList"];
}
set
{
ViewState["GlobalList"] = value;
}
}
you can use class level variable which hold the value after post if you want to use List make it class level variable then it wont loose the value.
I'm workng on a new, green-field ASP.Net application. We're implementing a base page which all pages will be, er, based on. The application will be running under Integrate Windows Auth, so I'll have the user's account details. With these, I'll be going to several databases (in which the user will exist) to find out what roles they are assigned to in each db. I'll be holding the role yay/nay in a bool array, and key into it via an enum.
There will be a session object that will hold a few things, and the roles assigned for that user. I'm thinking of making the session object available as a property of the base page, as the code would be something like this:
public SessionObject MasterSessionObject
{
get
{
if (Session["SessionObject"] == null)
{
// Create session object, assign user name, etc.
// Do something with roles...
Session["SessionObject"] = sessionObject;
}
return (SessionObject)Session["SessionObject"]
}
}
In order to control what happens on the (sub-classed) page, I want to provide a CheckSecurity method - e.g. if the user is not authorised to a certain part of a page, it can be hidden / disabled, or they could be booted back to a "not yours" page. The logical place for it is the base page, but seeing as the base page is already exposing the SessionObject that holds the roles permissions, would it not make more sense to Create a DatabaseSecurity type object and have the check on that?
Dealing with the latter approach, I've used abstract base classes to get me so far: I have a DatabaseRoles abstract class which contains the bool array, and a method to retrieve the roles for the user. The concrete implementation holds an Enum (as previously mentioned) to key into the array (in the base class). The abstract class also has the CheckRole method which takes in an int, to which I'm intending use a cast of the enum...
The SessionObject contains several of these DatabaseRoles implementations, and essentially does away with the need for a CheckSecurity in the base page class, leading to code like this in the actual page:
if (MasterSessionObject.SampleDatabaseRoles.Check((int)SampleDatabaseRolesEnum.RoleView))
{
// Do something
}
But, I'm sure you'll agree, it looks sucky...
If there was a CheckSecurity method on the base page, it would have to take a concrete DatabaseRoles object, but also an enum of which role to check, which would also look sucky. And finally, there would be a requirement at a later date to add more databases and their security settings...
I'll add code tomorrow if required... :-s
I dunno, I'm not that thick, but I do have a hard time sometimes binding all this together...
Thank you,
Mike K.
IF you happen to use ASP.Net / ASP.Net MVC, I would say the best place to do this would be via a custom HTTP Module by handling the AuthenticateRequest method & continuing with the request only if the request has been authenticated. There are tons of excellent articles online for this code.
Also - have a look at the Roles & Memberships of ASP.Net - it is pretty good & generally satisfies most requirements or you are always free to extend it. Again - tons of articles on custom membership providers...
unless I am missing something - HTH.