jQuery Method Chaining vs. C#/VB Lack of Method Chaining - c#

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

Related

Why are extension methods used extensively in LINQ, despite the framework's guidelines?

The Extension Methods documentation says:
For a class library that you implemented, you shouldn't use extension
methods to avoid incrementing the version number of an assembly.
So why has the .NET team used them extensively in Enumerable and Queryable?
In search of a reason I checked out my copy of C# In Depth, where I came away with a feeling that extension methods are used because:
You can chain them together in a readable way
You can bring them in and out of scope
Is this correct or are the .NET team flying in the face of their own documentation? Are there other reasons that justify their use?
That's not the entire sentence. What is actually written is this:
For a class library that you implemented, you shouldn't use extension methods to avoid incrementing the version number of an assembly. If you want to add significant functionality to a library for which you own the source code, you should follow the standard .NET Framework guidelines for assembly versioning.
(emphasis added)
What this means is that you should avoid just adding extension methods to a class when you're adding large amounts of functionality, just for the sake of not incrementing the assembly version. If you're going to introduce large amounts of new functionality, you should really do it in a new version of that assembly.
It's because LINQ works on IEnumerable, not any specific implementation of a collection. If they were part of the definition of IEnumerable, you would have to implement your own methods, and it would needlessly bloat the interface. By putting LINQ into extension methods, you can implement IEnumerable on any class you create yourself, and the existing LINQ methods will work on it.

using attribute to read Method Parameters

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.

Is there a way to hook a managed function in C# like I would a unmanaged function in C++?

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?

Is it a good practice to create wrapper over 3rd party components like MS enterprise Library or Log4net?

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.

How to wrap a method via attributes?

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

Categories

Resources