Reputation: 5417
Can someone perhaps help me with a little problem I have on my database application.
When a user logs into my database with a User Name and Password, I want the User Name to be stored and accesible by the application as a whole (all forms etc), so that every action undertaken carries the users signature as it were.
I'm thinking the code is probably something like the following:
namespace YourNamespaceName
{
class Variables
{
public static string strUser = "user name";
}
}
Which I can recall then with Variables.strUser
However I don't want to hard code the value of user name into my application. Rather I need it to be evaluated at runtime based on the initial log in procedure, and retain the user name for reference for the duration of the application running.
Thanking you all in anticipation of your assistance.
Upvotes: 3
Views: 1599
Reputation: 6612
You can have a user class like below, this ensures that there is only a single instance of user in the application see Instance property and test stub for usage details, you can add more properties to the class if you wish.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace yournamespace
{
public class User
{
private static User u;
public string Username
{ get { return _username; } }
private string _username;
protected User(){}
public void SetUserInformation(string uname)
{
_username = uname;
}
public static User Instance
{
get{
if(u==null)
u=new User();
return u;
}
}
#if(TEST_USER)
public static void Main(string[] args)
{
User u = User.Instance;
u.SetUserInformation("testuser");
User u1 = User.Instance;
}
#endif
}
}
Upvotes: 1
Reputation: 7627
For user identity you shoud use IIdentity
interface. You can start with GenericIdentiry
.
See http://msdn.microsoft.com/en-us/library/y9dd5fx0.aspx for details.
Upvotes: 0
Reputation: 16368
namespace YourNamespaceName
{
public static class Variables
{
private static string strUser;
public static string User {
get { return strUser; }
set { strUser = value; }
}
}
}
You didn't specify framework version, but this code works with .NET 2.0. To use:
Variables.User = "User name";
Upvotes: 4
Reputation: 3986
You could creAte some kind of a 'user' class to store the user information, such as username, password, email, etc...
You can implement this class as a singleton and creAte it once the user logs in for the first time.
Then whenever you need user information you can use the 'user' singleton class.
Upvotes: 0
Reputation: 7413
If your application maintains a session state, then your best solution is to have the variable live in the session and access it from session scoped variables
Upvotes: 0