Validation that Custom Attibute is assigned to non static class member - c#

I need to create a custom attribute that is applicable only for non static class member.
How can I validate this constraint on project compilation or using code analysis tools?

There's no such constraint.

You could always write some post-build event that uses reflection to verify this... Granted, it may not be the most elegant of solutions....
To set this up, you would go into project properties, then the 'Build Events' tab. You would then enter the command line for the reflection based tool you'd write to implement this verification

It's probably not what you're looking for, but it's possible to make such an attribute with PostSharp, you will probably have something like this:
[Serializable]
public sealed class StaticAttribute : OnMethodBoundaryAspect
{
public override bool CompileTimeValidate(System.Reflection.MethodBase method)
{
return method.IsStatic;
}
The OnMethodBoundaryAspect basically wrapps your method inside a try/catch block, and the CompileTimeValidate method determines whether or not the attribute is invoked at runtime.

Related

How to create "filters" for class' methods?

With ASP.NET I have created a few filters extending both ExceptionFilterAttribute and ActionFilterAttribute. With ActionFilterAttribute I can execute actions before or after the method's execution. I'd like to mimic that behavior on my class. I have a base class called BaseService and whenever a method from this class is invoked I'd like to check if it contains an attribute and if it does execute that. For instance, on my derived classes I have methods like:
public void DoSomething()
{
LoggedUser.RequireAnyRole<RoleX, RoleY>("DoSomething");
// code here
}
public void DoSomething2()
{
LoggedUser.RequireRole<RoleX>("DoSomething2");
// code here
}
Instead of writing LoggedUser.RequireRole... I'd like it to be an attribute. That way I'd just add an attribute on top of DoSomething2: [RequireRole(Roles.X)].
Is this possible? If so, what is the best approach? I was reading something related to callmember, but I'm not sure that's the way to do it. I checked https://github.com/ASP-NET-MVC/aspnetwebstack for its implementation but I think I didn't know how to search for it since I didn't find anything...

Custom Attribute invocation

I am trying with the Debugger to stop when a method attribute is invoked, but I am never seems to get to the break point.
Am I missing something here?
[SecurityImpl("test")]
public void test()
{
}
[AttributeUsage(AttributeTargets.All)]
public class SecurityImplAttribute : Attribute
{
public SecurityImplAttribute(string test)
{
//Break Point Here
}
}
Attributes are only metadata. They aren't actually created as instances unless you use reflection (GetCustomAttributes). You cannot use attributes to add arbitrary code calls, unless you use an AOP framework such as PostSharp, or are using a framework that checks for specific categories of attributes and instantiates/invokes them explicitly (like ASP.NET MVC does).
Attributes are only decorators and they do not execute by .net framework.
Attrubutes are just metadata for your code. They are not executed automatically. If you want to use some metadata, you should get it manually and execute it. In your case constructor of attribute will be executed when you'll try to get method custom attributes:
object[] attributes = methodInfo.GetCustomAttributes(true);
If you want some aspects to be executed automatically, when you invoke method, then you can use some AOP framework, like PostSharp. Here is an example of aspect creation, which executes some actions on method call:
[Serializable]
public class SecurityImplAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
// this code will be executed on method call
}
}
When you apply this attribute to some method, PostSharp will read method's metatada during compilation, and if aspect will be found, PostSharp will inject your code right into binaries.

How do I unit test private controller methods in ASP.NET MVC?

What is the best practice to unit-test private methods inside a controller in ASP.NET MVC? The Currently, if I want to unit-test a private method inside a controller I have to set it to public but when I do, that method is exposed to the web.
Is the best way to move the method to a helper class?
You should be moving the method into a helper class that you extracted an interface to. That way it's easier to perform dependency injection and switch the underlaying implementation or mock it if needed.
Testing private methods is a code smell (or a test smell).
Use InternalsVisibleTo trick only when you must (i.e. you are using an untestable class and must raise an event that is hidden from you by a protected function call).
You should use the private object, like this:
var privateObject = new PrivateObject(this.controller);
var result = (ActionResult)privateObject.Invoke("RegisterToEvent", shippingAddressID, creditCardID);
you could set the method to internal instead of private, and then set the InternalsVisibleTo attribute to the name of your test assembly.
In assembly info:
[assembly: InternalsVisibleTo("MyTestAssembly")]
You could create an action filter for test methods like this....
public class TestActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Redirect("loginurl");
//or throw exception or some other action
}
}
Or you could make the method only publicly accessible to another assembly.
[assembly: InternalsVisibleTo("TestAssembly")]
You can work around that problem by limiting tests to visible methods. Any private method will be used at least by one visible method (otherwise: it can safely be deleted).
So I suggest to develop tests that call the visible methods with practical values so that the private algorithms are tested. If code is not reachable through visible methods - delete it.
I have used the PrivateObject() method but I like Charlino's suggestion of NonActionAttribute (see comments to original question above), too.

What's the simplest most elegant way to utilize a custom attribute

