Auto-gen a URI string based on a method call

By | November 21, 2013

There are some navigational paradigms out there that use navigation strings to hit, in turn, methods within your own codebase. It’s a sound idea, but generating those URIs as strings which you in turn use in a Navigate() call can be problematic. What happens when you add a parameter to the method? Rearrange the parameters? And what if you could get intellisense when you wanted to generate those URIs?

Look no further than that awesomeness Microsoft provides us .Net developers than the beautiful acronym we all love: LINQ. More specifically, the Expression Tree objects that we got with LINQ.

I’ve used a pretty handy class for a while now that allow me to use hard references to properties when I am implementing/calling INotifyPropertyChanged objects. Basically, it turns

OnNotifyPropertyChanged("MyProperty");

in to

OnNotifyPropertyChanged(()=>this.MyProperty);

which, as you can guess, makes sure that I never misspell the property and also never use one that’s not available in my code.

So, I took this idea another step and dissected the handy reusable file I’d had in so many of my Windows Phone projects to accomplish this to see if I could make it fit the bill of a NavigationURI generator.

Here’s what I came up with:

class MethodProcessor
{
    public static string CreateStringForCall(Expression<action> methodCall)
    {
        var exp = methodCall.Body as MethodCallExpression;
        var retVal = string.Concat(exp.Method.Name, "/",
            string.Join("/", exp.Arguments.Cast<ConstantExpression>().Select(a => a.Value.ToString())));
        return retVal;
    }
}

which gets used like this:

public class SubClass
{
    public void MyMethod(string name, int value)
    {

    }
}

static void Main(string[] args)
{
    Console.WriteLine(
        MethodProcessor.CreateStringForCall<SubClass>(
        (o)=>o.MyMethod("theName",4)));
}

and gives me this:

image

Pretty slick! Feel free to dissect the expression tree magic going on here and augment it to your liking!

Play with it in .Net Fiddle below!