How to add dynamic property to your class with ExpandoObject

In some scenario, you may want to add dynamically information to your object without having to define a specific type or interface. This type of scenario has been developed by Asp.Net MVC with the ViewBag which let you add any type of information dynamically. In a project, you may want to have this kind of behavior and be able to add information of different type and to access it later.

To do, you need to use the ExpandoObject.

public class YourClass
{
	public int Id{ get; set; }
	public dynamic Attributes { get; set; }

	public MatriceRow()
	{
		Attributes = new ExpandoObject();
	}
}

This is a working example. From there you can use the YourClass class and set attributes.

 var myClass = new YourClass();
 myClass.Id = 1;
 myClass.Attributes.IsBoolean = true;
 myClass.Attributes.MyName = "Patrick Desjardins";

You cannot define the Attributes property directly to the type of ExpandoObject. If you do, you will get an exception.

‘IsBoolean’ and no extension method ‘IsBoolean’ accepting a first argument of type ‘System.Dynamic.ExpandoObject’ could be found (are you missing a using directive or an assembly reference?)

This functionality should be used rarely. It’s always better to be strongly typed and not use dynamic because this one is only checked when the code is executed rather than when compiled.

How to extend (or add) conditionnal clause to Expression

If you need to concatenate two expressions (with OR or AND) this can be done easily with the help of the LinqKit library.

The idea is to Invoke both expression with the same model object.

Expression<Func<Customer, bool>> filter1 = customer => customer.FirstName == "Test";
Expression<Func<Customer, bool>> filter2 = customer => customer.LastName == "Test";
Expression<Func<Customer, bool>> filter3 = customer => filter1 .Invoke(customer) || filter2.Invoke(customer);

The last step is to use AsExpendable() and to you Expand to the last filter (filter3).

IEnumerable<Customer> customers = CustomerRepository.GetAll().AsExpandable().Where(filter3.Expand()).OrderBy(c => c.Id);

The AsExpendable() method simple create a wrapper around the IQueryable to create a ExpendableQuery. From here, the provider will change with the concrete provider ExpendableQueryProvider which inherit from IQueryProvider. This one will call the .Expand() of the expression.

If you go check the source code of the method ExpendableQuery we can see the wrapping.

public static IQueryable<T> AsExpandable<T>(this IQueryable<T> query)
{
  if (query is ExpandableQuery<T>)
	return query;
  else
	return (IQueryable<T>) new ExpandableQuery<T>(query);
}

The expand look like this :

    public static Expression<TDelegate> Expand<TDelegate>(this Expression<TDelegate> expr)
    {
      return (Expression<TDelegate>) new ExpressionExpander().Visit((Expression) expr);
    }

It call the Visit method of the ExpressionExpander from the Expression.

In short, what you have to remember it the use of LinqKit.dll make you life really easier when you manipulate dynamic expression.

So you have appended two Linq To Entity expression
http://stackoverflow.com/questions/1266742/append-to-an-expression-linq-c

Dynamic caching level

I have read an interesting article that talk about the different level of caching that Dynamic keyword use.

The dynamic lookup is performed at runtime with 3 different ways. First, it checks if the last dynamic methods and arguments type correspond to the last call. If yes, it will reuse the compiled code. This is very fast, as fast as using something not dynamic minus the little extra step of validation.

The second way is to check into the complete list of dynamic code that has been called to find a method signature corresponding. This is also very fast. If it found something, it will update the last called method to be faster next time otherwise, it will goes into the last step.

The last step is so build the method call and to update the list of methods. The pseudo code of the logic is like that:

if (lastMethod = currentOneInvoked) {
    Invoke(currentOneInvoked);
}
else if(listMethod.Find(currentOneInvoked)) {
    Invoke(currentOneInvoked);
}
else {
    UpdateAndInvoke(currentOneInvoked, arg0, ...);
}

So, dynamic method is slower but is optimized to be as must fast as possible.

How to unit test a method that return an anonymous type?

It’s really easy to have in ASP.NET MVC a function that return an anonymous type. I say in ASP.NET MVC but this could be also in ASP.NET. In fact, when you have an action inside a controller that return a JsonResult you can simply return an anonymous type and Javascript will be able to handle it as simple as using the same syntax that you would use with object in C#.

public JsonResult Update(MyObject o)
{
 //...
 return Json(new { IsSaved = false, Id = 123});
}

In Javascript you would use :

//...Ajax call
 success: function (data) {
   var x = data.IsSaved;
   var xx = data.Id;
}

To unit test this scenario, you need to do two things. First, you need to use the dynamic keyword of .Net to be able to receive from the controller the response of the action which is anonymous.

dynamic returnedData = myController.Update(new MyObject());

The problem is that everything that has been generated as anonymous in a DLL stay internal. If you are doing you unit testing in a separated assembly (DLL) you will need to explicitly say that you want to share internal values with another assembly. This can be done by modifying the assembly configuration by editing AssemblyInfo.cs. You need to open the file AssemblyInfo.cs of the tested controller and add the following statement.

[assembly: InternalsVisibleTo("Tests.Unit")] 

This will give the permission to see internal to the unit testing project called “Tests.Unit”.

Import Json object from Javascript into C# with Dynamic keyword

I never really used the dynamic keyword in a real application. I did some tutorials but not much.

This week, I got a situation where I was getting from Silverlight a Json object that I did not want to create an object for.

string response = HtmlPage.Window.Invoke("GetMyJson").ToString();
MyObject data = (MyObject)JsonConvert.DeserializeObject(response);

But, I did not wanted to create the MyObject because it was just for transferring data; a simple DTO object. Instead, I used the dynamic keyword provided by .Net framework 4.0.

The dynamic keyword will be resolved in runtime and this give us the leverage to access property that might not exist. For example, “GetMyJson” function was returning a simple object with 2 properties “Abc” and “Def”.

{'Abc':'123','Def':'456'}

So, in the C# code, I simply called those properties from the dynamic object.

string response = HtmlPage.Window.Invoke("GetMyJson").ToString();
dynamic data = JsonConvert.DeserializeObject(response);
string s1 = data.Abc;
string s2 = data.Def;

This is pretty useful for accessing quickly some data from Json object.