PostSharp: aspecting classes that implement certain interface - .net-4.5

I can do the multiple declaration at AssemblyInfo.cs file at web service project, aspecting classs' method under specific namespace.
This is for my ASP.NET web api project.
I would like to aspecting through interface, stuffs that I want to subject to certain type of aspects, I will implement a specific interface (just a blank interface) at the class, then at the AssemblyInfo file, I will do something like:
[assembly: My.AOP.ValidateArguement(
//AttributeTargetTypes = "My.WebServices.Controllers.*"
AttributeTargetTypes = "My.WebServices.IWebApi"
, AttributeTargetElements = MulticastTargets.Method
, AttributeTargetTypeAttributes = MulticastAttributes.Public | MulticastAttributes.Instance
, AttributeTargetMemberAttributes = MulticastAttributes.Public | MulticastAttributes.Instance
)]
And I tested this doesn't work. AttributeTargetTypes only work for namespace.
When the web api class/controller grow, I can easily manage through Interface tagging to class.

When you apply the aspect attribute to interface methods, you can also enable the propagation of this attribute to the methods implementing the interface in concrete classes. For this you need to set the AttributeInheritance property when applying the attribute. In your case it should be enought to set it to MulticastInheritance.Strict.
[assembly: My.AOP.ValidateArguement(
AttributeTargetTypes = "My.WebServices.IWebApi",
AttributeInheritance = MulticastInheritance.Strict
/* ... */
)]
Please refer to Understanding Aspect Inheritance documentation page for more information.

Related

Enterprise Architect Code Generation: Get tags of interface

