I have a webforms application with functions that frequently require a particular value, in this case the logged in user:
// Get user
string strUser = (HttpContext.Current.User.Identity.Name);
What it the best way to populate this string only once and call it from everywhere in my application?
you can have a Session variable to hold it
Session["UserName"] = "myusername";
If its a session dependent variable like a logged in user name use Session state
else use Application state, Application state applies to all users and sessions
you can use Application variable.
Application["username"] = "xyz";
I think you can declare this variable at Global.asax file.
There isn't a way to store a global value in web applications, they are state-less.
You can make use of a Session variable.
Session["Login"] = HttpContext.Current.User.Identity.Name;
The other thing you can do is create a static class with a static variable and assign the value on say Page Load.
Related
I am working on a MVC application where i have to store a unique id for the user who visits for a certain amount of time, so i am using Session in my MVC application but whenevr i try to set a value in my Session, i get a null exception. dont know the reason why, i tried
HttpContext.Session["demo"] = "name";
Session["demo1"] = "username";
I tried both the above method but i am not able to set the Session in MVC application.
I was calling this method on the constructor, thats the reason i was not able to get the Session, once i moved the code to the Action, everything was working fine.
thank you all
I am using web browser control inside my application window application. is their any possibility to set or change session values through my application? is it possible to create or destroy session from windows application?
in web application i can create session using :
session("user")="loginUSer"
is their any similar process available in vb.net application?
There is no concept of Session in windows forms. You can create a static class. And then assigned a value to its variable when you want to log in.
Public static class login
{
public static string userId {get; set;}
}
login.userId = txtuserID.Text;
and set to null or empty string during log out.
U can set and remove the session variables in C#.net like
Session["UserID"] = UserID;
Session.Remove("UserID"); or Session["UserID"] = null;
And in VB.Net
Session("UserID") = UserID
Session.Remove("UserID") or Session("UserID") = Nothing
There's no need for "Session state" in a Windows application - you can store as much state in memory as you need. You can't directly set or remove session state values of a web application from your Windows app, but if you have access to the code for both, you could be crafty and have a 'hidden' page that you pass values to in the querystring to set or remove session state, i.e. 'http://mysite/sessionpage?variable=value'. Does this make sense ?
I have a web application which calls a DLL, this dll gets some of the data from a webservice. What I would like to do is when a user logs into the web app, i'm currently storeing it's username in a session variable. In my webService i have a WebMethod like this:
[WebMethod(EnableSession = true)]
public string getLoggedInUsername()
{
SessionManager session = new SessionManager();
return session.Username;
}
This works fine, however when i access the webservice from the DLL, the value returned is always NULL, this is because when the console app connects to the webservice a new session will be initialized. Is there any alternative how can i store the logged in username and pass it to the dll through my webservice? Using Application Get/Set is not a good decision since my webapp needs to handle different users. Anyone could point me in the right direction?
The SessionManager class contains the following:
public string Username
{
get
{
return (string)HttpContext.Current.Session["Username"];
}
set
{
HttpContext.Current.Session["Username"] = value;
}
}
after the user logs into my application (i'm using asp.net membership) : i assign the username to the session variable in this way:
SessionManager session = new SessionManager();
session.Username = User.Identity.Name;
Thanks.
Check this article: http://www.codeproject.com/Articles/35119/Using-Session-State-in-a-Web-Service
You may have to re-initialize the proxy and the cookie container
I'm using VS2010,C# to develop an automation site (ASP.NET web app) which may have up to hundreds of users at once. I'm almost finished creating the site, but I KNOW I HAVE MADE some mistakes and one of them is using public static variables at codebehind pages instead of using sessions for each user, now when user A changes a setting in a page, USER B also views the page exactly the same way that user A views it!, rather than viewing the page in default state. I have a question:
where should I declare my sessions for each user? when users login, I create a session for each one, and this is the only session that I've used so far:
Session.Add("userid" + myReader["ID"].ToString(), "true");
should I create other necessary sessions right here? i.e. at login time? for instance I have declared some public static variables at a page responsible for viewing DB:
public static string provinceid = "0";//0 means all
public static string branchid = "0";
public static string levelid = "0";
public static string groupid = "0";
public static string phrase = "";
should I declare one session for each of them at login time? or can I declare them at startup of each page?
thanks
The Session object is unique per user already - you do not need to "create" it.
Using static variables would cause these items to be shared across all threads (so all users). These should probably be converted to session variables.
Instead of your statics, you would just do something like this:
Session["provinceid"] = "0";
Session["branchid"] = "0";
Session["levelid"] = "0";
Session["groupid"] = "0";
Session["phrase"] = "";
As Oded mentioned in his answer, the Session is already unique to the user, so no need for using the "Add" method.
Whenever you are done with this information (user logs out, etc), you can use the Session.Clear() method, which removes all the keys and values from the Session object.
I KNOW I HAVE MADE some mistakes and one of them is using public
static variables at codebehind pages
You are right about that. That's a pretty bad thing to do on a web app.
You don't need to create a user Session since it's already created automatically when the user hits your website the first time. What you need in order to use Session the way you intend to is something like this:
//Store value
Session["Key"]=myValue;
//retrieve field
var myValue = Session["Key"];
You can do this on any page you want since Session is a global object; it doesn't need to be done on the login page, but whenever you need to store anything that's specific to the user.
I am currently using session to hold the user ID at my web application. And i read a lot about sessions is evil, so my plans is to find another solution.
So my next step is to use encrypted cookie.
Something like:
userInformation: ENCRYPT(UserID,subdomain,someComputerUniqueValue,hashvalueOftheString)
each user has their own subdomain, so the UserID and Subdomain must match.
But. Now at almost every page i call the session value to get the userID.
I want to change this to some kind of variable, but what kind of variable?!
I am now setting the session value inside a httpmodule. in the
public void Application_PreBeginRequest
Is it possible to create a variable within application_prebeginRequest and read it somewhere else during the creation of the page. for example in the masterpage, och the contentpage. or the classes that is used at that specific page.
WHen the page is created and sent to the client, the variable should die.
What kind of variable am i looking for? is it global variable? if not, what is global variable?
Thanks for reading!
Mattias R.
Edit:
This cookie is not for authentication. I want to save the ID of the user connected to the subdomain, so i dont have to run the "SELECT ID from account where subdomain='somethin'" query each time a page is visited.
You can store what you need inside the HttpContext.Current.Items. Items put inside that will live only during the current web request and will be available globally in your web application.
// Global.asax
void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Items["hello"] = DateTime.Now;
}
// Default.aspx
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = HttpContext.Current.Items["hello"].ToString();
}
}
By the way, at Application_BeginRequest event, the Session object isn't available.
For more information about HttpContext.Current.Items, look at https://web.archive.org/web/20201202215202/https://www.4guysfromrolla.com/articles/060904-1.aspx.
Once the user is authenticated, why don't you log them in with FormsAuthentication.SetAuthCookie?
You can then retrieve the currently logged in user using HttpContext.Current.User.Identity.Name.
Session is not "evil" Session is stored on the server, and for small amounts of data such as what you suggest, it scales very well.