Intercept method calls - c#

Is there a way of intercepting some method calls without making any code changes around the method itself?
I don't need to inject any custom behaviour at runtime, only add custom performance logging to an existing project.

You want Aspect Oriented Programming.
There are 4 main flavours of AOP
Runtime RealProxy based AOP
Runtime subclass/virtual method AOP
Post Compile IL weave AOP
Precompile source code AOP
The above are ordered in order of speed of execution (slowest to fastest). Note the last two "should" be the same speed. However I expect the compiler to produce better IL than a Post Compile IL weave.
The first camp usually includes IOC containers, since they lend themselves fairly well to this pattern, including and not limited to
Unity
Spring.NET
Castle.Windsor
Postsharp Express
The second camp, is pretty rare, and the only project that I can think of off the top of my head is Entity Framework (which uses it for Lazy loading, however it isn't extensible, and cannot be customised).
The third camp is pretty sparce also, since this technique is extremely complicated and difficult. This works by editing the dll assembly AFTER you have compiled, to add the extra code you want.
Postsharp Pro
Mono.Cecil
Fody (a mono.cecil wrapper)
The final camp is relatively new. So new in fact, the only real entry is the experimental MS Roslyn. This is actually a C# compiler. So...yeah...its pretty magic.
Now, if you are having real huge performance issues with performance critical code, I would suggest using Fody. What is awesome about this, is that it is free (unlike Postsharp Pro), it uses nuget and there is already a performance tool in Fody.MethodTimer.

I have successfully used Castle DynamicProxy for that. It's more lightweight than a full fledged AOP framework, and can be used without an IoC container.

You could take a look at Aspect Oriented Programming, and see if it's a solution for your situation.
For instance:
http://docs.castleproject.org/Default.aspx?Page=Introduction-to-AOP-With-Castle&NS=Windsor&AspxAutoDetectCookieSupport=1
http://fgheysels.blogspot.be/2006/11/aspect-oriented-programming-in-net.html

You can use any AOP Frameworks, like to Spring .NET or Unity, to intercept calls, before or after the method execute.
Thus, you dont need to change your method code.

What you are looking for is Fody: https://github.com/fody
Its open source, stable and has lots of plugins for different AOP use cases.
I am using it in a huge commercial application, and it is working very well.
Installation and configuration is super easy and done within some minutes via nuget.
Some example plugins are:
PropertyChanged: (Injects INotifyPropertyChanged code into properties at compile time)
Anotar (Simplifies logging through a static class and some IL manipulation)
Method Timer (Injects some very basic method timing code)
... and many more!
Requirements, examples and docs can be found on fodys github pages.

Using PostSharp
[Serializable]
public class LogPerformance : OnMethodBoundaryAspect
{
[NonSerialized]
Stopwatch _stopWatch;
public override void OnEntry(MethodExecutionArgs args)
{
_stopWatch = Stopwatch.StartNew();
base.OnEntry(args);
}
public override void OnExit(PostSharp.Aspects.MethodExecutionArgs args)
{
Console.WriteLine(string.Format("[{0}] took {1} ms to execute",
new StackTrace().GetFrame(1).GetMethod().Name,
_StopWatch.ElapsedMilliseconds));
base.OnExit(args);
}
}
Use the aspect like so on a function:
[LogPerformance]
static void LongRunningCalc()
{
//Your Code goes here
}
Simplified from : http://www.codeproject.com/Articles/337564/Aspect-Oriented-Programming-Using-Csharp-and-PostS

Related

Subscribe to whatever method is being executed

In my app I'm creating an auditing package that obtains various information, one such type of information should provide different information regarding what method is executed (time it took to execute, method name, method class, assembly, etc).
I'm not looking to use an existing package or framework, but to create my own.
I can imagine that this is a complicated thing to do, but I'm looking for some pointers to get me started .
One option you may be interested in is DI-level interception. Since container is responsible for your objects instantiation, sometimes it can be configured with proxy generators to enable call interception.
You can choose between Autofac, or Unity.
The most popular tasks to solve with this approach are cross-cutting concerns, like: logging, measurements, run-time application structure analysis. If you don't want to pollute your code base with repetitive diagnostic code, just delegate this task to an interceptor.
Similiar idea is AOP. I havn't seen popular AOP packages for a long time, and havn't used them, but it's worth to do a research on this topic too:
What is the best implementation for AOP in .Net?
DI Interception vs. AOP

Interceptor with Microsoft.Extensions.DependencyInjection and asp.net web api 2 for cross cutting concerns like logging

We are using Microsoft.Extensions.DependencyInjection in our asp.net web api2 for dependency injection.
For cross cutting concerns like logging, we are of thought that aspect oriented programming should be considered and unable to find any support in the above di.
Other DI like castle, Unity and ninject are opted out post looking at their benchmarks.
Is there any way to use injectors of other di frameworks like castle dynamic proxy and use it with Microsoft.Extensions.DependencyInjection?
Any suggestions related to IL-weaving frameworks are also welcomed.
Consideration of PostSharp is ruled out as it isn't free.
Decor.NET is a wrapper around Castle.Core dynamic proxy, which aims to simplify method decoration.
It is DI container agnostic, but has an integration with Microsoft's DI, which is available in Decor.Extensions.Microsoft.DependencyInjection NuGet package.
You create a decorator:
public class YourDecorator : IDecorator
{
public SomeDependency SomeDependency { get; }
public YourDecorator(SomeDependency someDependency) // Supports DI.
{
SomeDependency = someDependency;
}
public async Task OnInvoke(Call call)
{
...
await call.Next();
...
}
}
Decorate your methods:
[Decorate(typeof(YourDecorator))]
virtual void SomeMethod() // << has to be overridable (can come from an interface)
{
...
}
Register everything in Microsofts' DI:
services.AddDecor()
.AddTransient<YourDecorator>()
.AddScoped<YourService>().Decorated();
You can play around in this .Net Fiddle.
Disclosure: I'm the author of this package.
I'd argue you don't need any AOP frameworks, .NET provides just enough tooling to be able to do the majority of the aspect oriented stuff yourself.
The short version is this:
Inherit from MarshalByRefObject on your business class.
Create an "Aspect" for your desired functionality. As in, create a class that inherits from RealProxy. e.g. public class LoggingAspect<T> : RealProxy.
override the Invoke method, and implement your aspect code. Make sure to pass-though the method call to the original instance.
Create a builder/factory class that will create instances of the desired classes, e.g. Entity e = EntityBuilder.WithLogging();
Replace all instance of new Entity(...) with EntityBuilder.Get(...).
The long version is much better explained by Microsoft employees themselves:
Aspect-Oriented Programming : Aspect-Oriented Programming with the RealProxy Class
I am not convinced you need a tool like PostSharp or any other AOP tool for this when developing web api's. There are numerous extension points where you can plug in your logging/auditing/whatever actions. A good overview would be this poster
You could create an Action Filter. You can register this globally across all controllers (if needed) or a MessageHandler for example.
Now, adressing your comment:
[..] What about logging in classes of business layer/data access layer like any exceptions/ custom messages without making direct calls to logger. [..]
I am not sure what you want to achieve by this. If you have proper exception handling you have to deal with the exception or let it bubble up. When writing the exception handling, why not write one extra line that logs whatever you need? It gives you the opportunity to add meaningful context as well to your log message, something that is hard to do using an automated AOP tool!
Lastly, let me address this comment:
Consideration of PostSharp is ruled out as it isn't free.
Tools like PostSharp are very, very much worth their money if it can address the issue at hand. Sure you can spend day researching free alternatives or write your own implementation but it will probably much more limited, needs refactoring of your existing codebase, difficult to maintain for the team as a whole and it will swallow lots of time. The alternative might be more expensive than the tool.

Alternate (Free) to AOP PostSharp for method tracing (and exception)

I like to add tracing entering and leaving of every methods in classes. and also trace the arguments when an exception occurs. With PostSharp AOP, I don't need to put it in every method but just apply attributes. But I can't afford PostSharp.
Is there an alternate way to do this? Can Unity3D do that?
I am using log4net to log the message.
Yes you can do Aspect Oriented Programming and Interception using Unity.
Unity is a lightweight, extensible dependency injection container with
support for instance and type interception.
There is a great article from Dino Esposito: Aspect-Oriented Programming, Interception and Unity 2.0
Interception in Unity 2.0
The core idea of interception in Unity is enabling developers to customize the chain of calls that it takes
to invoke a method on an object. In other words, the Unity
interception mechanism captures calls being made to configured objects
and customizes the behavior of the target objects by adding some extra
code before, after or around the regular execution of methods.
Interception is essentially an extremely flexible approach to add new
behavior to an object at run time without touching its source code and
without affecting the behavior of classes in the same inheritance
path.
And also there is a great Patterns and Practices article about Interception using Unity.
The example code at article performs logging using interception.

How to Mock Sealed class with RhinoMocks [duplicate]

Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird.
So, What is the best way you mock sealed classes?
Java answers are more than welcome. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer.
But here are some of the .NET opinions:
Why Duck Typing Matters for C#
Develoepers
Creating wrappers
for sealed and other types for
mocking
Unit tests for WCF (and Moq)
For .NET, you could use something like TypeMock, which uses the profiling API and allows you to hook into calls to nearly anything.
My general rule of thumb is that objects that I need to mock should have a common interface too. I think this is right design-wise and makes tests a lot easier (and is usually what you get if you do TDD). More about this can be read in the Google Testing Blog latest post (See point 9).
Also, I've been working mainly in Java in the past 4 years and I can say that I can count on one hand the number of times I've created a final (sealed) class. Another rule here is I should always have a good reason to seal a class, as opposed to sealing it by default.
I believe that Moles, from Microsoft Research, allows you to do that. From the Moles page:
Moles may be used to detour any .NET
method, including non-virtual/static
methods in sealed types.
UPDATE: there is a new framework called "Fakes" in the upcoming VS 11 release that is designed to replace Moles:
The Fakes Framework in Visual Studio 11 is the next generation of Moles & Stubs, and will eventually replace it. Fakes is different from Moles, however, so moving from Moles to Fakes will require some modifications to your code. A guide for this migration will be available at a later date.
Requirements: Visual Studio 11 Ultimate, .NET 4.5
The problem with TypeMock is that it excuses bad design. Now, I know that it is often someone else's bad design that it's hiding, but permitting it into your development process can lead very easily to permitting your own bad designs.
I think if you're going to use a mocking framework, you should use a traditional one (like Moq) and create an isolation layer around the unmockable thing, and mock the isolation layer instead.
I came across this problem recently and after reading / searching web, seems like there is no easy way around except to use another tool as mentioned above.
Or crude of handling things as I did:
Create instance of sealed class without getting constructor called.
System.Runtime.Serialization.FormatterServices.GetUninitializedObject(instanceType);
Assign values to your properties / fields via reflection
YourObject.GetType().GetProperty("PropertyName").SetValue(dto, newValue, null);
YourObject.GetType().GetField("FieldName").SetValue(dto, newValue);
I almost always avoid having dependencies on external classes deep within my code. Instead, I'd much rather use an adapter/bridge to talk to them. That way, I'm dealing with my semantics, and the pain of translating is isolated in one class.
It also makes it easier to switch my dependencies in the long run.
It is perfectly reasonable to mock a sealed class because many framework classes are sealed.
In my case I'm trying to mock .Net's MessageQueue class so that I can TDD my graceful exception handling logic.
If anyone has ideas on how to overcome Moq's error regarding "Invalid setup on a non-overridable member", please let me know.
code:
[TestMethod]
public void Test()
{
Queue<Message> messages = new Queue<Message>();
Action<Message> sendDelegate = msg => messages.Enqueue(msg);
Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate =
(v1, v2) =>
{
throw new Exception("Test Exception to simulate a failed queue read.");
};
MessageQueue mockQueue = QueueMonitorHelper.MockQueue(sendDelegate, receiveDelegate).Object;
}
public static Mock<MessageQueue> MockQueue
(Action<Message> sendDelegate, Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate)
{
Mock<MessageQueue> mockQueue = new Mock<MessageQueue>(MockBehavior.Strict);
Expression<Action<MessageQueue>> sendMock = (msmq) => msmq.Send(It.IsAny<Message>()); //message => messages.Enqueue(message);
mockQueue.Setup(sendMock).Callback<Message>(sendDelegate);
Expression<Func<MessageQueue, Message>> receiveMock = (msmq) => msmq.Receive(It.IsAny<TimeSpan>(), It.IsAny<MessageQueueTransaction>());
mockQueue.Setup(receiveMock).Returns<TimeSpan, MessageQueueTransaction>(receiveDelegate);
return mockQueue;
}
Although it's currently only available in beta release, I think it's worthwhile keeping in mind the shim feature of the new Fakes framework (part of the Visual Studio 11 Beta release).
Shim types provide a mechanism to detour any .NET method to a user defined delegate. Shim types are code-generated by the Fakes generator, and they use delegates, which we call shim types, to specify the new method implementations. Under the hood, shim types use callbacks that were injected at runtime in the method MSIL bodies.
Personally, I was looking at using this to mock the methods on sealed framework classes such as DrawingContext.
I generally take the route of creating an interface and adaptor/proxy class to facilitate mocking of the sealed type. However, I've also experimented with skipping creation of the interface and making the proxy type non-sealed with virtual methods. This worked well when the proxy is really a natural base class that encapsulates and users part of the sealed class.
When dealing with code that required this adaptation, I got tired of performing the same actions to create the interface and proxy type so I implemented a library to automate the task.
The code is somewhat more sophisticated than the sample given in the article you reference, as it produces an assembly (instead of source code), allows for code generation to be performed on any type, and doesn't require as much configuration.
For more information, please refer to this page.
Is there a way to implement a sealed class from an interface... and mock the interface instead?
Something in me feels that having sealed classes is wrong in the first place, but that's just me :)

One framework for Dependency injection (in MVC app) and for simple AOP task (using attributes)

I have come to the point where I want to accomplish 2 tasks in my ASP.NET application that both can be done using some AOP framework but they are both of different nature:
Dependency injection for my controllers and services
I have created custom attribute NotNullAttribute and marked some method's parameters or properties with it instead of of throwing ArgumentNullException if those parameters or properties were null. I want AOP framework to check for those attributes in compile time and add throw causes instead. Example follows:
//original code that I write
public void MyMethod([NotNull]string param1){
//do something
}
.
//code actually being compiled - after AOF processing/weaning
public void MyMethod(string patam1){
if(param1 == null){
throw new ArgumentNullException("param1");
}
//do something
}
So I want framework (does not even have to be AOP necessarily but I guess it would have to be) that will allow me to do both those task simply.
I have some additional requirements:
small footprint, 1 or 2 assemblies
integration to VS - I just want to press Ctrl+F5 to compile and the framework does it work, injects dependencies, adds exception throwing code without me even knowing about it. I don't want to run pre-compilation from command line or anything like that.
for exception throwing code generation I'd like write classes. Like regular aspects. Not XML, no configuration (conventions are acceptable). For dependency injection I also prefer classes but XML or another config file is acceptable but it should be simple enough to use by somebody who don't really know XML and don't really like it.
Is there some such framework ? If there are more what are they pros/cons ?
EDIT: Oh yes I forgot very important think: The framework should be for free.
I don't have any personal experience with it, but I think Linfu fits your description.
Apart from that, you can get AOP-like behavior from DI Containers with dynamic interception - here's an example: http://blog.ploeh.dk/2010/09/20/InstrumentationWithDecoratorsAndInterceptors.aspx
The following DI Containers support interception out of the box:
Castle Windsor
Unity
Spring.NET
Pure AOP (without DI) can be had with PostSharp.

Categories