Open source AOP library for .NET with no interception limitations - aop

This topic may look like it has been discussed already but I have few more things to say and ask.
The obvious question is; I want to know what AOP library shall I go for a .NET 4.0 enterprise application? As per the post What Aspect-Oriented Programming (AOP) libraries for .NET are still actively developed, one should choose PostSharp or Spring.NET or Microsoft's Policy Injection Application Block. But there are problem with each one.
PostSharp: This is best but not open. I need one whose source is open.
Spring.NET: This is too heavy and has limitations like it can intercept only those classes that is not static, must be non-sealed, properties and methods must be virtual, etc...
Microsoft's Policy Injection Application Block: As per the post Policy Injection Application Block, this is a legacy component now and may stop being supported by MS and since it is implemented through the Unity interception mechanism hence it has same limitation as that of Spring.NET (Alternatives to PostSharp)
I came across the post Aspect Oriented Programming: learn step by step and roll your own implementation!. I have not used it yet but reading through the post gave me an idea that it should serve my purpose. I want to know if anyone has tried it and if it is advised to go for it?
I have one more question to ask; I have used Unity for DI and it is all cool but for AOP, unity is not a good option for my purpose hence I will definitely go for some other tool/library (maybe the one I suggested above!). Is it good to have Unity and something else for AOP in the same application, will there be any problem?
Can anyone please help me here? Thank you in advance!

I think you'll find few good options once you preclude PostSharp and also want to intercept static code.
Some options that you might check out are SheepAspect and Fody, which both take a similar approach to PostSharp (post-compile weaving). Both are very nice and show promise, but are relatively young compared to PostSharp.

Related

Is it possible to develop with MassTransit in VB.NET?

I'm a casual developer and typically use VB.Net when writing solutions, as its what I'm most familiar with. Though I aim to learn other languages in the future, such as C#, its very much on the back-burner and so here we are.
One of my current projects would benefit greatly from a service-bus architecture, so I have been researching potential options. Some of the more obvious choices, such as Azure Service Bus, are out of the question, as my application will not have access to the public internet once operational. Looking in to options that could be run within a local site I've stumbled across both nServiceBus & MassTransit as front runners.
My current stumbling block is that all the documentation and sample code seems to be written for C#. My question would be if the frameworks require programming to take place in C# exclusively, or whether I can utilise another .NET language (such as VB) instead. If this is indeed possible, I wonder if anyone could point me in the direction of some sample code? Of course I can gradually reverse engineer the C# if necessary, once I know if VB development is even possible (or practical).
Thanks,
Chris.

Is there a repository/library of ready-to-use postsharp aspects?

I'm about to start using PostSharp in my project. I'd like to leverage existing aspects. Is there a repository or a list of ready-to-use, user contributed, postsharp aspects? Something like the Mercurial'S extensions list.
For instance, is there a production ready implementation of the INotifyPropertyChanged pattern (I know there is one in the examples but I don't know if it's production ready)...
I saw the Shared Add Ins page on postsharp's website but it's not really what I'm looking for.
At this point in time, there is no aspect library that you can pull from. at least any "official". I have created my own to be used within my organization. You'll probably have to do the same.
That is a good idea, but not everyone will be able to use all aspects though. They would need to be configurable. The problem is that the business rules going into each hook will vary by organization so what's the point?
As far as the INotifyPropertyChanged aspect in the examples, that is a great place to start as it's one of the more popular aspects. I've used it several times in production. However, you should always test.
We have a whole bunch of aspects created and after cleanup will release them on Github not too far in the future. However this does not answer your question right now. I am willing to share what we have so far. Do you have a blog or something likewise where I can contact you?

How do you write good highly useful general purpose libraries?

