tsJensen

A quest for software excellence...

Try Catch Nothing Worst Code Ever

Tracking down a problem in a commercial .NET library today, I found this little gem (identifying code in the try removed):

try
{
   //any code that could fail in any way here
}
catch (Exception)
{
}

Not only should this construct not compile, any attempt to do so should cause your computer to explode.

Extend IEnumerable<T> with ForEach<T> and Once<T> Methods

A few days ago, a fellow programmer asked me a common question. How do you print odd numbers between one integer value and another. It's a common question and the quickest solution that came to mind is the common for loop with a simple if and the mod operator.

Later I began toying with the question and in combination wanted to experiment with an alternative to the limited ForEach extension method on IList<T>. What you see below is the result of a little tinkering and tweaking along with some fluent goodness.

I considered naming my custom extesion method ForEach but decided to use something different to remind myself that it is not your grandfather's ForEach extension method. So I named it ForEvery and in the middle of playing with that, I ended up creating the Once extension method on IEnumerable<T>.

class Program
{
   static void Main(string[] args)
   {
      PrintOdds(1, 100);
      Console.ReadLine();
   }

   static void PrintOdds(int x, int y)
   {
      Console.WriteLine("Odds with traditional for and if");
      for (int i = x; i <= y; i++)
      {
         if (i % 2 != 0) Console.Write("{0}, ", i);
      }

      Console.WriteLine();
      Console.WriteLine();
      Console.WriteLine("Odds with ToList and ForEach with if");
      Enumerable.Range(x, y - x + 1)
         .ToList()
         .ForEach(i =>
         {
            if (i % 2 != 0) Console.Write("{0}, ", i);
         });

      Console.WriteLine();
      Console.WriteLine();
      Console.WriteLine("Odds with Where then ToList and ForEach");

      Enumerable.Range(x, y - x + 1).Where(n => n % 2 != 0)
         .ToList().ForEach(i =>
         {
            Console.Write("{0}, ", i);
         });

      Console.WriteLine();
      Console.WriteLine();
      Console.WriteLine("Odds with Where and custom ForEach");

      Enumerable.Range(x, y - x + 1)
         .Where(n => n % 2 != 0)
         .ForEach(i =>
         {
            Console.Write("{0}, ", i);
         });

      Console.WriteLine();
      Console.WriteLine();
      Console.WriteLine("Odds with custom ForEvery fluent");

      Enumerable.Range(x, y - x + 1)
         .ForEvery(n => n % 2 != 0, i => 
         { 
            Console.Write("{0}, ", i);
         })
         .Once(n => n.Count() > 99, i =>
         {
            Console.WriteLine();
            Console.WriteLine("Once fluent");
            Console.WriteLine();
            Console.WriteLine("Evens with ForEvery fluent from {0} to {1}", i.Min(), i.Max());
         })
         .ForEvery(n => n % 2 == 0, i =>
         {
            Console.Write("{0}, ", i);
         });
   }
}

public static class EnumerableExtensions
{
   public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
   {
      foreach (var item in collection)
      {
         action(item);
      }
   }

   public static IEnumerable<T> Once<T>(this IEnumerable<T> collection, 
      Func<IEnumerable<T>, bool> predicate, Action<IEnumerable<T>> action)
   {
      if (predicate(collection)) action(collection);
      return collection;
   }

   public static IEnumerable<T> ForEvery<T>(this IEnumerable<T> collection, 
      Func<T, bool> predicate, Action<T> action)
   {
      foreach (var item in collection)
      {
         if (predicate(item)) action(item);
      }
      return collection;
   }
}

Drop the code into a console app and run it. If you like these little extensions, I'd love to hear from you.

Deep Null Coalescing in C# with Dis.OrDat<T>

The other day, a friend and I were reviewing some code like this and decided we deeply disliked it.

// var line1 = person.Address.Lines.Line1 ?? string.Empty;
// throws NullReferenceException: 
//    {"Object reference not set to an instance of an object."}

// The ugly alternative

var line1 = person.Address == null
        ? "n/a"
        : person.Address.Lines == null
        ? "n/a"
        : person.Address.Lines.Line1;

If you have ever written code like that or even worse, with the if (obj != null) statements, then you can certainly relate to our lack of love for the constructs required to avoid the dratted NullReferenceException.

So we experimented with a solution and nearly got there. Tonight I finished that up and the new Dis class is born with the OrDat<T> method so you can now write this instead.

