How to save username in global variable asp - c#

I have online exam system I want to save username in global variable or any other thing that just can save it.
I want this username for get and set data on SQL database.
I'm using a global variable in class but it replace in every login.
any way to save username foreach user?
public class GVar
{
public static string user
{
get; set;
}
public static string mail
{
get;
set;
}
public static string melli
{
get;
set;
}
public static bool go
{
get;
set;
}
public static System.Threading.Thread thread { get; set; }
}

Use Application or Session as the case may be.
Session variables are global but limited to current session (call it user for understanding).
Application variables are globally shared across all sessions.
So, following statements may be used to get/set variables at application level
Application["user"] = "abc"; //sets the value at application level
var user = Application["user"]; //gets the value stored at application level
Similarly, to make it global, but isolate at session level,
Session["user"] = "abc"; //sets the value at session level
var user = Session["user"]; //gets the value stored at session level
EDIT
For ease of use, I prefer implementing them as properties, somewhat like this:
Define the class with custom getter/setter properties, and add it to App_Code folder
public static class GVar
{
public static string user
{
get { return Session["GVar_User"]; }
set { Session["GVar_User"] = value; }
}
//...
}
Use it in your application, as you would normally do with any other property.
GVar.user = "abc"; //set value
var usr = GVar.user; //get value

You can save it on login like this:
Session["user"] = "gamesdl";
And then you can get the value during executing like this:
String username = (string)(Session["user"]);

You can use claims.
The claims are in identity. And you can config then in login action.

Related

User data getting swapped even without using sessions - asp.net mvc

When multiple users are logged into the website, the last logged in users details are visible to all previously logged in users. This is causing serious vulnerability issue.
I'm not using any session variables in storing user data instead, Once the user logged into my website, i'm keeping his acc details in helper class file like below.
And in my all other pages, am using getting userdetails like UserData.userid, UserData.username etc...
public class UserData
{
public static int userid;
public static string username;
public static string useremail;
public int user_id
{
get { return userid; }
set { userid = value; }
}
public string user_name
{
get { return username; }
set { username = value; }
}
public string user_email
{
get { return useremail; }
set { useremail = value; }
}
}
You are declaring the fields of this class as static. This means that every instance of the class UserData will have the same values in these fields.
See here documentation about the static keyword and when you set these values you set the same values for every instance still around in your program.
You need to remove the static keyword, but given the fact that you don't really have any use for these fields you could remove them and simply change your class to use auto implemented properties instead
public class UserData
{
public int user_id {get;set;}
public string user_name {get;set;}
public string user_email {get;set;}
}

Authorization in ASP.NET MVC 4

I have a menu in web site. I want to access this for every role .
For example : i have 3 role that Role1 have access to personnel, referred, visit menu, and role2 have access to personnel, diet menu , and role3 have full access.
I created a static class that set value when user login in site. and use this class property for show/hide menu. but change this value when a nother user is login in site.
public static class GlobalVariables
{
public static string UserName { get; set; }
public static string Image { get; set; }
public static bool IsAuthorizePersonnel { get; set; }
public static bool IsAuthorizeReferred { get; set; }
public static bool IsAuthorizeDiet { get; set; }
public static bool IsAuthorizeVisit { get; set; }
}
How do i set access for menu ?
The static class is changing when new users login because ASP.NET handles multiple requests/clients in the same App domain, which means they share static classes/properties.
In order to make something like this work you would need to cache the information either via session state or a user keyed memory cache (such as Redis).
Alternatively, Asp.Net simple membership does have role support, so you could also consider creating the IsX properties as wrappers around role checks.
See the following articles for some examples:
http://www.asp.net/web-pages/overview/security/16-adding-security-and-membership
http://msdn.microsoft.com/en-us/library/5k850zwb%28v=vs.140%29.aspx
Hide link based on Role
Basically you have a single instance of the class which is used for all users in the site. Due to it being a static class.
You should create an instance-per-user class. Which you could place inside the cache under fi username.

C# Class for UserData accross the whole Forms

i am trying to implement a windows desktop applicaiton c# VS 2010. To Application has a login form to ask the user to type his username and password. and the applicaiton checks them in the DB and returns the userdata (id, permissions, email, telephone) which are saved in DB.
Programmatically, when the login data is valid and correct, i create an instant from a class classed "clsUser" which provides the fields for the users.
and then fill the class with the data as normal and then open the main form and child forms after that.
My question is , how to access the class of user over the whole applicaiton (for example to check if he has the permission to access the Form or not). I tried different approaches like Calling string permission = FormLogin.clsUser.permission(); but its not fine .
thanks for your help or any suggestions !!
int id;
string fname;
string lname;
string uUsername;
public clsUser()
{ }
public int UserID
{
get { return id; }
set { id = value; }
}
public string FirstName
{
get { return fname; }
set { fname = value; }
}
public string LastName
{
get { return lname; }
set { lname = value; }
}
public string Username
{
get { return uUsername; }
set { uUsername = value; }
}
public override string ToString()
{
return base.ToString();
}
You can access to this object over the whole application by making it static:
public static class clsUser() { }
Now you can access its properties with:
string userPermission = clsUser.Permission;
You can set a property by:
clsUser.Permission = "Administrator";
You dont have to create a new Instance of a static class. You can access to it over the whole application by calling it with its class name (in your case clsUser) and the property name you want to access like above written.
Hope this is useful ;)
you can create a Global class using the singleton pattern. Inside that you can hold your actual User as a Property and access it via
var user = Global.Current.User;
var permission = Global.Current.User.Permission;
I found a topic for the singleton pattern here
Thread Safe C# Singleton Pattern

