Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Advertisements
Posted in Uncategorized | 1 Comment

Dynamic Proxy (or Getting Crazy with Dynamics and Expressions)

If you’ve read my earlier posts you’ll see I have a somewhat childish fascination (crush if you will) with the .Net Expressions and dynamics API’s. I think there is limitless potential with these two platforms and in this post I will demonstrate the two working together by creating a small interception “framework” built on a dynamic proxy object provider…

My goal is to create a class deriving from DynamicObject. When operations are executed against an object of type DyanamicObject, there is opportunity to intercept the call and do something meaningful; here I am going to just forward the call to the target object. What is this target object? It’s going to be a type fed to the generic class deriving from DynamicObject.

So the “real” object (the interception target) is going to be simple:

image

Ignore the attributes for now…just take note there is nothing special about this class. No class attributes, no interfaces…just a POCO with a property and two methods that do rather boring things.

The interception “framework” is a single class.

public delegate void BeforeSetDelegate(string name, object value);

   /// <summary>
   /// A class that will delegate operations to an instance of T.
   /// </summary>
   public class DynamicProxy<T> : DynamicObject
   {
       public event BeforeSetDelegate OnBeforeSet;

       /// <summary>
       /// The instance of T that will be proxied.
       /// </summary>
       private T instance = default(T);

       public DynamicProxy()
       {
           instance = Activator.CreateInstance<T>();
       }

       /// <summary>
       ///
       /// </summary>
       /// <param name="binder"></param>
       /// <param name="result"></param>
       /// <returns></returns>
       public override bool TryGetMember(GetMemberBinder binder, out object result)
       {
           result = null;

           PropertyInfo info = instance.GetType().GetProperty(binder.Name);

           if(info == null)
               return false;

           result = info.GetValue(instance, null);

           return true;
       }

       /// <summary>
       ///
       /// </summary>
       /// <param name="binder"></param>
       /// <param name="value"></param>
       /// <returns></returns>
       public override bool TrySetMember(SetMemberBinder binder, object value)
       {
           if(OnBeforeSet != null)
               OnBeforeSet(binder.Name, value);

           PropertyInfo info = instance.GetType().GetProperty(binder.Name);

           if(info == null)
               return false;

           foreach (var att in info.GetCustomAttributes(typeof(ValidationAttribute), true))
           {
               var vatt = att as ValidationAttribute;
               if(!vatt.IsValid(value))
               {
                   throw new ValidationException("Parameter failed validation.", vatt, value);
               }
           }

           info.SetValue(instance, value, null);

           return true;
       }

       /// <summary>
       ///
       /// </summary>
       /// <param name="binder"></param>
       /// <param name="args"></param>
       /// <param name="result"></param>
       /// <returns></returns>
       public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
       {
           MethodInfo info = instance.GetType().GetMethod(binder.Name);

           for(int i = 0; i < args.Length; i++)
           {
               var param = info.GetParameters()[i];

               foreach(var att in param.GetCustomAttributes(typeof(ValidationAttribute), true))
               {
                   ValidationAttribute vatt = att as ValidationAttribute;
                   bool isValid = vatt.IsValid(args[i]);

                   if (!isValid)
                   {
                       throw new ValidationException(String.Format("Parameter: ({0}) failed validation.", param.Name), vatt, args[0]);
                   }
               }
           }

           result = info.Invoke(instance, args);

           return true;
       }
   }

 

Ahhh…so that’s how the interception target is created! In the constructor of this class. So if I want to proxy say “SomeClass” I can use the following code.

image

Now, what if I want to fire an event before a property is set? Holy Smokes! This allows us to! Since DynamicProxy intercepts ALL calls, if I wire up an event I can raise it before forwarding on the call to the actual object.

image

This is where the magic happens. Before any property is executed on the target object the message get relayed here…in TrySetMember. Here I raise the OnBeforeSet event which I subscribed to earlier. So when i make the call “d.Name = ‘String one’” I will get the following output.

image

So it tells me the name of the property being set. The second line of the output is simply the value of the Name property. Here is what’s happening under the hood: when I set a dynamic property the DynamicProxy class is intercepting the call then it forwards the set to the real object (object of type T). But it’s totally transparent to the caller (aside from using the dynamic keyword when creating the object); the caller is just setting the “Name” property on the SomeClass object.

