Introduction
Most of the applications will have different types of users. Based on user type, they can perform operations like Create
, Read
, Edit
, Delete
, etc. so when we develop an application, we have to write multiple lines of code to enable and disable the controls for each screen based on logged in user. It is a very time consuming activity in the development phase.
Using attached property, we can simplify this activity in a generic way. This approach will be fit to WPF and Silverlight applications and we have no need to write the logic for every screen.
Sample Requirement
Application will have the below user types:
- Super Admin
- Admin
- Master
- Standard
Screen wise access
Screen Name
|
Action
|
Access to User Type
|
Customer
|
Add New Customer
|
SuperAdmin, Admin, Master
|
Customer
|
View Customer Personal Detail
|
SuperAdmin, Admin, Master, Standard
|
Customer
|
Modify Customer Detail
|
SuperAdmin, Admin, Master
|
Customer
|
Delete Customer Detail
|
SuperAdmin, Admin
|
Supplier
|
Add New Supplier
|
SuperAdmin,Admin,Master
|
Supplier
|
View Supplier Personal Detail
|
SuperAdmin, Admin, Master, Standard
|
Supplier
|
Modify Suppler Detail
|
SuperAdmin, Admin, Master
|
Supplier
|
Delete Supplier Detail
|
SuperAdmin, Admin
|
Manage User
|
Add User
|
SuperAdmin
|
Manage User
|
Modify User Detail
|
SuperAdmin
|
Manage User
|
Delete User Detail
|
SuperAdmin
|
Implementation
When we design a screen, we can set the user type to the appropriate control that can perform the action.
Screen Shots
When the logged in user type is “Standard”
When the logged in user type is “Master”
When the logged in user type is “Admin”
When the logged in user type is “Admin”
When the logged in user type is “Super Admin”
Source Code
Main Window
public partial class MainWindow : Window
{
public MainWindow()
{
AppCommon.LogedUserType = UserType.SuperAdmin;
InitializeComponent();
userType.Text = "User Type : " + AppCommon.LogedUserType.ToString();
}
}
User Types
[Flags]
public enum UserType
{
All=0,
SuperAdmin=1,
Admin=2,
Master=4,
Standard=8
}
Attached Property
public class UserAcccess : FrameworkElement
{
public static UserType GetUserAccessType(DependencyObject obj)
{
return (UserType)obj.GetValue(UserAccessProperty);
}
public static void SetUserAccessType(DependencyObject obj, UserType value)
{
obj.SetValue(UserAccessProperty, value);
}
public static readonly DependencyProperty UserAccessProperty =
DependencyProperty.RegisterAttached("UserAccessType",
typeof(UserType), typeof(UserAcccess), new PropertyMetadata
(UserType.All, new PropertyChangedCallback(UserAcccessnChanged)));
private static void UserAcccessnChanged
(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement userAccess = (FrameworkElement)d;
if (((UserType)e.NewValue & AppCommon.LogedUserType) == AppCommon.LogedUserType)
userAccess.IsEnabled = true;
else
userAccess.IsEnabled = false;
}
}