Featured Post

IOC ModelBinder

I had an idea a couple of days ago, that I decided to play around with, and maybe collect opinions on. The ASP.NET MVC ModelBinder infrastructure is quite exhaustive, and allows you to perform almost any action when a something the developer wants to get data from the request into the domain/data/business...

Read More

Simple factory for open dynamic delegates

Posted by BernhardGlueck | Posted in .net development, VisualStudio, c# | Posted on 18-04-2010

0

During the course of my development adventures I came to a point where I needed to call instance methods dynamically based only on information that can be obtained through reflection. It is well known that MethodInfo.Invoke is quite slow, and so I decided to create and cache delegates based on the given MethodInfo on first use, and use those to invoke the method.

However it would be prohibitive to generate a delegate for every instance of an object, rather it would be nice to create a delegate per Method prototype and decide the instance to call it on during the final invocation.

A little known feature that allows us to achieve this, is the ability of the CLR to create so called “open” delegates. In the CLR a call to an instance method is quite similar to the call of a static one, except that the first parameter on the stack is the instance on which to call the method. Open Delegates allow us to create delegates that for an instance method take an additional first parameter for the instance to call the method on, thus neatly wrapping the above concept.

The feature is not common knowledge, basically because neither C# or VB offer the syntax to create such open delegates, one has to always use Delegate.CreateDelegate to create it dynamically.

The overload to use is mainly Delegate.CreateDelegate( Type delegateType,MethodInfo method,bool throwOnBindFailure ).
This is quite straightforward to use, a little complication stems from the fact that we need a delegate type to create the delegate instance. I decided to leverage the predefined Action<> and Func<> types for that, and bind the generic arguments to the parameter types of the method.

Here is my simple utility class that wraps the presented ideas.

Note that it does not support open generic methods and that it is limited to methods that have up to 16 parameters ( not that you should have methods that have more ).
To use just call the CreateOpenDelegate method with the MethodInfo that represents your instance method.
The returned delegate can then either be casted to an appropriate Action<> or Func<> or called via DynamicInvoke.
Regardless of the call method used, one has to pass in the instance to call the method on as the first parameter.

Here is the source code:

    public static class DelegateFactory
    {
        private static readonly Type[] actionTypes = new [] {
                                                                typeof(Action),
                                                                typeof(Action<>),
                                                                typeof(Action<,>),
                                                                typeof(Action<,,>),
                                                                typeof(Action<,,,>),
                                                                typeof(Action<,,,,>),
                                                                typeof(Action<,,,,,>),
                                                                typeof(Action<,,,,,,>),
                                                                typeof(Action<,,,,,,,>),
                                                                typeof(Action<,,,,,,,,>),
                                                                typeof(Action<,,,,,,,,,>),
                                                                typeof(Action<,,,,,,,,,,>),
                                                                typeof(Action<,,,,,,,,,,,>),
                                                                typeof(Action<,,,,,,,,,,,,>),
                                                                typeof(Action<,,,,,,,,,,,,,>),
                                                                typeof(Action<,,,,,,,,,,,,,,>),
                                                                typeof(Action<,,,,,,,,,,,,,,,>),
                                                            };

        private static readonly Type[] functionTypes = new [] {
                                                                typeof(Func<>),
                                                                typeof(Func<,>),
                                                                typeof(Func<,,>),
                                                                typeof(Func<,,,>),
                                                                typeof(Func<,,,,>),
                                                                typeof(Func<,,,,,>),
                                                                typeof(Func<,,,,,,>),
                                                                typeof(Func<,,,,,,,>),
                                                                typeof(Func<,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,,,,,,,>),
                                                                typeof(Func<,,,,,,,,,,,,,,,,>),
                                                            };

        public static Delegate CreateOpenDelegate( MethodInfo method )
        {
            Contract.Requires(method != null);

            var closedType = GetClosedDelegateType(method);

            return closedType != null ?
                     Delegate.CreateDelegate(closedType, method, true)
                     : null;
        }

        private static Type GetClosedDelegateType( MethodInfo method )
        {
            Contract.Requires(method != null);

            var openType = GetOpenDelegateType(method);

            if (openType != null)
            {
                var parameterTypes =
                    new[] {method.DeclaringType}.Union(method.GetParameters().Select(p => p.ParameterType));

                if (method.ReturnType != typeof (void))
                {
                    parameterTypes = parameterTypes.Union(new[] {method.ReturnType});
                }

                return openType.MakeGenericType(parameterTypes.ToArray());
            }

            return null;
        }

        private static Type GetOpenDelegateType( MethodInfo method )
        {
            Contract.Requires( method != null );

            var parameterCount = method.GetParameters().Length + 1;

            if (parameterCount < functionTypes.Length && parameterCount < actionTypes.Length)
            {

                return method.ReturnType != typeof (void)
                           ? functionTypes[parameterCount]
                           : actionTypes[parameterCount];
            }

            return null;
        }
    }
  • Share/Bookmark

Visual Studio 2010 Beta2 Impressions

Posted by BernhardGlueck | Posted in .net development, VisualStudio, c# | Posted on 26-10-2009

Tags: , , ,

0

Beta 2 of Visual Studio 2010 has arrived and is available for download for just about anyone to grab.

I’ve played around with this release for a week now ( Msdn release was a few days prior to public availability )
and so far my feelings are best described in romantic terms: Love at first sight.

