As a part of learning process, I am writing simple IM app, using Remoting in .NET. As of now it is simple console app and it works as i expect. Thinking about next features/functionalities, I’ve stuck in a situation represented by the code below:
public static class UserManager {
public static started { get; private set; }
private static List<User> users;
static UserManager() {
users = List<User>();
started = true;
}
public static addUser(int _userID) {}
public static activateUser(int _userID) {
foreach (User u in users) {
if (u.userID == _userID) {
u.setActive();
break;
}
}
}
}
class User {
public int userID { get; private set; }
public bool active { get; private set; }
public User(int _userID) {
userID = _userID;
}
public void setActive() {
// only UserManager should be allowed to modify user state
}
}
I want to make only UserManager static class be allowed to modify states of it’s users list. I was thinking about “friend” clause but as I understand, there is no such construct in C#. Would it be enough just checking (inside User class methods), if calling “object” is of class UserManager?
I would appreciate any input/advice, including those saying “don’t do that as You try to do, better make it using..”
PS. Didn’t know which Title should i choose, feel free (more experienced programmers/so users) to change it if ther is more accurate.
You can put the
UserManagerandUserclasses in their own assembly and mark parts of the API asinternal(which is the equivalent of VB’sFriend). This enables you to restrict access from outside that assembly.Another way to restrict access is by doing role based security. .NET has the PrincipalPermissionAttribute for this:
Note that this will only work when you know the role of the user, but it is especially useful in scenario’s such as web sites (ASP.NET WebForms / MVC) and web services (WCF) were users normally log on.