I created a custom attribute class that will check the system security and throws an authentication exception if there is a security error.
public class EntityChecker: System.Attribute
{
public EntityChecker(int entityId)
{
// doing some logic to check if the entityId is allowed to be inserted
}
}
I want to use this custom attribute as a declaration to an entity addition function and I want to pass a variable from the function to the attribute constructor. can something like this be done?
[EntityChecker(entityId)]
public int AddNewEntity(entityId)
{
// logic of entity addition
}
Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.
To set the value of an attribute, pass value parameter along with name parameter. In the above example, $('p'). attr('style') gets style attribute of first <p> element in a html page. It does not return style attributes of all the <p> elements.
Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.
Can something like this be done ?!
No. Constructor parameters in attributes must be resolved at compile time. They are intended as metadata on the type or method itself, not something that would be used per call or per instance.
Given your description, an attribute is likely not an appropriate way to handle this. Since you want to run extra code that happens per call, you will need a different technique. For example, you could pass a delegate, ie:
public int CheckedAddEntity(int entityId, Func<int, int> funcToAdd)
{
// Perform your checking on entityId here
return funcToAdd();
}
This would let you then call via something like:
int result = CheckedAddEntity(entityId, AddNewEntity);
In this case, I recommend looking at Aspect-Oriented programming. It is a different way of doing code, but one that allows you to re-use the boilerplate logic (e.g. authentication) throughout. You might have to design your attribute a little bit differently, but all of the logic can be put into an "aspect" which then gets compiled automatically into the code when you build the project.
I personally use PostSharp, although I know there are others out there. They have a free license available for development; as long as you don't require advanced functionality, it's very cost-effective.
http://www.postsharp.net/blog/post/5-Ways-That-Postsharp-Can-SOLIDify-Your-Code-Authorization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With