I'm wondering if it's possible to wrap a method only by adding an attribute.
Example: I want to log the execution time a method takes.
[LogTimings]
public void work()
{
..
}
This is kind of wrapping a method into another one (see this python implementation).
AOP is possible in .NET. Here's an article about it. And here's a list of AOP frameworks for .NET.
Have a look at PostSharp, an AOP framework for .NET.
In terms of logging and timing, there's also a framework called Gibraltar which integrates with PostSharp and which should make it easier to collect and use the results. I keep meaning to get round to trying it...
Using only the standard .NET framework library, you would have to create the wrap functionality by deriving from System.Runtime.Remoting.Proxies.RealProxy.
This functionality you then can apply to your class, but this class has to derive from System.MarshalByRefObject.
This is quite some restriction, that's why you might want to look at 3rd party components like PostSharp.
You can do this without having to use a different compiler if you use PostSharp.
I wrote some stuff about AOP on .Net here:
Help and Information about Aspect Oriented Programming
Related
I want to log the entry of methods. In entry log I would have inputs\parameters received by the method. This has to be done for thousands of methods.
I thought of doing this logging of input parameters using C# ATTRIBUTES, since they fired before method call. (Something similar to ActionFilters in MVC)
Is that possible to read method parameters through attributes?
The concept you are looking for is called aspect oriented programming (AOP). It is a technique that allows you to "weave" in blocks of boilerplate code across your application code. Logging is a perfect example for that. You can either go the hard way and implement logging before and after each method call manually (which is on the one hand not feasible in large projects and on the other hand error prone).
Or you can use an AOP Framework that allows you to define these cross cutting functions in one place and apply it declaratively to your application code. There are several approaches to achieve this; one is to create IL after the build of the application logic and therefore integrating the aspects at compile time. A well known example for this is PostSharp. There also is a free edition that is good for the start.
BTW: PostSharp heavily relies on attributes, so you're on the right track.
Another option is to integrate the aspects at run time (keyword is interception). Most IoC Frameworks offer this. This approach is easy to use but has some downsides IMHO (weaker runtime Performance, only virtual methods can be intercepted).
Attributes are not 'fired before method call', the code that invokes a method that is decorated with an Attribute may (or may not) do something based on the presence of the Attribute.
The Attribute doesn't know the member it is applied on, nor can access it in any (straight forward) way.
What intrinsic properties of jQuery and the requirements it satisfies makes it such a good candidate for the builder pattern and method chaining?
Asked another way, could the C#/VB .NET core libraries be rewritten with much more method chaining similar to jQuery or are there some inherit, limiting factors?
Does a lot of it come down to JavaScript being dynamic vs. typed like VB/C# or something with jQuery mostly being interested in DOM manipulation?
You can chain methods in C# just fine. For example, that is done with Linq all of the time.
To understand method chaining implementation in C#, see
Method-Chaining in C#
This is also sometimes referred to as a fluent interface.
The fundamental idea is that each method that participates in a chain returns this, so that other methods of the class can be called by referencing the return value of the previous call.
There is nothing technical preventing the core libraries from being rewritten to make more extensive use of method chaining. Practically, though, rewriting the core libraries would break all existing .NET applications.
Certainly one could write a library that provides a fluent interface to things in the core library. One thing that springs to mind is the handling of Streams and Readers in System.IO.
No there are several C# libraries that are written with similar "chaining". It's typically called Fluent APIs. One example is Fluent NHibernate, but there are many more as it's just a way of structuring your code. It's not a limitation of dynamic vs static languages
In C++ I would get the address of the function and overwrite the first few bytes to a jmp to my function, do some stuff, restore the original bytes, and call the original function.
Can I do something like this in C#?
The .NET Profiler API is the closest "Microsoft-approved" way of intercepting methods at runtime. As already mentioned, this is somewhat difficult to implement and I am not aware of a library that makes this easy to implement using purely managed code.
While researching options for this myself a few months ago, I stumbled on CLR Method Injection, which is an article with source code explaining how to intercept methods at runtime. I considered using this myself, and even had the sample project working, but ultimately concluded that I needed more than method interception and would need a different solution. However, this approach directly answers your question.
Lastly, what I ended up doing was developing Afterthought as an open source alternative to PostSharp, which runs as a post-compile step and allows you to modify existing methods to call other code, or replace the method implementations altogether. I am working right now on a new fluid syntax, which I will include a sample of now to provide an example to help you see how this AOP approach would meet your needs:
Methods
.Named("Sum")
.WithParams<int[]>()
.Before((T instance, ref int[] values)
=> { var s = new Stopwatch(); s.Start(); return s; })
.After((instance, stopwatch, values)
=> instance.Result = (int)stopwatch.ElapsedMilliseconds);
In this case while amending an existing type with a Sum method I am introducing code before and after the method to measure the execution time. After running Afterthought against the original compiled class, the resulting Sum method would have calls to these lambda expressions (the C# compiler just turns them into static methods) before and after the method body. I could have just as easily called Implement and replaced the entire method implementation.
I hope one of these approaches meets your needs. In my case, I went the AOP route because I wanted to do more than interception, such as implementing interfaces, adding new methods/properties, etc. I also wanted something that would not introduce dependencies at runtime or concerns about stability or performance in the runtime environment--compile-time processing is just safer and easier to test.
Do you want to hook at runtime or do you want to patch the binary?
To hook at runtime you can use the profiling api(relatively difficult):
http://msdn.microsoft.com/en-us/magazine/cc188743.aspx
To hook at compiletime you can use an IL rewriter, such as PostSharp.
The technique you're looking for is called AOP - Aspect Oriented Programming. You can find several frameworks for C# if you goggle a little.
Update: You can find plenty of links and info in this question: Built-in AOP in C# - is it on the way?
In Java we have used the javaagent argument and ASM (http://asm.ow2.org/) utilities to modify the byte code at run/load time in memory by the classloader . (aka Add a method call to a method in a class dynamically).
Once example of this is where you remove all calls to Log4j to speed up an application (http://surguy.net/articles/removing-log-messages.xml).
I’m trying to figure out how to do this same process on runtime with C# / .Net. I have seen that you can manipulate the CIL for .Net, but I haven’t found an example of this at runtime.
System.Reflection.Emit seems to be the closest .Net equitant where you can dynamically create classes, but is there a way to add to or override existing classes using this?
I have never used Mono.Cecil for generating dynamic code (it does make your life much easy if you want to instrument assemblies though).
In .Net if you want to generate code you can use System.CodeDom and System.Reflection.Emit. One particular useful class that enables you to inject methods dynamically is DynamicMethod.
Check out the newer features in .net 4, I think most of what your looking for is in the System.Dynamic namespace.
Check out this post on DuckTyping
It's been a while since I looked at it (I'm pretty much a Java bunny) but I think the Mono project had something called Cecil which did at least some of this.
This is more like a good practise question. I want to offer different generic libraries like Logging, caching etc. There are lots of third party libraries like MS enterprise library, log4Net, NCache etc for these.
I wanted to know if its a good practise to use these directly or create wrapper over each service and Use a DI to inject that service in the code.
regards
This is subjective, but also depends on the library.
For instance, log4net or NHibernate have strictly interface based API's. There is no need to wrap them. There are other libraries which will make your classes hard to test if you don't have any interfaces in between. There it might be advisable to write a clean interface.
It is sometimes good advise to let only a small part of the code access API's like for instance NHibernate or a GUI library. (Note: This is not wrapping, this is building abstraction layers.) On the other side, it does not make sense to reduce access to log4net calls, this will be used in the whole application.
log4net is probably a good example where wrapping is just overkill. Some people suffer of "wrappitis", which is an anti-pattern (sometimes referred to as "wrapping wool in cotton") and just produces more work. Log4net has such a simple API and is highly customizable, they made it better then your wrapper most probably will be.
You will find out that wrapping a library will not allow you to just exchange it with another product. Upgrading to newer versions will also not be easier, rather you need to update your wrapper for nothing.
If you want to be able to swap implementations of those concepts, creating a wrapper is the way to go.
For logging there already is something like that available Common.Logging.
Using wrapping interfaces does indeed make unit testing much easier, but what's equally important, it makes it possible to use mocks.
As an example, the PRISM framework for Silverlight and WPF defines an ILoggerFacade interface with a simple method named Log. Using this concept, here's how I define a mocked logger (using Moq) in my unit tests:
var loggerMock = new Mock<ILoggerFacade>(MockBehavior.Loose);
loggerMock.Setup(lg => lg.Log(It.IsAny<string>(), It.IsAny<Category>(), It.IsAny<Priority>()))
.Callback((string s, Category c, Priority p) => Debug.Write(string.Format("**** {0}", s)));
Later you can pass loggerMock.Object to the tested object via constructor or property, or configure a dependency injector that uses it.
It sounds like you are thinking of wrapping the logging implementation and then sharing with different teams. Based on that here are some pros and cons.
Advantages of Wrapping
Can abstract away interfaces and
dependencies from implementation.
This provides some measure of protection against breaking changes
in the implementation library.
Can
make standards enforcement easier and
align different project's
implementations.
Disadvantages of Wrapping
Additional development work.
Potential additional documentation
work (how to use new library).
More
likely to have bugs in the wrapping
code than mature library. (Deploying your bug fixes can be a big headache!)
Developers
need to learn new library (even if
very simple).
Can sometimes be
difficult to wrap an entire library
to avoid leaking implementation
interfaces. These types of wrapper
classes usually offer no value other
than obfuscation. e.g. MyDbCommand
class wraps some other DbCommand
class.
I've wrapped part of Enterprise Library before and I didn't think it added much value. I think you would be better off:
Documenting the best practices and usage
Providing a reference implementation
Verifying compliance (code reviews
etc.)
This is more of a subjective question but IMO it's a good thing to wrap any application/library specific usage into a service model design that has well thought out interfaces so you can easily use DI and later if you ever need to switch from say EntLib Data Application Block to NHibernate you don't need to re-architect you're whole application.
I generally create a "helper" or "service" class that can be called statically to wrapper common functionality of these libraries.
I don't know that there is a tremendous amount of risk in directly referencing/calling these, since they are definitely mature projects (at least EntLib and Log4Net), but having a wrapper isolates you from the confusion of version change, etc. and gives you more options in the future, at a fairly low cost.
I think it's better to use a wrapper, personally, simply because these are things you don't want to be running when your unit tests run (assuming you're unit testing also).
Yes if being able to replace the implementation is a requirement now or in a reasonable future.
No otherwise.
Defining the interface that your application will use for all logging/enterprising/... purposes is the core work here. Writing the wrapper is merely a way to make the compiler enforce use of this interface rather than the actual implementation.