Getting IdConvention in RavenDB

Lets say we have a User class
public class User
{
public User() {
Created = DateTime.Now;
Tags = new List<string>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Created {get;set;}
public IEnumerable<string> Tags {get; private set;}
}
And one might want a user to have an id like [FirstName]/[LastName] so we register an IdConvention like this:
_documentStore
.Conventions
.RegisterIdConvention<User>(
(dbname, commands, user) => user.FirstName +"/" + user.LastName ));
Now lets say you created a new user with a new set of tags attached. You want to store it in RavenDB if the User does not exist. However, if the User does exist you don't want to overwrite the existing Object as you want to keep the initial Created date. Therefore you only update the Tags enumeration with the values of the newly created User.
You might do something like this:
public void AddOrUpdateUser(User newUser) {
using (var session = _documentStore.OpenSession())
{
var existingUser = session.Load<User>("myFirstname/myLastname")
if(user != null) {
existingUser.Tags = user.Tags;
}
else {
session.Store(newUser);
}
session.SaveChanges();
}
}
However, if for some reason I changed my IdConvention, I have had to update the code above as well. Is there a way to reference the IdConvention registered in order to calculate the id for the newUser Object. With this id value you could check wether an item exists or not rather than creating the Id by yourself.
After registering an id convention, the GenerateDocumentKey method will use that convention instead of the default hilo generation scheme.
It needs some parameters, which are easiest to get at if you first cast the IDocumentSession to a real DocumentSession.
var s = ((DocumentSession) session);
var key = s.Conventions.GenerateDocumentKey(s.DatabaseName,
s.DatabaseCommands,
yourEntity);

Creating and storing a session

I'm working on creating a session for a user login on my website. I can initialize the session and use its members just fine, but I also need a method within my session class that will store itself. I need to provide HttpSessionState as an input parameter, and then store it into an object like: Session["sessionName"]=this;.
Furthermore, when I want to retrieve the session, it won't yet be created, so it must be static. Then I need to return a new instance of my session class with the properties filled (username and companyID) out of the HttpSessionState.
How can this be done in my session class? What I've described above is from the research I've done that provides a particular solution to my problem, but since I'm new to using session, I don't quite understand it.
Thanks.
Snippet of my session class:
public class MySession : System.Web.UI.Page
{
private MySession()
{
Username = Business.User.labelUsername;
CompanyId = Business.User.labelCompanyId;
}
public static MySession Current
{
get
{
try
{
MySession session = (MySession)HttpContext.Current.Session["sessionName"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["sessionName"]=session;
}
return session;
}
catch (NullReferenceException e)
{
Debug.WriteLine("NullReferenceException:");
Debug.WriteLine(e);
}
return null;
}
}
public string Username
{
get; set;
}
public string CompanyId
{
get; set;
}
}
You could try using a serialized "session info" object:
[Serializable]
public class SessionInfo
{
// Stuff to store in session
public string Name { get; set; }
public int Foo { get; set; }
private SessionInfo()
{
// Constructor, set any defaults here
Name = ""
Foo = 10;
}
public static SessionInfo Current
{
get
{
// Try get session info from session
var info = HttpContext.Current.Session["SessionInfo"] as SessionInfo;
// Not found in session, so create and store new session info
if (info == null)
{
info = new SessionInfo();
HttpContext.Current.Session["SessionInfo"] = info;
}
return info;
}
}
}
You can then use this from within your application like this:
SessionInfo.Current.Name = "Something Here";
SessionInfo.Current.Foo = 100;
The serialization/deserialization is all done within the SessionInfo object, and you get the benefit of type safe data.
What you are asking about is called serialization and deserialization.
Serialization is taking an object and converting it to a format, such as a string, that can be stored. Deserialization is the reverse of that action.
The "quick" way is to add the [Serializable] attribute to your class. However, without knowing the details of that class it's hard to say whether it is in fact easily serializable without a bit of work.
Here's a walkthrough: http://msdn.microsoft.com/en-us/library/vstudio/et91as27.aspx

Categories