Skip to content

Generics With Type Uknown At Compile Time

2010 February 18
by stefanoricciardi

The following is an example of a service containing both generic method calls and generic types.

public interface IContainer<T>
{
    IEnumerable<IProperty<T>> Properties { get; }
}

public interface IPropertyService
{
    IContainer<T> GetProperties<T>(string propertyCode);
}

Now suppose that you don’t know the actual type of the data until runtime (possibly because the type is retrieved from a DB or from some other service). You need a way to interact with these generics, and Reflection can help you here.

Let’s assume that you have managed to get the Type of the data that you are handling (such as string, decimal, double, etc…) and that you have a concrete implementation of the IPropertyService (perhaps through Dependency Injection).

Once you have that, you can invoke the GetProperty method in the following way:

Type type = // ... this is the actual runtime type
IPropertyService service = // ... this is an instance of the service

Type serviceType = typeof(IPropertyService);
MethodInfo getPropertiesInfo =
    serviceType.GetMethod("GetProperties", new Type[] { typeof(string) });

if (getPropertiesInfo == null)
{
    // Uh-oh.... has the interface changed after we wrote this? Throw an exception...
}

Type[] genericArguments = { type }; // we only have one generic argument (<t>)
MethodInfo getPropertiesMethodInfo =
    getPropertiesInfo.MakeGenericMethod(genericArguments);

// Finally invoke the method to search for a price
var propertiesContainer =
    getPropertiesMethodInfo.Invoke(service, new object[] { "price" });

As you can see are quite a few steps to be performed, but at the end, through reflection, you end up with a container filled with all the objects that you have required.

Now assume that you want to access to the single properties contained in the IContainer. You need some way to invoke the C# property Properties. defined on IContainer. Similarly to the MethodInfo class, System.Reflection has a PropertyInfo class that you can use to work with Properties.

The following solution, despite compiling fine, will not work at run-time:

PropertyInfo containerInfo = typeof(IContainer<>).GetProperty("Properties"); // WRONG!!!
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;

If you try to run this, you will be greeted by the following exception: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

After scratching my head for a while, I realized that I should have first created a generic type at run-time before retrieving the PropertyInfo:

Type containerType = typeof(IContainer<>).MakeGenericType(type);
PropertyInfo containerInfo = containerType.GetProperty("Properties");
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;

At this point I have a collection of IProperties which I can enumerate through. If needed, since the types in this collection are also generic, I need to repeat the process above until I reach a fundamental type (such as string, double, etc…).

kick it on DotNetKicks.com

Shout it

Top Podcasts For .NET Developers

2010 February 6
by stefanoricciardi

Why Should You Care About Podcasts

There are many ways to keep up to date to what’s going on in the software community. Blogs, books, magazines, conferences, discussion groups, mailing lists, you name it… So, should you care about podcasts?

If you are anything like most of us mere mortals, you’ve already come to realize that there are way too many things that you would like learn and only so many hours in a day. Podcasts allow you to squeeze some more “learning time” from an otherwise compressed schedule.

I especially love to listen to podcasts on my running sessions. On the other end, I have found that I don’t usually care for them while commuting to and from work: I need some time to relax listening to good music before and after a stressful day. Your mileage might vary.

The podcasts listed below are basically the only one which I am subscribed to on iTunes. I can’t keep up with all the shows, so I try to cherry pick from the themes that are closer to my day to day work, occasionally listening to topics I am not familiar with just to see what’s going on.

A few other podcasts did not make my selection, like Elegant Code or Stackoverflow: after listening to a few episodes I found that they simply were not my cup of tea.

I especially love shows which have a clear focus, the right amount of “small talk”, and where the host(s) have a good understaing of the subject matter. Again, YMMV.

read more…

See Your XML Docs As You Type With CR Documentor

2010 January 22
by stefanoricciardi

Introduction

Almost 10 years ago now I used to be a Java developer in Motorola. After a long hiatus in the embedded systems and a job change, I have come back to enterprise development, this time in .Net.

I remembered that in the good ol’ days it required 2 steps to see the final rendering of the XML documentation: firing javadoc (usually from within an ANT task) and the open up the content in a browser.

I was quite surprised to see that in the .Net area seeing the final output of the docs was not as straightforward as I hoped for. Yes, there was NDoc to parse the XML, but its development stopped around 2005 and it’s doesn’t support anything beyond C# 2.0. There’s also Sandcastle, but to make it work for me it has required a few downloads and a bit of tweaking here and there. And integrating it into my NAnt task had not been that easy either. But somehow in the end I have pulled that out.

Therefore I have been pleasantly surprised when I met CR Documentor, a little plug-in for visual studio that let’s you see your XML documentation as you write it. It’s almost like having a WYSIWYG editor, without having to launch Sandcastle, wait for the complete build, and open up the browser.

Installation

  • cr_documentor-logoRequirements:
    • Visual Studio 2005 or greater (I am pretty confident that you need at least a Professional version as opposed to Express). I am running it on Visual Studio Team System 2008, not sure whether it works also on 2010.
    • The DXCore plugin framework from DevExpress. Possibly the best (and only?) way to get it is to get through the excellent free CodeRush Xpress for C# and VB
  • Download the plugin: CR Documentor is hosted at Google Code at this link.
  • Copy the dll in your DX-Core plugin-folder (C:\Users\<username>\Documents\DevExpress\IDE Tools\Community\PlugIns)
  • Restart Visual Studio

Usage

  1. CR Documentor adds itself in the right click menu, close to the bottom. From the submenu, choose “Show CR_Documentor window”.CR_documentor-1
  2. A new window opens up in floating mode (I prefer to dock-it to the right side together with my solution explorer and luckily the plug-in remembers this choice every time I open the window after closing it and at startup).image
  3. Now every time your cursor is on an XML doc, you can see the preview in the Documentor window. See for example when I put the cursor on the XML doc of a class: I get a complete picture of the documentation for that class and its methods all in real time.
    image
  4. There are a few other features that I don’t use very often. All of them are accessible by the right-click content sensitive menu:

Configuration

Like all DXCore plugins, you can access to the configuration by pressing ALT+CTRL+SHIFT+O combination. I like to check all my options to Sandcastle because that’s the tool that I will be using to create the final XML documentation.

image

kick it on DotNetKicks.com

Shout it

Bookmark and Share

8 visitors online now
8 guests, 0 members
Max visitors today: 8 at 12:47 am CEST
This month: 8 at 08-01-2010 12:47 am CEST
This year: 40 at 05-03-2010 04:48 am CEST
All time: 40 at 05-03-2010 04:48 am CEST