There are so many great features/improvements that I just don’t know where to begin, but I’ll try anyway.

For the first time since Visual Studio 6 back in the 90s, online help is fast again. Microsoft rewrote the complete help
system and based it around a small local Web server that serves Javascript enriched help content.
Hovering on some identifier, pressing F1 and waiting for the new context sensitve help to pop up takes about 0.5 seconds
on my local machine.

TFS Basic is great. I stayed clear of TeamFoundation server for the last releases since my initial evaluation turned out that it did
not offer much over other tools, but required insane ammounts of hardware and installation/administration effort that just were
not easily recouped by it’s functionality.

TFS Basic installs easy, fast ( 20 minutes for me without any error whatsoever ) and runs even on client OS editions if you’re into that.

UML Modelling support has finally arrived, of course it’s the first release, and code generation support seems not to be on the agenda, but
for some fast and simple diagramming it’s certainly enough.

The C++ compiler supports a few things from the upcoming revised standard, like the auto keyword, lambda functions and nullptr.
TR1 support has also matured and so we can write even better standard compliant code right now.
Performance of C++ intellisense seems also much better, especially with larger codebases.
Also C++ finally uses Msbuild for it’s build system as well as project files. So codebases that mix C++ with C# are now much easier to handle
in build environments.

For C# we have of course the new dynamic dispatch features, as well as optional and named parameters, and better co/contravariance support for generics.
I still don’t like dynamic dispatch support, simply because I think it will be used for all the wrong reasons, and because it throws out a lot of the investment
in static source code analysis technology, and proofing program correctness.

On the runtime side of things, of course we have additions to WCF/WPF a completly rewritten Workflow Foundation, and many other small things like
a few conveniance methods ( string.IsNullOrWhiteSpace ).

The Task Parallel library is a godsend, but I am still in fear of it’s usage patterns. I see a lot of developers who are not experienced in multithreading
just use things like Parallel.ForEach or PLINQ because it’s so damn easy thereby ignoring the concurrency issues, producing code that will just fail
at unpredictable times.
At least we have some by default threadsafe collections now, but the performance implications of those must not be overlooked, collections are rarely the
right place for some last effort “catch all” synchronization.

Things like native support for Memory Mapped files, the inclusion of Code Contracts which were previously available as an addon, as well as conveniance
data structures like tuples or sets round off the framework itself.

The client GC can now do parallel garbage collections under certain circumstances ( during full collections a certain number
of allocations can be still be done while the collection is running ).

The server GC does not support this apparently because of lack of development time, which is really not nice, since especially there it would have resolved certain issues in long running applications
that have bitten me in the past.

Last but not least ADO.NET Entity Framework is in it’s second release, supports forward engineering finally, and generally seems much more mature now, time to take it for a spin in the next few days.

All in all a great release, and the nice WPF UI of Visual Studio just make working that little extra spicy, so in conclusion: I really like it !

  • Share/Bookmark

Visual Studio Extensions

Posted by BernhardGlueck | Posted in .net development, VisualStudio, c# | Posted on 20-06-2009

Tags: , ,

0

As a friend asked me today, what kind of tools I use for my day to day .NET development work in addition
to Visual Studio, I thought I’ll whip up a list, and include some not so common tools as well.

So here it is:

Resharper: Not much to say, if you still write C# code without it, you can’t be helped.

Regionerate: Code layout/reformatting on steroids. A time saver if you have to reformat a lot of inherited code.

StyleCop: Code style analysis, based on the .NET framework design guidelines by Microsoft. There is also a plugin for Resharper available that executes the analysis in the background while you work. ( http://www.codeplex.com/StyleCopForReSharper )

Sandcastle for Visual Studio: Allows you to create documentation projects in a solution and automatically build
Msdn style documentation based on xml documentation comments, and manually edited content.

FxCop: Static code analysis. This is of course included in Visual Studio, but I am often surprised how little people make use of it, so I thought I’d mention it anyway.

RockScoller: Addin that provides you with an overview of the source file you’re working on. Great for large files.

Pex: Automated white box testing for your code. Allows you to generate unit test code by executing your code and trying to find the weak spots.

Chess: Automated testing of multithreaded code, to detect interleave patterns that cause deadlocks/livelocks or race conditions in your code. This is a godsend, I can’t reiterate enough how great this tool is.

InteliShade: HLSL syntax highlighting and intellisense support. For the graphics developers among us.

Code Contracts: Code contract support, which allows you to add precondition, postcondition and invariant checking code, enforce it at runtime, and find weak spots through static analysis.

Pinvoke.Net: Easy lookup of P/Invoke signatures for those pesky Win32 API imports ( and a lot of others ).

PostBuild.Net: Code obfuscation, compression and virtualization. Allows you to deploy your .NET client applications to systems without them even needing .NET installed.

PostSharp Great tool for post build code modification with included AOP support and msbuild integration. Use it for post processing your assemblies, injecting code, or modifying it.

Visual WebGui: Build AJAX or Silverlight based RIA applications with a development model similar to Windows Forms.

Script#: Write code in C# with a special class library, and have it automatically translated to client side JavaScript code at build time. Great if you don’t like the JavaScript syntax or object model.

VisualSVN: Work with Subversion from Visual Studio, based on the familiar TortoiseSVN base platform. Beats any other integration hands down.

Of course I left out some others, so if you have any ideas of tools to add, leave a comment.

  • Share/Bookmark