Dynamic columns via DynamicObject

This might be obvious to some of you, but I thought of writing a small post, since it has a nice example of the usage of .NET 4. DynamicObject.
Recently I had a requirement where I had to dynamically generate a tabular data (rows/cols) and use that data for Json serialization.
There are few ways of implementing this. The below example uses the .NET 4. DynamicObject to generate custom columns. I found this is quite easier and cleaner to implement than the tradition reflection based approach.

static Table GenerateData()
           {

               var columnsSet1 = new List<Col>() {new Col("row1Col1"), new Col("row1Col2"), new Col("row1Col3")};
               var columnsSet2 = new List<Col>() {new Col("row2Col1"), new Col("row2Col2"), new Col("row2Col3")};             

               var rows = new List<Row> {  new Row() { Cols = columnsSet1 },
                                           new Row() { Cols = columnsSet2 },

                                    };

               var rowList = new List<dynamic>();

               foreach (var row in rows)
               {
                   dynamic dynamicCol = new ColExpando(); //ColExpando derived from DynamicObject
                   var cols = row.Cols;

                   foreach (var col in cols)
                   {
                       dynamicCol.Column = col.Val;
                   }
                   rowList.Add(dynamicCol);
               }
               var tb = new Table { Data = rowList };
               return tb;
           }

        public class ColExpando: DynamicObject
        {
            private readonly Dictionary<string, object> members = new Dictionary<string, object>();
            private int colAppendIndex = 0;           

            public override bool TrySetMember(SetMemberBinder binder, object value)
            {

                   colAppendIndex++;
                    string key = binder.Name + colAppendIndex;

                    if (!members.ContainsKey(key))
                    {
                        members.Add(key, value);
                    }
                    else
                    {
                        members[key] = value;
                    }
                    return true;
              }

            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                    if (members.ContainsKey(binder.Name))
                    {
                        result = members[binder.Name];
                        return true;
                    }

                    return base.TryGetMember(binder, out result);
              }

            public override IEnumerable<string> GetDynamicMemberNames()
            {
                return members.Keys;
            }
        }

Note that colAppendIndex is an incremental number which appends a number in front of the key of the property name. This gives us the uniqueness of the keys in the dictionary.
If you call this method in console app and binds to json as below


static void Main(string[] args)
           {
               var json = JsonConvert.SerializeObject(GenerateData(), Formatting.Indented); //using Newtonsoft.Json lib
               Console.WriteLine(json);
               Console.Read();
           }

Output:

{

  "Data": [

    {

      "Column1": "row1Col1",

      "Column2": "row1Col2",

      "Column3": "row1Col3"

    },

    {

      "Column1": "row2Col1",

      "Column2": "row2Col2",

      "Column3": "row2Col3"

    }

  ]

}

ASP.NET MVC Unit Tests with UnityAutoMoq Container

 

UnityAutoMoq container is a great way to write maintainable Unit Tests. Since the container simplifies faking of dependencies, we can now focus on the actual test itself and spend less time on faking unwanted dependencies

For more info, please refer to the article below.

http://www.dotnetcurry.com/ShowArticle.aspx?ID=767

Keeping your C# code clean with Regionerate

I came across with this really nice VS add-in called Regionerate, which allows you to group various member types into regions. I’m a fan of keeping code tidy and this add-in really helps me to organise the code.

It works on Visual Studio 2010 and only works with C#.

You can download the Add-In from here.

Once you install this tool, you are ready to use the Regionerate.

You can also change the settings of Regionerate, go to Tools and click Regionerate Settings.

To use the Regionerate, simply use the Ctrl +R. You should see a window with few options as below. Alternatively just right click on Text Editor and select ‘Regionerate this’ from the context menu.

image

 

As per the above options, you can create regions based on the member types (I.e public, private, and internal), regionalise by the member name, regionalise by the member type and the member name, order the members without and regions, and remove existing regions etc..

Below is a code sample on selecting the ‘Primary Code Layout’.

image

 

I strongly encourage you to have a look at this Add-In as it is very useful.