How can i assign and maintain values to session variables - c#

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 ?

Related

Is it possible in ASP.NET Core to bind an instance of a C# class to a session?

Is it possible in ASP.NET Core to bind an instance of a C# class to a session?
So that the class lifetime is also tied to the session lifetime ~20 minutes.
I want to store somewhere the values entered by the user in a web form so that the values are saved when the user hits browser refresh or leaves the page for a short time.
Like this:
HttpContext.Session.RegisterClass(MySessionDataClass);
...
HttpContext.Session.GetObjectValue(MySessionDataClass);
// Create new MySessionDataClass or return an
// instance of a class that has already been created for this session.

Alternative to Session Variable

I am trying to find an alternative to using a session variable. In my solution I have a project that is referenced by an ASP.NET web application and a console application. Both these applications can make changes to data and when a change is made the ID of the user making the change is logged against that row.
So if it was just the ASP.NET app making changes, it could do something like myObj.LastUpdatedByID = Session["userid"]. Given that the command line app needs to make changes and doesn't have a session, what alternative could I use that has the equivalent of session scope in ASP.NET but is also available in the console app scope?
I've had a look at MemoryCache, but that seems to be application level in ASP.NET.
I don't want to go down the line of passing the user ID through to each call.
Would doing something like checking for a HttpContext and if there is, pull from the session and if there isn't, pull from MemoryCahce? Or is there a better way of doing it?
EDIT:
The user ID is specifically set in the console app depending on what action is being carried. The console app is used for automated processes and there are numerous actions it undertakes. So for example, the sending email process would be carried out by user ID 1 and the delete old files process would be carried out by user ID 2. In some instances, the user ID would be set to the user ID that last made the change to that row of data.
EDIT:
Some example code (stripped for brevity). You can see I am using the MemoryCache here, which as I understand would be application wide and therefore not usable in ASP.NET app:
public class Base(
{
private int auditID = -1;
public int AuditID
{
get
{
if (this.auditID <= 0)
{
ObjectCache memCache = MemoryCache.Default;
this.auditID = ((int)memCache["CurrentUserID"]);
}
return this.auditID;
}
}
}
public class MyObject : Base
{
public int LastUpdatedByID { get; set; } = 0;
public bool Save()
{
bool b = false;
this.LastUpdatedByID = this.AuditID;
//Call to DB here...
return b;
}
}
If the data needs to be persistent across application then you can't use Session or HttpContext.Cache since those are dependent on current HttpContext which you don't have in console app.
Another way, would be to store the data in some persistent data store like Database or distributed cache like Redis Cache / Azure Mem Cache

Session Variable value from DLL

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

How do I create an ASP.NET webforms global value

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.

where should I create user sessions?

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.

Categories

Resources