var line2 = Dis.OrDat<string>(() => person.Address.Lines.Line2, "n/a");

Here’s the full example and if you’re patient enough to scroll down, you’ll also find the full implementation of the Dis.OrDat class and method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DeepNullCoalescence
{
  class Program
  {
    static void Main(string[] args)
    {
      var person = new Person();

      // var line1 = person.Address.Lines.Line1 ?? string.Empty;
      // throws NullReferenceException: 
      //    {"Object reference not set to an instance of an object."}
      
      // The ugly alternative
      var line1 = person.Address == null
              ? "n/a"
              : person.Address.Lines == null
              ? "n/a"
              : person.Address.Lines.Line1;

      // A cooler alternative
      var line2 = Dis.OrDat<string>(() => person.Address.Lines.Line2, "n/a");

      Console.WriteLine(line1);
      Console.WriteLine(line2);
      Console.ReadLine();
    }
  }

  internal class Person
  {
    public Address Address { get; set; }
  }

  internal class Address
  {
    public AddressLines Lines { get; set; }
    public string State { get; set; }
  }

  internal class AddressLines
  {
    public string Line1 { get; set; }
    public string Line2 { get; set; }
  }
}

And for the patient reader, here is the actual magic.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace DeepNullCoalescence
{
  public static class Dis
  {
    public static T OrDat<T>(Expression<Func<T>> expr, T dat)
    {
      try
      {
        var func = expr.Compile();
        var result = func.Invoke();
        return result ?? dat; //now we can coalesce
      }
      catch (NullReferenceException)
      {
        return dat;
      }
    }
  }
}

.NET Task Factory and Dangers of Iteration

I had a simple small array of objects. I wanted to send each of them into a method that would fire off and manage a long running process on each of them in a new thread pool thread.

So I remebered the coolness of the new .NET 4.0 Task and it's attendant Factory. Seemed simple enough but I quickly learned a lesson I should have already known.

I've illustrated in code my first two failures and the loop that finally got it right. Let me know what you think. Undoubtedly there is even a better way.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TaskFactoryExample
{
  public class ServerManager
  {
    IServerLib[] serverLibs;
    List<Task> taskList = new List<Task>();
    List<CancellationTokenSource> cancelTokens = new List<CancellationTokenSource>();

    public ServerManager(IServerLib[] servers)
    {
      serverLibs = servers;
    }

    // FIRST FAIL: only the last lib in the iteration gets sent to all ManageStart calls
    internal void Start_FirstFailed(string[] args)
    {
      foreach (var lib in serverLibs)
      {
        var tokenSource = new CancellationTokenSource();
        taskList.Add(Task.Factory.StartNew(() => { ManageStart(lib, args); }, tokenSource.Token));
        cancelTokens.Add(tokenSource);
      }
    }

    // SECOND FAIL: i is incremented finally to serverLibs.Length before ManageStart is called
	// resulting in an index out of range exception
    internal void Start_SecondFailed(string[] args)
    {
      for (int i = 0; i < serverLibs.Length; i++)
      {
        var tokenSource = new CancellationTokenSource();
        taskList.Add(Task.Factory.StartNew(() => { ManageStart(serverLibs[i], args); }, tokenSource.Token));
        cancelTokens.Add(tokenSource);
      }
    }

    // finally got it right - get a local reference to the item in the array so ManageStart 
    // is fed the correct serverLib object
    internal void Start(string[] args)
    {
      for (int i = 0; i < serverLibs.Length; i++ )
      {
        var serverLib = serverLibs[i];
        var tokenSource = new CancellationTokenSource();
        taskList.Add(Task.Factory.StartNew(() => { ManageStart(serverLib, args); }, tokenSource.Token));
        cancelTokens.Add(tokenSource);
      }
    }

    private void ManageStart(IServerLib lib, string[] args)
    {
      try
      {
        //code redacted for brevity
        //start long running or ongoing process with lib on threadpool thread
        lib.Start();
      }
      catch (Exception e)
      {
        //TODO: log general exception catcher
        throw; //leave in for testing
      }
    }

    internal void Stop()
    {
      try
      {
        foreach (var lib in serverLibs) lib.Stop();
        foreach (var tokenSource in cancelTokens) tokenSource.Cancel();
        foreach (var t in taskList) if (t.IsCompleted) t.Dispose();
      }
      catch (Exception e)
      {
        //TODO: log general exception catcher
        throw; //leave in for testing
      }
    }
  }
}

