Reputation: 5266
I decided to write the below code for Access Control List permission check.
My database will return a record like EmployeeDetFeature
,Create
,Edit
I would like to Parse Create
and add it to a Feature ACL enum list.
Also i need to find it later.
public enum ACL
{
Create,
Delete,
Edit,
Update,
Execute
}
public class Feature
{
public int Id { get; set; }
public string Name { get; set; }
public List<ACL> ACLItems { get; set; }
}
public static class PermissionHelper
{
public static bool CheckPermission(Role role, string featureName, ACL acl)
{
Feature feature = role.Features.Find(f =>f.Name == featureName);
if (feature != null)
{
//Find the acl from enum and if exists return true
return true;
}
return false;
}
}
How do i make it with Enum collection preparation and find the same later for checking permission.
Upvotes: 2
Views: 232
Reputation: 4606
If you are working on .NET 4.0, you can decorate ACL enum with Flags attribute and change your model a bit:
// Added Flags attribute.
[Flags]
public enum ACL
{
None = 0,
Create = 1,
Delete = 2,
Edit = 4,
Update = 8,
Execute = 16
}
public class Feature
{
public int Id { get; set; }
public string Name { get; set; }
// ACLItems is not List anymore.
public ACL ACLItems { get; set; }
}
Now you can use Enum.TryParse, like in the following example:
static void Main(string[] args)
{
ACL aclItems = ACL.Create | ACL.Edit | ACL.Execute;
var aclItemsString = aclItems.ToString();
// aclItemsString value is "Create, Edit, Execute"
ACL aclItemsOut;
if (Enum.TryParse(aclItemsString, out aclItemsOut))
{
var areEqual = aclItems == aclItemsOut;
}
}
Upvotes: 1
Reputation: 35363
Find the acl from enum and if exists return true
Something like this?
bool b= Enum.GetValues(typeof(ACL)).Cast<ACL>().Any(e => e == acl);
Upvotes: 3