So what more can we do with this interception technique? How about data validation (could be used as pre/post conditions, for instance). If you take a look back at SomeClass, the property, Name, and a parameter to the function “DoSomethingAndReturn” are both decorated with attributes from the System.ComponentModel.DataAnnotations namespace: StringLength and Range, respectively. I bet you can see where I am going with this…If a property  on the target object is decorated with one of these ValidationAttributes, I will check the validity of the data before setting the property; throwing an exception if validation fails. If you look at the “TrySetMember” operation of the DynamicProxy class, you’ll see I find all custom attributes of type “ValidationAttribute” and check the validity of the data being provided (remember: TrySetMember will have the value of the property). Nothing special here…I just call IsValid() with the data provided (StringLength and Range both derive from ValidationAttribute).

image

To demonstrate the validation I am going to change the code in Main slightly to purposely fail the StringLength(10) rule applied to the “Name” property of “SomeClass.” If I run it I will get the following output:

image

So it told me which validator failed and the expression??? Where did that come from? Ooooh, wait…that’s the actual StringLength attribute displayed as a mathematical expression! How useful is that!? I get the validator that failed along with why (the expression…telling me (26 > 0 and 26 < 10). Remember: The StringLength attribute describes the maximum length of a string…and 0 is obviously the minimum. This makes sense but how did it know? With a simple extension method I created to craft the expression from the attribute:

image

…and on and on. You can take this as far as you want to go…and I’ve only scratched the surface.

Posted in Uncategorized | Leave a comment

ExpandoObject in Practice

It sounds like a joke but there really is a class called ExpandoObject. When I first heard of it I thought it was a farce, but it is actually pretty useful. [Let me preface this by saying I wouldn’t necessarily use this class in production code because it has the potential to be a maintenance nightmare but it’s a good place to learn about dynamic objects.] The ExpandoObject is a DyanamicObject and a DynamicObject is essentially an object that accepts and brokers member calls (methods and properties) made under the dynamic context (sort of like a proxy). ExpandoObject is a type of DynamicObject with a very specific implementation; it defines and overrides specific operations that can be performed on an object (like an actual method call or property set). It then creates properties at runtime that can be executed. The full documentation of the ExpandoObject can be found here.

So what does it mean to create properties at runtime? With ExpandoObject you can do things like this:

// Create an ExpandoObject. Declare it "dynamic".
dynamic ex = new System.Dynamic.ExpandoObject();

ex.Name = "test"; // Creates a simple property of type string.
Console.WriteLine(ex.Name);

In this code example I’ve created an instance of ExpandoObject and assigned it to dynamic variable ex. Variables marked as dynamic are not compile-time checked, but are runtime resolved.

ex.Name is the first property I create. I am going to make it of type string by assigning it a string value. This compiles fine even though I’ve never defined the property “Name;” I am going to let ExpandoObject create it for me.

Under most circumstances, ex.Name would fail at runtime because there is no runtime implementation. In other words if you were to do run the following code you would get an error:

dynamic v = new Object();
v.Name = "test";

Console.WriteLine(v.Name);

 

image 

An exception is thrown because “Name,” even though it compiled, does not exist at runtime.

You can also define methods on ExpandoObject.

// We can also create functions (this action takes no parameters).
  ex.PrintToConsole = (Action)(() => Console.WriteLine("some function"));

  // Creating methods that take a parameter.
  ex.PrintWithParam = (Action<string>)((string s) => Console.WriteLine(s));

  // Creating methods that take a parameter and return a value.
  ex.MethodWithReturn = (Func<int, int>)((int i) => i * i);

  ex.PrintWithParam("hello");
  Console.WriteLine(ex.MethodWithReturn(9));

In the code example above, I defined the method PrintToConsole to be a delegate of type action (does not take any parameter and returns void); you can also create delegates of type Action<> and Func<>…this is a very slick way of defining dynamic methods.

So how does this all work? How does the ExpandoObject know to intercept method calls and define properties? Well, as I mentioned above the ExpandoObject is a DynamicObject (it’s actually an IDynamicMetaObjectProvider, but DynamicObject implements IDynamicMetaObjectProvider). There are many overridable methods in DynamicObject but for our purposes the three most important are: TryGetmember(,,.), TrySetMember(…), and TryInvokeMember(…). When implemented in a subclass, the DLR will call the appropriate method during runtime. So, for instance, when a property is set on an instance of ExpandoObject the DLR calls TrySetMember (with some parameters) on ExpandoObject then ExpandoObject does stuff and returns either true or false; true if the call was successful (which is always is), false otherwise. If false is returned you will get the error above (object does not contain a definition for blah blah blah). I wrote an absurdly simple implementation of my own ExpandoObject for demonstration purposes.

image

Not much to it, really. When a setter is called, TrySetMember will be executed. The binder parameter knows the name of the property that was set….so if you have ex.MyProp = “text”, the binder.Name property will be set to “MyProp.’ In my case I use this as a key into a hashtable…the value is the second parameter. Now when a get member is executed, TryGetMember will be executed with similar parameters: the name of the property that was executed and the result, which you must set before exiting the method. The result is literally the result of the operation. So if I have a property called MyProp with a value “text,” when I go to print that to the screen I should see “text,’ because that’s what I stored in the dictionary when the property was set.

TryInvokeMember is a little more interesting. This is called when a method is executed on a dynamic object (like in my first code example when I defined the delegates). So if I do something like ex.Something(), TryInvokeMember will be executed with all the appropriate parameters set. Since Action, Action<>, and Func<> are all delegate types, I cast the value from the dictionary to a Delegate then dynamically invoke it with the arguments provided.

Using MySimpleExpandoObject in code.

image 

 

Posted in Computers and Internet | Leave a comment

Further Exploring the .Net Expressions API

The .Net Expressions API (as a part of System.Linq.Expressions assembly) provides a vast set of functions that can be used to express mathematical expressions, which can be composed and executed (as lambas) at runtime. Expressions.Add, .Multiply, and .Subtract, are just some of the mathematical functions offered by the API that can be used to express large equations. And, conveniently, the API lends itself well to infix notation (expressions where the operators come before the operands; e.g. (+ * 4 5 6…in infix this would be written as (4 * 5) + 6).

Let’s convert (3 * 9) + 5  into a lambda using the Expressions API. The first thing I will do is express this equation in prefix notation: + * 3 9 5. So as I scan the new equation left to right I will create the appropriate expression construct.

Expression e = Expression.Add(
   Expression.Multiply(Expression.Constant(3), Expression.Constant(9),
         Expression.Constant(5)));

 

If we print “e” directly to the console we will get the equation in infix notation:

image

Notice I did not have to do anything special to “pretty print” the equation. I did not have to write a stack to hold all the variables used, I did not have to create a visitor to print the nodes of the tree…I let .Net handle that for me.

If we want to actually execute it we need to create a lamba expression. Since the function is paramaterless I will use Func<int>as the delegate type.

var fn = Expression.Lambda<Func<int>>(e).Compile();

This line of code creates a Lamba expression whose delegate is of type Func<int> (which simply means the delegate will return an int and has no parameters).

Console.WriteLine(fn().ToString());

Once the function is compiled it can be executed as if it were a conventional method call. Print the result to the console to get 32 as the answer to the equation.

 image

Now, of course, this is an extremely simple example but you see the potential of the API.

Posted in Uncategorized | Leave a comment

C# Properties and Expression Trees

Expression trees in C# fascinate me. They can be used to create dynamic methods or, in some cases, wrap existing methods or properties. Once constructed as lambdas, the expressions can be executed like any other C# method. Reflection accomplishes a similar goal without using the expansive verbosity of expressions. Expressions can be thought of a language within a language; allowing developers to programmatically create c# constructs from any source: a domain specific language, XML, etc. The power of expressions is virtually limitless…but that’s not what this article is about. In this article I’d like to show some useful examples of expression usage, specifically calling properties.

A C# property is just syntactic sugar for getters and setters (methods that return a value and accept a single parameter). Once compiled, a property call (setter) will take on the form of set_X.

image

So if we want to use expression trees to invoke the setter, we need to use the Expression.Call(..) construct. Expression.Call, when compiled into a delegate, executes on an instance. So before we create the expression let’s first create a simple class with a single method (you can also do this with anonymous types).

public class TestClass
{
    public string Name { get; set; }
}

 

Pretty simple class with one property of type string. Now let’s create an expression to set a value on the property on an instance of TestClass.

TestClass t = new TestClass();

// Get the actual setter method.
MethodInfo info = t.GetType().GetProperty("Name").GetSetMethod();

// Create a parameter for the method call expression.
ParameterExpression param = Expression.Parameter(typeof(string), "val");

// Create a method call expression.
// The expression will be .call <instance>.set_Name(val), where val is the parameter to the method.
MethodCallExpression call = Expression.Call(Expression.Constant(t), info,
    new ParameterExpression[] { param });

// Create a delegate whose implementation is the expression we just created.
// An Action is a delegate that takes a single parameter and returns void.
// Create a Lambda expression whose body is the MethodCallExpression that takes a single parameter.
// The parameter will be passed at run time.
Action<string> action = Expression.Lambda<Action<string>>(call, param).Compile();

// Call the delegate (execute the expression).
action("hi");

// Proof we actually set the property.
Console.WriteLine(t.Name);

 

We’ll invoke the delegate (supplying a parameter) then print the value of the property to the console. As you’d expect, it prints “hi.”

image

This all begs the question: why on earth would you want to do this? Well, for most practical purposes it’s obviously easier to just call a property on an instance when you want to set something. But what if you have cascading expressions? What if you need to create an expression-tree to represent dynamically created methods? With the expression API you can build an interpreter of a custom language, for instance. I believe the future of C# lies in the Expression API and the DLR. In a future entry I will examine the DLR and expressions more closely by building a small dynamic proxy engine using method call expressions and the dynamic keyword.

Posted in Uncategorized | Leave a comment

Windows Workflow and Error Handling

Unless caught with a fault handler, runtime exceptions in workflow activities terminates the workflow raising the workflow_terminated event. This could be problematic if your controller logic depends on the completion of the workflow wholesale.

Exceptions can be handled at the workflow level, or, for finer-grained exception handling, at the activity level (be it custom or built-in activities).

imageAll sequential workflows have ‘n’ number of activities that can be applied to the designer surface by dragging and dropping an activity from the toolbox (this is also true for custom activities). When custom activities are compiled they become available in the toolbox; a custom activity is any class that derives from SequenceActivity or, more generically, Activity.

To enable error handling select “Fault Handlers” from the activities’ dropdown.  imageIn this screenshot I choose to design an error handler for the “ProcessingData” activity. The fault handler activity is analogous to a try/catch block in code; exceptions in code…you start with catching specific exceptions and work down to generic “Exception” class. In the FaultHandler activity specific to generic fault handlers are arranged left to right.

image

Since this workflow drives an ADO.Net query I will begin by catching DataServicesRequestException. This is the exception thrown by the server when the service returns a response code less than 200 or greater than 299. Be mindful the Message property of this class will be an XML-encoded message from the server.

From the toolbox find “FaultHandler” and drag it on to the design surface placing it in the fault handler “channel.” Once you’ve added a fault handler it must be set to “catch” a specific exception. Select the fault handler, right click properties and click the ellipses in the “FaultType” property descriptor. imageThe exception chooser dialog that appears has two tabs; we will be focusing on the “Type” tab. On this tab on the left tree view, a list of all referenced assemblies is displayed; I am going to find “System.Data.Services.Client” and select the “DataServiceRequestException”. Once I’ve chosen the exception I want to handle and click ok, I have the opportunity to bind the fault to a workflow property for inspection by a later activity…and this is exactly what I want to do. To bind the fault I choose “Promote Bindable Properties” from the properties view, which will auto generate a property in the workflow code behind that will store the fault.image Now that I have the “catch” and the fault object itself, I want to do something useful with it. I am going to add a code activity to the fault hander that will simply log the fault and continue.

image

Double clicking on “codeActivity1” brings me to the code behind.

private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{

}

 

 

I am going to ignore both parameters in favor of the property I setup earlier, which now stores the actual fault object.

private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
    Logger.Write(faultHandlerActivity1_Fault2.Message);
}

Using the Enterprise Library, I am going to simply write the faults’ message to disk. Now that I caught the exception in this specific activity, any DataServiceRequestExceptions that are raised during the execution of the activity will no longer result in the workflow being terminated; I log the message and continue. Of course this could be problematic if later activities depend on data from this activity, but I will handle each case appropriately (maybe by using an IfElse activity to programmatically disable activity execution).

If you want to handle all exceptions across all activities, use a fault handler to catch “System.Exception” and the workflow level.

Posted in Computers and Internet | Leave a comment