DomainAspects: Aspect Oriented Programming Infrastructure for Domain Driven Design

The DomainAspects library introduced here may be the birth of an open source project that could add real value to the .NET stack. On the other hand, it could be just a small exploration of Castle Windsor's aspect oriented programming construct called the Interceptor. Time will tell but I felt it would be worth sharing the bits at this early stage to gauge interest and get some preliminary feedback.

DomainAspects is an aspect oriented infrastructure library for domain driven .NET projects. It uses Castle Windsor's Interceptor to provide configurable aspect oriented audit logging, authorization and exception handling to domain operations. Service classes in the domain can take advantage of DomainAspects using a custom attribute, avoiding the clutter of infrastructure code in the business logic.

There are many variations for the definitions of aspect oriented programming and domain driven design. I'll let Wikipedia contributors sort out the "pure" definitions. I'm not a purist or self-declared expert on either of these topics. But for the record, I'll share my definitions of these two as succinctly as I can.

Aspect Oriented Programming - The separation of cross cutting concerns, such as logging, authorization, and exception handling, from the business logic core of the application. AOP can allow the business application developer to focus on implementing business requirements without worrying about consistently applying and debugging repetitive infrastructure code throughout the application.

Domain Driven Design - An approach to writing applications where the domain is the core of the application. The domain defines the data, data persistence and business operations available to a user interface or service host of which it has no knowledge. DDD seeks to separate the mechanical concerns of the application host from the core business operations and data in order to maximize the potential for application developer specialization and code re-use. Common constructs seen in the domain are entities, services and repositories with a dependency on a persistence framework or data access layer.

DomainAspects brings AOP to DDD to make it easier to write the domain layer. Now I can write my acceptance criteria driven tests for a business operation and then implement that business operation with pure business logic while one or two simple attributes assure the consistent execution of infrastructure code every time that method is called. Here's a simplistic example:

[InterceptOperation, Authorize(RolesRule = "!Guest")]
public string GetUserPhoneNumber(int userId)
{
  var userRepository = new UserRepository();
  return userRepository.GetUser(userId).PhoneNumber;
}

And using that operation is just as easy. Here's the code to call that operation using the DomainProxy (normal UI exception handling not shown):

private void ShowPhoneButton_Clicked(object sender, EventArgs e)
{
  using (var proxy = new DomainProxy<IUserService>())
  {
    var phone = proxy.Service.GetUserPhoneNumber(userId);
    this.txtPhone.Text = phone;
  }
}

The client or host code uses the DomainProxy wrapper to get an IDisposable instance of a Castle Windsor container instance of the service class which is in turn wrapped by the Interceptor proxy. Here’s a look at these three important classes:

da_class_1

Under the covers, three specific DomainAspects infrastructure things are happening via the auditor and authorizer objects injected into the interceptor along with the principal provider object injected into the authorizer object. Here’s a look at the classes in question.

da_class_2

The first two things that happen occur before the proxy proceeds with calling the business operation. The third only happens if the business operation code throws an exception.

  1. The OperationAuditor's LogOperationInvoked method is called allowing the invokation to be logged by your implementation of IOperationAuditor.
  2. The OperationAuthorizer's Authorize method is called where the authorize attribute's rule is enforced. In this case, the logged in user cannot be in the role "Guest" or an exception will be thrown. Note that the IPrincipal used to determine this is provided by the injected PrincipalProvider implementation.
  3. The OperationAuditor's LogOperationException method is called if the business operation throws an exception.

In future posts, I'll write about each of these parts and how they work, but for now, download the code and let me know what you think. You will need to download the Castle Windsor library and correct the references in the solution depending on where you have installed the Castle project library.

Download the code here: DomainAspects.zip (29.39 KB)

Target Framework and Platform Target: Get Your .NET Projects on the Same Page

It builds and runs fine on your local machine but when you deploy it to the server, all kinds of problems arise. Before you spent countless hours chasing ghosts, make sure you have your .NET projects on the same page, namely building for the right .NET Framework and targeting the right platform.

Open your project properties bag and try these first and then narrow it down. First, make sure your target frameworks for all your projects are in synch.

targetframework

Then make sure you give yourself as much latitude as you can by setting your platform target to Any CPU:

anycpu