I use Enterprise Architect for code generation and I would like to automatically retrieve all tags (in my case Java annotations) of the interfaces that a class realizes. Consider the following example:
From this model, I want to generate a class that looks like this:
#AnnotationOfMyInterface
public class MyClass {
...
}
So I want to add annotations as tags to MyInterface that should be applied to MyClass during code generation. In the UI, tags of implemented interfaces are shown so I was hoping there is a way to get these tags during code generation.
I tried to edit the code generation templates and found macros to get
All interfaces that a class implements: %list="ClassInterface" #separator=", "%
All tags with a given name (of the class that code is being generated for): %classTag:"annotations"%
But unfortunately, I cannot combine these macros, i.e., I cannot pass one interface to the classTag macro so that I can retrieve the tags of that particular interface (and not the one I'm generating code for). Is there a way to get classTags of a specific class / interface?
I also tried to create a separate code generation template and "call" it from the main class code generation template. But inside my template, the classTag macro still only gets the tags of the class.
Thanks to the comments above and especially because of an answer to my question in EA's forum, I was able to setup a little proof of concept achieving what I wanted. I'm answering my question to document my solution in case someone has a similar problem in the future.
After Eve's hint in EA's forum I looked into creating an AddIn for Enterprise Architect to use this AddIn from a code generation template. I started by writing a basic AddIn as explained by #Geert Bellekens in this tutorial. Afterwards I changed the AddIn to fit my needs. This is how I finally got the tagged values (annotations) of the interfaces a class realizes:
First step:
Inside a code generation template, I get all the interfaces a class realizes and pass them to my AddIn:
$interfaces=%list="ClassInterface" #separator=", "%
%EXEC_ADD_IN("MyAddin","getInterfaceTags", $interfaces)%
Second step:
As documented here the repository objects gets passed along with the EXEC_ADD_IN call. I use the repository object and query for all interfaces using the names contained in $interfaces. I can then get the tagged values of each interface element. Simple prototype that achieves this for a single interface:
public Object getInterfaceTags(EA.Repository repo, Object args)
{
String[] interfaceNames = args as String[];
String firstInterfaceName = interfaceNames[0];
EA.Element interfaceElement = repo.GetElementsByQuery("Simple", firstInterfaceName).GetAt(0);
String tag = interfaceElement.TaggedValues.GetAt(0);
return interfaceElement.Name + " has tag value" + tag.Value;
}
I know, there are a couple of shortcomings but this is just a simple proof of concept for an idea that will most likely never be production code.

How to create a library exposing named configured singletons generated at runtime with Dagger 2?

I'm considering migrating to Dagger 2 some libraries. This library expose a configurable client, each configuration can be named and later retrieved in a singleton fashion.
Let me show a pseudo-code of how the library works from the user perspective:
// initialization
ClientSDK clientA = new ClientSDK.Builder()
.configuration().attributes().here()
.apiKey("someString") // set api key / credentials
.build();
LibraryAuthenticationManager customAuthManager = new MyCustomAuthenticationManager();
ClientSDK clientB = new ClientSDK.Builder()
.configuration().attributes().here()
.apiKey("someStringElse")
.customAuthManager(customAuthManager) // override some default
.baseApiUrl("https://custom.domain.com/and/path") // override some default setting
.build();
ClientSDK.setSingleton("clientA", clientA);
ClientSDK.setSingleton("clientB", clientB);
And when I need an instance elsewhere:
// usage everywhere else
ClientSDK clientB = ClientSDK.singleton("clientB");
clientB.userManager(); // "singleton" using the configuration of clientB
clientB.subscriptionsManager(); // "singleton" using the configuration of clientB
clientB.currentCachedUser(); // for clientB
clientB.doSomething(); // action on this instance of the ClientSDK
ClientSDK instances are created by the user of the library and the ClientSDK statically keep a map of singletons associated to the name.
(The actual behavior of the SDK is slightly different: the naming is automatic and based on a mandatory configuration parameter.)
It's like I have lot of singleton classes with a single point of entry (the ClientSDK) but since I can have multiple configuration of the ClientSDK each with his own singletons instances this are not really singletons.
If I would try write a library like that with Dagger 2 I would do something like:
class ClientSDK {
#Inject SDKConfiguration configuration;
#Inject LibraryAuthenticationManager authManager;
...
}
The problem is that I need each instance of the ClientSDK to have its own configuration and authManager (and many other services) injected. And they need to be definable (the configuration) and overridable (the actual implementation) from the library user.
Can I do something like this with Dagger 2? How?
I've seen I can create custom Scopes but they are defined at compile time and the library user should be the one defining them.
(the library is an Android Library, but this shouldn't be relevant)
Thanks
It sounds like you should be creating stateful/configurable Module instances and then generating separate Components or Subcomponents for each ClientSDK you build.
public class ClientSDK {
#Inject SDKConfiguration configuration;
#Inject LibraryAuthenticationManager authManager;
// ...
public static class Builder {
// ...
public ClientSDK build() {
return DaggerClientSDKComponent.builder()
.configurationModule(new ConfigurationModule(
apiKey, customAuthManager, baseApiUrl)
.build()
.getClientSdk();
}
}
}
...where your ConfigurationModule is a #Module you write that takes all of those configuration parameters and makes them accessible through properly-qualified #Provides methods, your ClientSDKComponent is a #Component you define that refers to the ConfigurationModule (among others) and defines a #Component.Builder inner interface. The Builder is important because you're telling Dagger it can no longer use its modules statically, or through instances it creates itself: You have to call a constructor or otherwise procure an instance, which the Component can then consume to provide instances.
Dagger won't get into the business of saving your named singletons, but it doesn't need to: you can save them yourself in a static Map, or save the ClientSDKComponent instance as an entry point. For that matter, if you're comfortable letting go of some of the control of ClientSDK, you could even make ClientSDK itself the Component; however, I'd advise against it, because you'll have less control of the static methods you want, and will lose the opportunity to write arbitrary methods or throw exceptions as needed.
You don't have to worry yourself about scopes, unless you want to: Dagger 2 tracks scope lifetime via component instance lifetime, so scopes are very easy to add for clarity but are not strictly necessary if you're comfortable with "unscoped" objects. If you have an object graph of true singleton objects, you can also store that component as a conventional (static final field) singleton and generate your ClientSDKComponent as a subcomponent of that longer-lived component. If it's important to your build dependency graph, you can also phrase it the other way, and have your ClientSDKComponent as a standalone component that depends on another #Component.

PostSharp AOP - Unable to apply aspect to mscorlib System.IO.StreamReader members

**I'm using PostSharp Express... not sure that would make a difference in this instance though.
I've got an OnMethodBoundary->OnEntry aspect that successfully multicasts at the assembly level to class members in my own code, but when I attempt to apply it to mscorlib System.IO.StreamReader members, no dice. Based on the searching I've done on the PostSharp web site, here on SO, and on Google, I can't tell what the correct way to go about this is with the current version of PostSharp. Does anyone know? Hopefully I'm just missing something simple :\
Here's the aspect followed by multicast attribute I'm using:
namespace Test.Aspects {
[AttributeUsage(AttributeTargets.Assembly)]
[MulticastAttributeUsage(MulticastTargets.Method, AllowMultiple = false)]
[Serializable]
public class PatchStreamReaderAttribute : OnMethodBoundaryAspect {
public override void OnEntry(MethodExecutionArgs args) {
System.Threading.Thread.Sleep(1000);
}
}
}
[assembly: PatchStreamReader(AttributeTargetMembers = "ReadLine", AttributeTargetAssemblies = "mscorlib", AttributeTargetTypes = "System.IO.StreamReader")]
Usually, when you apply an aspect in a given assembly, PostSharp will modify that assembly during its build process. This, of course, cannot happen for mscorlib or, in fact, for any 3-rd party library you reference but do not build from source code.
This is why PostSharp uses different approach when applying aspects to the referenced assemblies using AttributeTargetAssemblies. Instead of modifying the target 3-rd party assembly, PostSharp will modify the calls from your assembly to the target assembly.
This, of course, gives you less options of where you can inject your code. For example, PostSharp can detect the call to the library's method and inject the aspect around that call. But you cannot inject the aspect around the static or instance constructor of the type from the library.
You also need to pay attention to the AttributeTargetTypes property when applying the aspect. For example, you want to apply the aspect on the calls to the StreamReader.ReadLine() method. This virtual ReadLine() method is originally declared on the TextReader class and StreamReader overrides the method. If you look at the IL, then the method call looks like this:
callvirt instance string [mscorlib]System.IO.TextReader::ReadLine()
This means you need to set AttributeTargetTypes property to "System.IO.TextReader" to apply the aspect to the ReadLine() method.

Creating global aspects in postsharp

I am looking for a way in which to all aspects to run on methods in many places in my project, without having to manually add in the attribute tag to each method or class.
My entire solution holds around 20 separate projects. One of which I have created called myname.space.Attributes which holds my attribute declarations, as well as a file called GlobalAspects which has the following:
using PostSharp.Patterns.Diagnostics;
using PostSharp.Extensibility;
using myname.space.Attributes;
// This file contains registration of aspects that are applied to several classes of this project.
[assembly: TraceLoggingAttribute(AttributeTargetTypes = "myname.space.Controllers.*",
AttributeTargetTypeAttributes = MulticastAttributes.AnyVisibility,
AttributeTargetMemberAttributes = MulticastAttributes.AnyVisibility)
]
[assembly: TraceLoggingAttribute(AttributeTargetTypes = "myname.space.Repositories.*",
AttributeTargetTypeAttributes = MulticastAttributes.AnyVisibility,
AttributeTargetMemberAttributes = MulticastAttributes.AnyVisibility)
]
The goal of this was to add my TraceLoggingAttribute to all the methods held within these other 2 projects, Controllers and Repositories.
I have set up these 2 other projects to reference the Attributes project, and the attribute works perfectly fine if I put the [TraceLoggingAttribute] tag on the classes and methods within the Controller and Repositories projects.
Is there a way in which I can set up my GlobalAspects.cs to work in the way I am looking for? Please ask question if I have not explained the issue well enough here
For interest, the TraceLoggingAttribute is defined as:
namespace myname.space.Attributes
{
[MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Instance)]
[Serializable]
public class TraceLoggingAttribute : OnMethodBoundaryAspect
{
Unfortunately you can only apply attributes to currently compiled assembly (or to calls to other assemblies through TargetAssembly property but that also affects only currently compiled assembly).
I think that the easiest solution would be to link GlobalAspects.cs into all projects that you want to be affected by it. This should work as you expect and not cause any problems.
Hope that helps.

Tell C# to use Castle to create objects

I think my question is a long shot.
Lets say I have an attribute:
public sealed class MyCustomAttribute: ActionFilterAttribute
Used on a class method
[MyCustomAttribute]
public virtual ActionResult Options(FormCollection collection)
Now, I need to add a contructor's parameter
public MyCustomAttribute(IMyDependentObject dependentObject)
{
(...)
}
(You propably notice that it's some Asp.NET MCV code)
I would like to use DI to create this attribute. Asp.NET MVC code automatically create it and I don't know how/where I could write code to use Castle istead.
Any ideas?
As far a I konw castle does not support injection of existing objects, which makes it impossible to inject attributes as their construction is not under your control. Other IoC containers such as Ninject support injection of existing objects. They inject properties of your attribut filter. See http://github.com/ninject/ninject.web.mvc for an extension that exactly does what you need.
What you can do if you want to stay on castle is to inject your own ControllerActionInvoker derived from ControllerActionInvoker (AsyncControllerActionInvoker in case of async controller) into all controllers. In your own invoker you override GetFilters. Additionally to the Filters returned by the base you add FilterInfos that are created by castle.
The decision which filters infos are created and added can be achieved with various strategies e.g.:
Add an own custom attribute that contains the information e.g. name of a binding
A configuration file/database
May you consider switching to MVC3 this makes all a bit easier. As you can register your own FilterProvider which makes all much easier. In this FilterProvider you have to decide which filter info you want to add. See again the two strategies above. See http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html for information about MVC3 and filters.