So a little confession, I've never written an attribute class. I understand they serve the purpose of decorating classes with flags or extra functionality possibly.
Can someone give me a quick example of not just creating and applying an attribute to a class, but rather utilizing the attribute from another block of code. The only code samples I've ever seen to utilize any form of attributes was doing so with reflection, though I've always hoped there's a way of using them without reflection.
Attributes are always used with reflection. They are baked into the metadata of the types during compile time and the only way to read them is through reflection. Attributes are used when you want write a type and you want to associate some metadata with it which could be used by consumers of this type.
The simplest and most elegant way to use an attribute from another block of code is to use a property instead of an attribute.
See http://blogs.msdn.com/b/ericlippert/archive/2009/02/02/properties-vs-attributes.aspx for a discussion of the differences between properties and attributes.
First create your attribute
public class ImportableAttribute : Attribute
{
}
Then a class with a item that uses the Attribute
[ImportableAttribute]
public class ImportClass
{
[ImportableAttribute]
public string Item {get; set;}
}
Then check if that property uses that attribute. Can be done with classes to.. Of course :)
PropertyInfo property = typeof(ImportClass).GetProperty("Item");
if (property.IsDefined(typeof(ImportableAttribute),true))
{
// do something
}
With a class:
typeof(ImportClass).IsDefined(typeof(ImportableAttribute), true);

Modify C# Class method during execution

I'd like to override a class method without inheriting the base class because it'd take a lot of time and modifications and, therefore, more and more tests. It's like this:
class TestClass{
public void initialMethod(){
...
}
}
And somewhere on the code, I'd like to do something like this:
public testMethod()
{
return;
}
test(){
changeMethod(TestClass.initialMethod, testMethod);
}
And this changeMethod function would override the TestClass initialMethod so that it'd call testMethod instead.
Inheriting and overriding the method using normal practices is not an option, as this class A is a graphic component and, inhereting it (and changing it) would break lots of code.
Edit: We don't have the base code for the TestClass, so it's not an option to modify the code there defining the initialMethod as a delegate.
Edit 2: Since this is a graphical component, the designer added a lot of code automatically. If I were to inherit this code, I would have to replace all code added by the designer. That's why I wouldn't like to replace this component.
You need the Strategy pattern.
Main steps:
Create an interface with ie. Do() signature
Your initialMethod() should call a strategy.Do(), where strategy is type of your interface
Create a class that implements this interface. Do() is your testmethod now.
Inject into your main class an instance of this class
If the job it's not so big (let's say just a color replacement or something) then I agree with Jhonny D. Cano's solution with C# (anonymous)delegates.
Edit (after edit 2)
May - just as proof-of-concept - you should inherit the class and replace all references from base class to this new. Do this, and nothing else. If it works, you can think about the next steps (new methods or delegates etc.)
You need only a new checkout from your version control system, and if it maybe fails you can abandon it. It's worth trying.
Perhaps you can do it as a delegate.
class TestClass {
public Action myAction;
public void initialMethod(){
...
}
initialMethod
public TestClass() {
myAction = initialMethod;
}
}
and then on TestMethod
public testMethod()
{
return;
}
test() {
testClassInstance.myAction = testMethod;
}
I think your best bet might be to use a AOP framework like LinFu. There's a codeproject article explaining it:
Introducing LinFu, Part VI: LinFu.AOP – Pervasive Method Interception and Replacement for Sealed Types in Any .NET Language
If 'TestClass' is something you defined, you could replace the 'initialMethod' definition with a property and delegate which can then be set to any method with a given signature. (Even anonymous ones.)
class TestClass {
Action _myMethod;
Action MyMethod {
get { return _myMethod; }
set { _myMethod = value; }
}
var tc = new TestClass()
tc.MyMethod = () -> Console.WriteLine("Hello World!");
tc.MyMethod()
The above code is untested.
The short and simple answer is: if you can't adjust the base TestClass code, no, there's no way you can modify the class to replace a method by another. Once we started doing stuff like that, we'd be in a completely different kind of language, like JavaScript.
The longer answer is: it depends on who is calling the replaced method.
If it's other classes, see if you can't implement a Proxy in between them and the unmodifiable concrete class. Whether this is doable depends on whether that class implements interfaces, or is its own interface.
If it's the class itself, then your only option is to decompile and modify the class, at design time using Reflector (or equivalent tools), or at runtime using Reflection.Emit. However, you'd have to be hurting pretty badly to go this route, as it's sure to be painful and brittle.
Unfortunately you still haven't explained what you are trying do and why. Replacing methods on the go is powerful stuff in the languages that permit it directly... There might be mocking libraries that can be twisted sufficiently far to do the reflection stuff, but then you'd be skating on thin ice.
If you don't have the code use Extension Methods.
public void doSmth(this objectYOUWANT arg)
{
//Do Something
}
Here you use the principle Closed for Modification Open for Extension.
This will add functionality to the library you don't have the source code. It's very clean to do it this way.
Edition:
In FrameWork 3.5 there is something new called Extension Methods. These kind of methods adds functionality to a closed Assembly letting you Extend in functionality a closed dll/assembly.
To use this for example you have a dll that you import, that is called Graphics.dll (you have the reference on your project)
First of all you shoud create a new static class called for example Extension:
public static class Extensions
{
}
Second, you want to add extra functionality to a class contained in Graphics.dll named ChartGraph. You will do this:
public static class Extensions
{
public static void draw(this ChartGraph g)
{
// DO SOMETHING
}
}
Third, when you instantiate a new object from the graphics.dll you now will have the new method you have created:
ChartGraph myG = new ChartGraph();
myG.draw();
As you can see there you have added new functionality without much effort without recompiling the dll, this is good if you don't have the source code.

Categories