Once you know your project and its dependencies are all on the same page and you still have problems on your deployment target, then go ahead and spend countless hours chasing ghosts.

ASP.NET MVC Custom Authorize Attribute with Roles Parser

Do you ever get frustrated with the limited nature of the ASP.NET MVC AuthorizeAttribute class’s limited Roles property which provides only a simple comma delimited list and creates a simple OR list? Would you like to be able to exclude specific roles or have a more complex expression such as:

!Guest & ((Admin | Supervisor) | (Lead & Weekend Supervisor))

Well, now you can. All thanks to the random convergence of great minds! (Or perhaps the obsessions of two code monkeys who have no life. You decide.)

While working on a project for a future blog post, I discussed the code with Nick Muhonen of Useable Concepts and MSDN author who offered to write a parser for an authorization strategy in the project that uses attributes similar to the ASP.NET MVC AuthorizeAttribute class.

Nick showed me the parser yesterday and after I agreed to say that I liked the code, he sent it to me with his blessing to use in my blog post project I’ve been working on. As I began to work the code into my project, I realized that this code deserved its own post as a descendant of the real ASP.NET MVC AuthorizeAttribute class for general use in the ASP.NET MVC world. I’m still planning to use the same parser for my future post, but here it is for your general use in your ASP.NET MVC projects.

The power starts in the return value of the RoleParser’s Parse method, the IRule:

public interface IRule
{
  bool Evaluate(Func<string, bool> matcher);
  string ShowRule(int pad);
}

Here’s the simple, but powerful SuperAuthorizeAttribute class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using SuperMvc.RoleRules;

namespace SuperMvc
{
  public class SuperAuthorizeAttribute : AuthorizeAttribute
  {
    private string _superRoles;
    private IRule _superRule;

    public string SuperRoles
    {
      get
      {
        return _superRoles ?? String.Empty;
      }
      set
      {
        _superRoles = value;
        if (!string.IsNullOrWhiteSpace(_superRoles))
        {
          RoleParser parser = new RoleParser();
          _superRule = parser.Parse(_superRoles);
        }
      }
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      base.OnAuthorization(filterContext);
      if (_superRule != null)
      {
        var result = _superRule.Evaluate(role => filterContext.HttpContext.User.IsInRole(role));
        if (!result)
        {
          filterContext.Result = new HttpUnauthorizedResult();
        }
      }
    }
  }
}

You’ll note that the setter on SuperRoles creates a parser instance and generates an IRule for later use in the OnAuthorization override. This allows us to parse once and run many times, making the evaluation even faster.

I’m not going to dive into how the parser works. I’ll let Nick blog about that. The great thing is that it does work and it’s very fast. Here’s how it’s put to use. First a look at the controller code on which we test it and a peek at one or two of the test methods. The HomeController has been modified with some test actions:

//partial listing

public class HomeController : Controller
{
  [SuperAuthorize(SuperRoles = "!Guest")]
  public ActionResult AboutTestOne()
  {
    return RedirectToAction("About");
  }

  [SuperAuthorize(SuperRoles = "Admin & Local Office | Local Office Admin")]
  public ActionResult AboutTestFive()
  {
    return RedirectToAction("About");
  }

  [SuperAuthorize(SuperRoles = "!Guest & !(SuperUser | DaemonUser) & ((Admin & Local Office | Local Office Admin) & !User)")]
  public ActionResult AboutCrazyTwo()
  {
    return RedirectToAction("About");
  }

  public ActionResult About()
  {
    return View();
  }
}

And here’s the tests, including some crucial initialization logic, that allows us to verify the attribute works.

[TestClass]
public class HomeControllerTest
{
  [TestInitialize]
  public void Initialize()
  {
    string[] roles =
      {
         "Admin",
         "User",
         "Local Office"
      };
    HttpContextHelper.SetCurrentContext(new FakePrincipal("Fake", "testuser", true, roles));
  }

