C # how to create an attribute for roles?

1

I'm working on an application (windows forms) this works with a sql server database connection and has a table of users who have roles.

The application has modules or functionalities that are accessible according to the user's role:

[inventario; factura; ventas; reporte; administración]

the way to restrict access to the modules could be:

  • through a validation with a conditional and verify that the user who has logged in is x then put the property of x the controls enable = false.
  • equal to 1 but hiding controls with visible property = false

  • equal to 1 but performing the validation in each event of the control.

  • Example:

    Method 1 and 2:

     private void MenuForm_OnLoad(object sender, EventArgs e)
     {
       //realizar la consulta a la base de datos y comprobar el rol
       if(rol == "bodega")
       {
         Ventas.enable = false;//Ventas.visible = false;
         Factura.enable = false;//Factura.visible = false;
       }
      }
    

    Method 3:

    private void IngresoVentasButton_Click(object sender, EventArgs e)
    {
      if(rol=="vendedor")
      {
       VentasForm ventas = new 
       VentasForm();
       ventas.Show();
      }
      else
      {
       MessageBox.Show("ud no tiene acceso a este modulo!");
      }
    }
    

    For these cases I would like to be able to implement attributes in classes, methods or variables that would allow restricting the execution of the method (task) or setting the enable properties to false.

      [AutorizacionAttribute(rol="admin")]
    
        
    asked by Deiby Olaya Orejuela 08.05.2018 в 13:12
    source

    1 answer

    1

    You can use the interceptor method with PostSharp, for example, in the call to this method of using an Interceptor, in my example of use to make Caché. In the repository link has the complete code.

    [Serializable]
    public class CacheableResultAttribute : MethodInterceptionAspect
    {
        private double _cacheRetainSeconds;
    
        public CacheableResultAttribute(params double[] cacheRetainSeconds)
        {
            _cacheRetainSeconds = cacheRetainSeconds[0];
        }
    
        public sealed override void OnInvoke(MethodInterceptionArgs args)
        {
            var cache = MethodResultCache.GetCache(args.Method);
            var arguments = args.Arguments.Union(new[] { WindowsIdentity.GetCurrent().Name }).ToList();
            var result = cache.GetCachedResult(arguments);
            if (result != null)
            {
                args.ReturnValue = result;
                return;
            }
    
            base.OnInvoke(args);
    
            cache.CacheCallResult(args.ReturnValue, arguments, _cacheRetainSeconds);
        }
    }
    
    [CacheableResult(600)] 
    public List<dynamic> ReturnCustomer()
    {
        // return something
    }
    
        
    answered by 08.05.2018 / 20:15
    source