I asked this question about Microsoft .NET Libraries and the complexity of its source code. From what I'm reading, writing general purpose libraries and writing applications can be two different things. When writing libraries, you have to think about the client who could literally be everyone (supposing I release the library for use in the general public).
What kind of practices or theories or techniques are useful when learning to write libraries? Where do you learn to write code like the one in the .NET library? This looks like a "black art" which I don't know too much about.
That's a pretty subjective question, but here's on objective answer. The Framework Design Guidelines book (be sure to get the 2nd edition) is a very good book about how to write effective class libraries. The content is very good and the often dissenting annotations are thought-provoking. Every shop should have a copy of this book available.
You definitely need to watch Josh Bloch in his presentation How to Design a Good API & Why it Matters (1h 9m long). He is a Java guru but library design and object orientation are universal.
One piece of advice often ignored by library authors is to internalize costs. If something is hard to do, the library should do it. Too often I've seen the authors of a library push something hard onto the consumers of the API rather than solving it themselves. Instead, look for the hardest things and make sure the library does them or at least makes them very easy.
I will be paraphrasing from Effective C++ by Scott Meyers, which I have found to be the best advice I got:
Adhere to the principle of least astonishment: strive to provide classes whose operators and functions have a natural syntax and an intuitive semantics. Preserve consistency with the behavior of the built-in types: when in doubt, do as the ints do.
Recognize that anything somebody can do, they will do. They'll throw exceptions, they'll assign objects to themselves, they'll use objects before giving them values, they'll give objects values and never use them, they'll give them huge values, they'll give them tiny values, they'll give them null values. In general, if it will compile, somebody will do it. As a result, make your classes easy to use correctly and hard to use incorrectly. Accept that clients will make mistakes, and design your classes so you can prevent, detect, or correct such errors.
Strive for portable code. It's not much harder to write portable programs than to write unportable ones, and only rarely will the difference in performance be significant enough to justify unportable constructs.
Even programs designed for custom hardware often end up being ported, because stock hardware generally achieves an equivalent level of performance within a few years. Writing portable code allows you to switch platforms easily, to enlarge your client base, and to brag about supporting open systems. It also makes it easier to recover if you bet wrong in the operating system sweepstakes.
Design your code so that when changes are necessary, the impact is localized. Encapsulate as much as you can; make implementation details private.
Edit: I just noticed I very nearly duplicated what cherouvim had posted; sorry about that! But turns out we're linking to different speeches by Bloch, even if the subject is exactly the same. (cherouvim linked to a December 2005 talk, I to January 2007 one.) Well, I'll leave this answer here — you're probably best off by watching both and seeing how his message and way of presenting it has evolved :)
FWIW, I'd like to point to this Google Tech Talk by Joshua Bloch, who is a greatly respected guy in the Java world, and someone who has given speeches and written extensively on API design. (Oh, and designed some exceptionally good general purpose libraries, like the Java Collections Framework!)
Joshua Bloch, Google Tech Talks, January 24, 2007:
"How To Design A Good API and Why it
Matters" (the video is about 1 hour long)
You can also read many of the same ideas in his article Bumper-Sticker API Design (but I still recommend watching the presentation!)
(Seeing you come from the .NET side, I hope you don't let his Java background get in the way too much :-) This really is not Java-specific for the most part.)
Edit: Here's another 1½ minute bit of wisdom by Josh Bloch on why writing libraries is hard, and why it's still worth putting effort in it (economies of scale) — in a response to a question wondering, basically, "how hard can it be". (Part of a presentation about the Google Collections library, which is also totally worth watching, but more Java-centric.)
Krzysztof Cwalina's blog is a good starting place. His book, Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, is probably the definitive work for .NET library design best practices.
http://blogs.msdn.com/kcwalina/
The number one rule is to treat API design just like UI design: gather information about how your users really use your UI/API, what they find helpful and what gets in their way. Use that information to improve the design. Start with users who can put up with API churn and gradually stabilize the API as it matures.
I wrote a few notes about what I've learned about API design here: http://www.natpryce.com/articles/000732.html
I'd start looking more into design patterns. You'll probably not going to find much use for some of them, but as you get deeper into your library design the patterns will become more applicable. I'd also pick up a copy of NDepend - a great code measuring utility which may help you decouple things better. You can use .NET libraries as an example, but, personally, i don't find them to be great design examples mostly due to their complexities. Also, start looking at some open source projects to see how they're layered and structured.
A couple of separate points:
The .NET Framework isn't a class library. It's a Framework. It's a set of types meant to not only provide functionality, but to be extended by your own code. For instance, it does provide you with the Stream abstract class, and with concrete implementations like the NetworkStream class, but it also provides you the WebRequest class and the means to extend it, so that WebRequest.Create("myschema://host/more") can produce an instance of your own class deriving from WebRequest, which can have its own GetResponse method returning its own class derived from WebResponse, such that calling GetResponseStream will return your own class derived from Stream!
And your callers will not need to know this is going on behind the scenes!
A separate point is that for most developers, creating a reusable library is not, and should not be the goal. The goal should be to write the code necessary to meet requirements. In the process, reusable code may be found. In that case, it should be refactored out into a separate library, where it can be reused in the future.
I go further than that (when permitted). I will usually wait until I find two pieces of code that actually do the same thing, or which overlap. Presumably both pieces of code have passed all their unit tests. I will then factor out the common code into a separate class library and run all the unit tests again. Assuming that they still pass, I've begun the creation of some reusable code that works (since the unit tests still pass).
This is in contrast to a lesson I learned in school, when the result of an entire project was a beautiful reusable library - with no code to reuse it.
(Of course, I'm sure it would have worked if any code had used it...)

WCF service instantiation via IoC container

Can the WCF runtime be made to instantiate a service via an IoC container rather than via its usual process? (Also, given a potential clash between the container's lifestyle configuration for the type and the service's InstanceContextBehavior, would this approach be a terrible idea?)
I'm aware that I might be asking the wrong question altogether. My objective is an AOP approach via method interception facilities provided by the container (for example, method enter/exit logging, perf counting, and call throttling, all involving logic and dependencies that I do not want to insert into my service implementation). I imagine WCF provides other ways to approach this, so I would also be curious to hear other recommended approaches.
Short answer - yes it may.
Please take a look at Castle WCF intergration. It let's you use Castle Windsor for WCF, what gives you much more powerful capabilities than just injecting dependencies.
It's best to use the trunk version found here. There's not much documentation on it, but take a look at tests. They are easy to follow and will be a good sample code for you.
WCF facility let's you do exactly those kinds of thinkgs you're asking about.
Yes, heres implementations using both ObjectBuilder and Spring.NET (and more if you follow the links!):
http://www.infoq.com/news/2008/01/wcf-di
Can't comment on lifestyle and instance context behavior interaction though.
As for more WCF-specific approaches, leveraging WCFs behaviors concept (as the above example does) may also be useful. There are several different types, heres a starting point:
http://mehranikoo.net/CS/archive/2007/02/22/WCFBehaviours.aspx
Cheers,
Matt

Do you use AOP (Aspect Oriented Programming) in production software?

AOP is an interesting programming paradigm in my opinion. However, there haven't been discussions about it yet here on stackoverflow (at least I couldn't find them). What do you think about it in general? Do you use AOP in your projects? Or do you think it's rather a niche technology that won't be around for a long time or won't make it into the mainstream (like OOP did, at least in theory ;))?
If you do use AOP then please let us know which tools you use as well. Thanks!
Python supports AOP by letting you dynamically modify its classes at runtime (which in Python is typically called monkeypatching rather than AOP). Here are some of my AOP use cases:
I have a website in which every page is generated by a Python function. I'd like to take a class and make all of the webpages generated by that class password-protected. AOP comes to the rescue; before each function is called, I do the appropriate session checking and redirect if necessary.
I'd like to do some logging and profiling on a bunch of functions in my program during its actual usage. AOP lets me calculate timing and print data to log files without actually modifying any of these functions.
I have a module or class full of non-thread-safe functions and I find myself using it in some multi-threaded code. Some AOP adds locking around these function calls without having to go into the library and change anything.
This kind of thing doesn't come up very often, but whenever it does, monkeypatching is VERY useful. Python also has decorators which implement the Decorator design pattern (http://en.wikipedia.org/wiki/Decorator_pattern) to accomplish similar things.
Note that dynamically modifying classes can also let you work around bugs or add features to a third-party library without actually having to modify that library. I almost never need to do this, but the few times it's come up it's been incredibly useful.
Yes.
Orthogonal concerns, like security, are best done with AOP-style interception. Whether that is done automatically (through something like a dependency injection container) or manually is unimportant to the end goal.
One example: the "before/after" attributes in xUnit.net (an open source project I run) are a form of AOP-style method interception. You decorate your test methods with these attributes, and just before and after that test method runs, your code is called. It can be used for things like setting up a database and rolling back the results, changing the security context in which the test runs, etc.
Another example: the filter attributes in ASP.NET MVC also act like specialized AOP-style method interceptors. One, for instance, allows you to say how unhandled errors should be treated, if they happen in your action method.
Many dependency injection containers, including Castle Windsor and Unity, support this behavior either "in the box" or through the use of extensions.
I don't understand how one can handle cross-cutting concerns like logging, security, transaction management, exception-handling in a clean fashion without using AOP.
Anyone using the Spring framework (probably about 50% of Java enterprise developers) is using AOP whether they know it or not.
At Terracotta we use AOP and bytecode instrumentation pretty extensively to integrate with and instrument third-party software. For example, our Spring intergration is accomplished in large part by using aspectwerkz. In a nutshell, we need to intercept calls to Spring beans and bean factories at various points in order to cluster them.
So AOP can be useful for integrating with third party code that can't otherwise be modified. However, we've found there is a huge pitfall - if possible, only use the third party public API in your join points, otherwise you risk having your code broken by a change to some private method in the next minor release, and it becomes a maintenance nightmare.
AOP and transaction demarcation is a match made in heaven. We use Spring AOP #Transaction annotations, it makes for easier and more intuitive tx-demarcation than I've ever seen anywhere else.
We used aspectJ in one of my big projects for quite some time. The project was made up of several web services, each with several functions, which was the front end for a complicated document processing/querying system. Somewhere around 75k lines of code. We used aspects for two relatively minor pieces of functionality.
First was tracing application flow. We created an aspect that ran before and after each function call to print out "entered 'function'" and "exited 'function'". With the function selector thing (pointcut maybe? I don't remember the right name) we were able to use this as a debugging tool, selecting only functions that we wanted to trace at a given time. This was a really nice use for aspects in our project.
The second thing we did was application specific metrics. We put aspects around our web service methods to capture timing, object information, etc. and dump the results in a database. This was nice because we could capture this information, but still keep all of that capture code separate from the "real" code that did the work.
I've read about some nice solutions that aspects can bring to the table, but I'm still not convinced that they can really do anything that you couldn't do (maybe better) with "normal" technology. For example, I couldn't think of any major feature or functionality that any of our projects needed that couldn't be done just as easily without aspects - where I've found aspects useful are the kind of minor things that I've mentioned.
I use AOP heavily in my C# applications. I'm not a huge fan of having to use Attributes, so I used Castle DynamicProxy and Boo to apply aspects at runtime without polluting my code
We use AOP in our session facade to provide a consistent framework for our customers to customize our application. This allows us to expose a single point of customization without having to add manual hook support in for each method.
Additionally, AOP provides a single point of configuration for additional transaction setup and teardown, and the usual logging things. All told, much more maintainable than doing all of this by hand.
The main application I work on includes a script host. AOP allows the host to examine the properties of a script before deciding whether or not to load the script into the Application Domain. Since some of the scripts are quite cumbersome, this makes for much faster loading at run-time.
We also use and plan to use a significant number of attributes for things like compiler control, flow control and in-IDE debugging, which do not need to be part of the final distributed application.
We use PostSharp for our AOP solution. We have caching, error handling, and database retry aspects that we currently use and are in the process of making our security checks an Aspect.
Works great for us. Developers really do like the separation of concerns. The Architects really like having the platform level logic consolidated in one location.
The PostSharp library is a post compiler that does the injection of the code. It has a library of pre-defined intercepts that are brain dead easy to implement. It feels like wiring in event handlers.
Yes, we do use AOP in application programming . I preferably use AspectJ for integrating aop in my Spring applications. Have a look at this article for getting a broader prospective for the same.
http://codemodeweb.blogspot.in/2018/03/spring-aop-and-aspectj-framework.html