  //[SuperAuthorize(SuperRoles = "!Guest")]
  //public ActionResult AboutTestOne()
  [TestMethod]
  public void AboutTestOne()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<RedirectToRouteResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutTestOne");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  //[SuperAuthorize(SuperRoles = "Admin & Local Office | Local Office Admin")]
  //public ActionResult AboutTestFive()
  [TestMethod]
  public void AboutTestFive()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<RedirectToRouteResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutTestFive");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  //[SuperAuthorize(SuperRoles = "!Guest & !(SuperUser | DaemonUser) & ((Admin & Local Office | Local Office Admin) & !User)")]
  //public ActionResult AboutCrazyTwo()
  [TestMethod]
  public void AboutCrazyTwo()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<HttpUnauthorizedResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutCrazyTwo");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  private FakeControllerActionInvoker<TExpectedResult> GetInvoker<TExpectedResult>(out ControllerContext context) where TExpectedResult : ActionResult
  {
    HomeController controller = new HomeController();
    var httpContext = new HttpContextWrapper(HttpContext.Current);
    context = new ControllerContext(httpContext, new RouteData(), controller);
    controller.ControllerContext = context;
    var invoker = new FakeControllerActionInvoker<TExpectedResult>();
    return invoker;
  }
}

All you have to do is download the code and plug in the SuperMvc project into your ASP.NET MVC web project and you too can have the power of parsed roles at your authorization attribute finger tips. Let me know if you like it or find an even better way to accomplish the same things.

SuperMvc.zip (281.93 KB)

Generic Asynchronous Wrapper for .NET

Recently I extended a previous blog post and published it on Code Project under the title Generic WCF Service Host and Client. An astute reader asked about calling a service method asynchronously, something I had not given much thought.

I decided that I wanted a way to support asynchronous calls on the generic WCF client without having to modify my service contract (interface) or implementation class libraries. I also wanted a way to do asynchronous calls with as little client code as possible, which meant support for a simple event based solution.

So I went to work experimenting. If you want the WCF version of the solution, visit the Code Project article and you can get the updated code there just as soon as I get an update published.

In this post, I'll present a more generalized version of the solution I created. The GenericAsyncWrapper<T> class is the heart of the solution. Take any instance of T (any class) and GenericAsyncWrapper<T> puts an event based asynchronous wrapper that allows you to call any method on the instance asynchronously.

I'm not going to explain how standard delegates are used to make asynchronous calls. If you want to brush up on the basics, check out Microsoft's How to call a Visual C# method asynchronously along with thousands of other online resources. I will show some examples of using standard generic delegates to do the asynchronous calls to compare with the use of the generic wrapper's event model.

Here's my test class. It does nothing, as you can see, but it does allow me to test my wrapper.

internal class MyTestClass
{
  public void DoNothingNoParams()
  {
    Console.WriteLine("MyTestClass.DoNothingNoParams called on thread: {0}", 
      Thread.CurrentThread.ManagedThreadId);
  }

  public string DoSomething(string input)
  {
    Console.WriteLine("MyTestClass.DoSomething called on thread: {0}", 
      Thread.CurrentThread.ManagedThreadId);
    return "Output of DoSomething with " + input + " as input.";
  }
}

And here's the test code. Just a simple console app that first shows the test class being called directly, then using standard generic delegates and finally using the wrapper. One advantage you may note is that with the wrapper, you also get all your original input params back.

class Program
{
  static void Main(string[] args)
  {
    Console.WriteLine("Main called on thread: {0}", Thread.CurrentThread.ManagedThreadId);
    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++");
    Console.WriteLine("synchronous calls");
    var mytest = new MyTestClass();
    mytest.DoNothingNoParams();
    string output = mytest.DoSomething("my name is Tyler");
    Console.WriteLine(output);

    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++");
    Console.WriteLine("Action<> and Func<> delgate calls");
    Action action = new Action(mytest.DoNothingNoParams);
    action.BeginInvoke(new AsyncCallback(ActionCallback), "test1");

    Func<string, string> func = new Func<string, string>(mytest.DoSomething);
    func.BeginInvoke("my name is Arnold", new AsyncCallback(FuncTTCallback), "test2");

    Thread.Sleep(1000);

    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++");
    Console.WriteLine("asynchronous wrapper calls");
    var wrapper = new GenericAsyncWrapper<MyTestClass>(mytest);
    wrapper.AsyncCompleted += new EventHandler<GenericAsyncWrapperCompletedEventArgs>(wrapper_AsyncCompleted);
    wrapper.AsyncInvoke("DoSomething", "test2", "my name is Bob");
    wrapper.AsyncInvoke("DoNothingNoParams", "test1", null);

    Console.ReadLine();
  }

