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.
Related
• Create model, controller and the views given below.
• On the submit button click the data about employee should be stored in cookie.
• When the user clicks on “Retrieve” ActionLink, the cookie values should be read and displayed on EmpDtl.cshtml view.
The only reason for this question is that I do not know how to Retrieve and Store data in cookies can someone show me how to do it any generic code which retrieve and store data in cookies and if possible with explanation because some of the things have not cleared to me like what is expirationMinutes and how much time a session will be created.
Image of Scenario
Something like the following will store a cookie with an expiration time. Note that for writing / deleting cookies you need to use the HttpResponse object, and to read them you use the HttpRequest object. These are both accessible in your Controller class.
public void SetCookie(string key, string value, int expirationMinutes)
{
var options = new CookieOptions();
if (expirationMinutes > 0)
{
options.Expires = DateTime.Now.AddMinutes(expirationMinutes);
}
Response.Cookies.Append(key, value, options);
}
Then to read the cookie you need Request.Cookies[key] and to delete a cookie you need Response.Cookies.Delete(key).
If you are storing sensitive information then you should use options.Secure = true to force HTTPS-only transmission of cookie data.
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
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 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.
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.