  static void FuncTTCallback(IAsyncResult result)
  {
    Console.WriteLine("FuncTTCallback called on thread: {0}", Thread.CurrentThread.ManagedThreadId);
    Thread.Sleep(250);
    Func<object, object> deleg = ((AsyncResult)result).AsyncDelegate as Func<object, object>;
    if (deleg != null)
    {
      object returnValue = deleg.EndInvoke(result);
      Console.WriteLine("FuncTTCallback return value: {0}", returnValue);
    }
  }

  static void ActionCallback(IAsyncResult result)
  {
    Console.WriteLine("ActionCallback called on thread: {0}", Thread.CurrentThread.ManagedThreadId);
    Thread.Sleep(250);
    Action deleg = ((AsyncResult)result).AsyncDelegate as Action;
    if (deleg != null)
    {
      deleg.EndInvoke(result);
    }
  }

  static void wrapper_AsyncCompleted(object sender, GenericAsyncWrapperCompletedEventArgs e)
  {
    Console.WriteLine("wrapper_AsyncCompleted called on thread: {0}", Thread.CurrentThread.ManagedThreadId);
    if (e.Error == null)
    {
      Console.WriteLine("methodName: {0}, userState: {1}, result: {2}", 
        e.MethodName, e.UserState, e.Result);
      if (e.InValues != null)
      {
        for (int i = 0; i < e.InValues.Length; i++)
        {
          Console.WriteLine("   value[{0}] = {1}", i, e.InValues[i]);
        }
      }
    }
    else
    {
      Console.WriteLine(e.Error.ToString());
    }
  }
}

Now here's the real magic. The GenericAsyncWrapper<T> class and its attendant event args class.

public class GenericAsyncWrapper<T> where T : class
{
  private T _instance;

  public GenericAsyncWrapper(T instance)
  {
    if (instance == null) throw new NullReferenceException("instance cannot be null");
    _instance = instance;
  }

  public T Instance { get { return _instance; } }

  public event EventHandler<GenericAsyncWrapperCompletedEventArgs> AsyncCompleted;

  public void AsyncInvoke(string methodName, object userState, params object[] inValues)
  {
    if (string.IsNullOrEmpty(methodName)) throw new NullReferenceException("methodName cannot be null");
    MethodInfo mi = this.Instance.GetType().GetMethod(methodName);
    if (null != mi)
    {
      Func<MethodInfo, object[], object> func = new Func<MethodInfo, object[], object>(this.ExecuteAsyncMethod);
      func.BeginInvoke(mi, inValues, new AsyncCallback(this.FuncCallback), 
        new GenericAsyncState() { UserState = userState, MethodName = methodName, InValues = inValues });
    }
    else
      throw new TargetException(string.Format("methodName {0} not found on instance", methodName));
  }

  private object ExecuteAsyncMethod(MethodInfo mi, object[] inValues)
  {
    return mi.Invoke(this.Instance, inValues);
  }

  private void FuncCallback(IAsyncResult result)
  {
    var deleg = (Func<MethodInfo, object[], object>)((AsyncResult)result).AsyncDelegate;
    var state = result.AsyncState as GenericAsyncState;
    if (null != deleg)
    {
      Exception error = null;
      object retval = null;
      try
      {
        retval = deleg.EndInvoke(result);
      }
      catch (Exception e)
      {
        error = e;
      }
      object userState = state == null ? null : state.UserState;
      string methodName = state == null ? (string)null : state.MethodName;
      object[] inValues = state == null ? null : state.InValues;
      GenericAsyncWrapperCompletedEventArgs args = new GenericAsyncWrapperCompletedEventArgs(retval, error, methodName, userState, inValues);
      if (this.AsyncCompleted != null)
        this.AsyncCompleted(this, args);
    }
  }

  private class GenericAsyncState
  {
    public object UserState { get; set; }
    public string MethodName { get; set; }
    public object[] InValues { get; set; }
  }
}

public class GenericAsyncWrapperCompletedEventArgs : EventArgs
{
  public GenericAsyncWrapperCompletedEventArgs(object result, Exception error, string methodName, object userState, object[] inValues)
  {
    this.Result = result;
    this.Error = error;
    this.MethodName = methodName;
    this.UserState = userState;
    this.InValues = inValues;
  }
  public object Result { get; private set; }
  public Exception Error { get; private set; }
  public string MethodName { get; private set; }
  public object UserState { get; private set; }
  public object[] InValues { get; private set; }
}

You can download the code here GenericUtils.zip (7.33 KB). If you find it useful, I'd love to hear from you. If you think this was a total waste of time, turn the TV back on.