Showing posts with label dynamic. Show all posts
Showing posts with label dynamic. Show all posts

Tuesday, April 19, 2016

Deserialize JSON string to C# dynamic type

Introduction

This is the age of APIs in computer science. To be more specific web APIs. Don't get confused with the specific technology of .Net Web API. Any methods or resources which are exposed via URL in a structure is an API. From our apps we can call them to do achieve the functionality.

Resources are now a days exposed via ReST protocol and the format is JSON. It works well with JavaScript. But when coming to .Net world, its little difficult to keep the JSON as is in our app. Often we need to convert those resources into entity classes. Creating entity class for each API response is a tricky tasks. It puts more time to complete the API integration tasks. Often after using one API for months we may need to switch to another API providing same service. At that time we need to rewrite it. Creating classes to get exact replica of response is really difficult to manage.

But its always suggested to have entity classes which are for our application regardless of the API we are using. As soon as we got the response from the web API, we should convert the response to our model and that should go on from that point on wards.

Dynamic object to hold JSON

In the beginning people were programming without type safety. Then the strong typed languages were introduced and everybody went behind that. Now its the time everybody again going to dynamic typing. May be its because of JavaScript's success.

VB always gave us the option to have dynamic typing. But in C# its introduced with .Net 4.0. The dynamic keyword is introduced to denote the variables which are not type safe. In other words a type which we don't know at compile time, what it is going to contain. Kind of key value store / dictionary.

Enough theory. Below is the code to convert a GitHub API response. The API url is 

private Project GetProjectFromJSON(string json)
{
    JavaScriptSerializer ser = new JavaScriptSerializer();
    dynamic projectNode = ser.Deserialize<dynamic>(json);
    return new Project()
    {
        Name = projectNode["name"],
        Description = projectNode["description"],
        SourceUrl = projectNode["html_url"],
        Url = projectNode["homepage"]
    };
}

JavaScriptSerializer is a .Net framework class. We don't need to add any dependency to third parties. There are other .Net libraries which are helping to convert JSON to dynamic object but those will add unwanted dependencies. Hope this is self explanatory.

Important thing to note here is the usage of dynamic. Do not ever return dynamic to outer world. This method should hide the complexities of getting the project from GitHub. The consumers of this method then don't need to change when the logic of GitHub API interaction changes.

More details about usage in real application can be seen in this file.

Tuesday, September 3, 2013

Reading formatted MS Excel cell values using Open XML SDK and showing as HTML

Most of the existing mechanisms which helps to access Excel cells from our applications doesn't give us the formatting of the excel cell. If we select the excel data using OleDB connectors it return plain text. The Excel COM interop give more, but it gives format details for entire cell. What about an Excel cell contains data like below and we want to show the excel cell values with formatting in a MVC application using a Rich Text Editor say KendoUI editor?

Bold data,
Italics, Underlined and big font in green color

Since everything in new Excel file format is XML based and open, the sdk provides the options. But not as easy as we think. We need to get the reference string and we need to iterate through the RunProperties collection. The code is as follows

private string GetCellValue(Cell excelCell)
        {
            if (excelCell == null) 
                return null;
            if (excelCell.DataType == null)
                return excelCell.InnerText;
 
            string value = excelCell.InnerText;
            switch (excelCell.DataType.Value)
            {
                case CellValues.SharedString:
                    value = ReadFromSharedString(excelCell);
                    break;
                case CellValues.Boolean:
                    switch (value)
                    {
                        case "0":
                            value = "false";
                            break;
                        default:
                            value = "true";
                            break;
                    }
                    break;
            }
            return value;
        }

This starts with the assumption that you have basic idea how to obtain Excel Cell object using open xml. If you are not clear on it please refer the link. Make sure you have the open xml sdk dll named DocumentFormat.OpenXml.dll. You may download from this link too.

What is SharedString and ReadFromSharedString? Actually excel keeps a reference to the value and the actual value will be there in a different node. The reference will normally be integer and that will be stored in the excelCell.InnerText property.Lets see the code for ReadSharedString();

private string ReadFromSharedString(Cell cell)
{
    string value = cell.InnerText;
    SharedStringTablePart sstPart = GetSharedTablePart(cell);
    // lookup value in shared string table
    if (sstPart != null && sstPart.SharedStringTable != null)
    {
        int index = int.Parse(value);
        if (sstPart.SharedStringTable.ElementAt(index).ChildElements.Count == 0)
        {
            value = sstPart.SharedStringTable.ElementAt(index).InnerText;
        }
        else
        {
            //ChildElements is collection of Run
            value = GetStringValueFromRuns(sstPart.SharedStringTable.ElementAt(index).ChildElements);
        }
    }
    return value;
}


First part is about how to get the SharedStringTablePart object? Next is about why we are calling GetValueFromRuns(). First things is simple. You can understand by looking the below code. Second one I will explain after the code segment to get the SharedStringTable.


private SharedStringTablePart GetSharedTablePart(Cell cell)
{
    Worksheet workSheet = cell.Ancestors<Worksheet>().FirstOrDefault();
    SpreadsheetDocument doc = workSheet.WorksheetPart.OpenXmlPackage as SpreadsheetDocument;
    SharedStringTablePart sharedStringTablePart = doc.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
    return sharedStringTablePart;
}


Now coming to the GetStringValueFromRuns. Basically the cell data is arranged as series of Run elements. Each run element represents unique formatting and corresponding text.In this case 'Bold Data' will be a run element and 'Italics' will be next run element. So we need to iterate the run collection and create the required formatting.


private string GetStringValueFromRuns(OpenXmlElementList openXmlElementList)
{
    StringBuilder text = new StringBuilder();
    foreach (Run run in openXmlElementList)
    {
        //    //t ADD OPENNING TAGS HERE, if any
        if (run.RunProperties != null)
        {
            foreach (OpenXmlLeafElement element in run.RunProperties.OrderBy(e => e.LocalName))
            {
                //StartTagWrite is the extension method.
                element.StartTagWrite(text);
            }
        }
        text.Append(run.Text.Text.Replace("\n","<br/>"));
        if (run.RunProperties != null)
        {
            foreach (OpenXmlLeafElement element in run.RunProperties.OrderByDescending(e => e.LocalName))
            {
                element.EndTagWrite(text);
            }
        }
    }
    return text.ToString();
}


Each Run will be having Run properties which define the attributes of each run. Important thing to note down is the Run properties classes are different in different Office versions.

Note the extension methods StartTagWrite and EndTagWrite. Those are defined in a different class


    static class Extension
    {
        public static void StartTagWrite(this OpenXmlLeafElement runElement, StringBuilder writer)
        {
            IWriteOperation x = new HTMLWriteOperation { Writer = writer };
            x.StartTagWrite((dynamic)runElement);
        }
        public static void EndTagWrite(this OpenXmlLeafElement runElement, StringBuilder writer)
        {
            IWriteOperation x = new HTMLWriteOperation { Writer = writer };
            x.EndTagWrite((dynamic)runElement);
        }
    }

Here comes a design challenge. Look at the casting using dynamic. This is because each run property is different class. ie there is no base class for run properties. The property class Bold , Italic and Color don't have a common base. The base which we gets is the OpenXmlLeafNode. This is in fact a base class for many nodes other than Run properties. So we need to use the dynamic casting and call the method. Since its dynamic it will call corresponding methods defined in the interface.Below is the interface declaration and corresponding class


private interface IWriteOperation
{
    void StartTagWrite(Bold bold);
    void StartTagWrite(Italic it);
    void StartTagWrite(Underline underline);
    void StartTagWrite(Color c);
    void StartTagWrite(Font font);
    void StartTagWrite(FontSize fontSize);
    void StartTagWrite(FontFamily fontFamily);
    void StartTagWrite(FontScheme fontScheme);
    void StartTagWrite(RunFont runFont);
    void StartTagWrite(Strike strike);
    void StartTagWrite(VerticalTextAlignment vertialAlignment);
    void StartTagWrite(Shadow shadow);
    void StartTagWrite(Outline outline);
    void StartTagWrite(Condense condense);

    void EndTagWrite(Bold b);
    void EndTagWrite(Italic b);
    void EndTagWrite(Underline b);
    void EndTagWrite(Color u);
    void EndTagWrite(Font u);
    void EndTagWrite(FontSize u);
    void EndTagWrite(FontFamily u);
    void EndTagWrite(RunFont u);
    void EndTagWrite(FontScheme u);
    void EndTagWrite(Strike u);
    void EndTagWrite(VerticalTextAlignment u);
    void EndTagWrite(Shadow u);
    void EndTagWrite(Outline u);
    void EndTagWrite(Condense u);
}
private class HTMLWriteOperation : IWriteOperation
{
    public StringBuilder Writer { get; set; }

    void IWriteOperation.StartTagWrite(Bold iThing) { Writer.AppendLine("<B>"); }
    void IWriteOperation.EndTagWrite(Bold iThing) { Writer.AppendLine("</B>"); }

    void IWriteOperation.EndTagWrite(Underline aThing) { Writer.AppendLine("</U>"); }
    void IWriteOperation.StartTagWrite(Underline aThing) { Writer.AppendLine("<U>"); }

    void IWriteOperation.StartTagWrite(Italic aThing) { Writer.AppendFormat("<I>"); }
    void IWriteOperation.EndTagWrite(Italic aThing) { Writer.AppendFormat("</I>"); }

    void IWriteOperation.StartTagWrite(Strike u) { Writer.AppendLine("<del>"); }
    void IWriteOperation.EndTagWrite(Strike aThing) { Writer.AppendLine("</del>"); }

    void IWriteOperation.StartTagWrite(Color u)
    {
        if (u.Rgb != null)
        {
            string colorFormat = @"<span style=""color:#{0};"">";
            string span = string.Format(colorFormat, u.Rgb.Value.Substring(2, 6));
            Writer.AppendLine(span);
        }
    }
    void IWriteOperation.EndTagWrite(Color aThing)
    {
        Writer.AppendLine("</span>");
    }
    void IWriteOperation.StartTagWrite(RunFont u)
    {
        if (u.Val.HasValue)
        {
            string fontFormat = @"<span style=""font-family:'{0}';"">";
            string span = string.Format(fontFormat, u.Val.Value);
            Writer.AppendLine(span);
        }
    }
    void IWriteOperation.EndTagWrite(RunFont aThing)
    {
        Writer.AppendLine("</span>");
    }

    void IWriteOperation.EndTagWrite(FontSize aThing)
    {
        Writer.AppendLine("</span>");
    }
    void IWriteOperation.StartTagWrite(FontSize u)
    {
        string fontSizeFormat = @"<span style=""font-size:{0}px;"">";
        string span = string.Format(fontSizeFormat, u.Val);
        Writer.AppendLine(span);
    }

    void IWriteOperation.StartTagWrite(Font u) { }
    void IWriteOperation.EndTagWrite(Font aThing) { }

    void IWriteOperation.EndTagWrite(FontScheme aThing) { }
    void IWriteOperation.StartTagWrite(FontScheme u) { }

    void IWriteOperation.EndTagWrite(Condense aThing) { }
    void IWriteOperation.StartTagWrite(Condense u) { }
    
    void IWriteOperation.EndTagWrite(VerticalTextAlignment aThing) { }
    void IWriteOperation.StartTagWrite(VerticalTextAlignment u) { }

    void IWriteOperation.EndTagWrite(Shadow aThing) { }
    void IWriteOperation.StartTagWrite(Shadow u) { }

    void IWriteOperation.StartTagWrite(FontFamily u) { }
    void IWriteOperation.EndTagWrite(FontFamily aThing) { }

    void IWriteOperation.StartTagWrite(Outline u) { }
    void IWriteOperation.EndTagWrite(Outline aThing) { }   
}

Reading a cell using OpenXML itself involves lot of code. So this is certainly not going to be easy to understand. Let me know if anybody needs a sample which does it.

Tuesday, September 6, 2011

Creating non zero based arrays in .Net

Last week when I was hunting for .Net performance tips and an array related tip got my attention.It says “Non-zero based arrays will reduce performance”.ie the current default lower bound of .net array is 0.If we change this lower bound of array it will cause performance penalty.But luckily there are no places in our project where developers used non-zero based arrays. I should say thanks to .Net architects in Microsoft than our developers, for making the creation of non-zero based arrays bit complicated. According to my current knowledge, using the normal declaration syntax of array, its not possible to create non-zero based arrays. The only way now is to use the Array.CreateInstance method.Look at the below code snippet.

Array arrayObject = Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 2 });



This creates single dimension integer array of size 5 with lower bound as 2.ie you need to access the array as arrayObject[2] to [6] not arrayObject[0].



Normal array and Array.CreateInstance


As you know all the arrays are of class type Array which gives them the ability of iteration and all. We can create array using the CreateInstance method, just like how we create normal array with square bracket.If we display the type of Array object we can see its exactly same as the type of normal array object with [].We can cast the output to normal array object and access the elements using [].Look at the below code it just creates an array with zero as lower bound and access the element at position 0.




private void TestBase0Array()
{
Array arrayObject=Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 0 });
int[] intArray = arrayObject as int[];
if (intArray != null)
{
Console.WriteLine("TestBase0Array(): ArrayCreateInstance() succeded for base 0, Array type :" + intArray.GetType().FullName);
try
{
intArray[0] = 10;
Console.WriteLine("TestBase0Array():Write & Read from array [0] - " + intArray[0]);
}
catch (Exception ex)
{
Console.WriteLine("TestBase0Array():Not able to access array");
}
}
else
Console.WriteLine("TestBase0Array(): Not able cast to int[]");
}



Type of non-zero based arrays


When we come to arrays who’s lower bound is not zero, the type will be different. it will contain a ‘*’.If its an integer array the type will be ‘System.Int32[*]’. This means we cannot cast the output of Array.CreateInstance to our normal array object which is declared using [].(But I am not sure whether there are any hidden methods to cast to normal array).So we cannot access the array elements using [].Then the final option is to use the SetValue and GetValue methods of Array class.Look at the below code.




private void TestBase2Array()
{
Array arrayObject=Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 2 });
int[] intArray = arrayObject as int[];
if (intArray != null)
{
Console.WriteLine("TestBase2Array(): ArrayCreateInstance() succeded for base 0, Array type :" + intArray.GetType().FullName);
try
{
intArray[0] = 10;
Console.WriteLine("TestBase2Array():Write & Read from array [0] - " + intArray[0]);
}
catch (Exception ex)
{
Console.WriteLine("TestBase2Array():Not able to access array using []");
}
}
else
{
Console.WriteLine("TestBase2Array(): Not able cast to int[].Array Type :"+arrayObject.ToString());
Console.WriteLine("TestBase2Array(): Lower bound :" + arrayObject.GetLowerBound(0).ToString());
Console.WriteLine("TestBase2Array(): Length :" + arrayObject.Length.ToString());

try
{
arrayObject.SetValue(10, 0);
Console.WriteLine ("TestBase2Array(): Element at 0"+ arrayObject.GetValue(10, 0).ToString());
}
catch (Exception ex)
{
Console.WriteLine("TestBase2Array(): Not able to access element at 0.Trying 2nd element");
arrayObject.SetValue(10, 2);
Console.WriteLine("TestBase2Array(): Element at "+arrayObject.GetValue(2).ToString());
}
}
}



dynamic keyword and non-zero based arrays


Its really difficult to use 2 methods to access an array for a developer who would like to access the array as it is.So I tried assigning the output of Array.CreateInstance to a dynamic variable and used the square brackets.It never gives a compilation error.But at runtime it fails with an exception “Unable to cast object of type 'System.Int32[*]' to type 'System.Int32[]'”.




private void TestBase2ArrayUsingDynamic()
{
Array arrayObject = Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 2 });
dynamic intArray = arrayObject;
try
{
intArray[2] = 10;
Console.WriteLine("TestBase1ArrayUsingDynamic():Write & Read from array [0] using dynamic keyword- " + intArray[2]);
}
catch (Exception ex)
{
Console.WriteLine("TestBase1ArrayUsingDynamic():Exception :"+ ex.Message +
Environment.NewLine + "Not able to access non zero based array even using dynamic keyword!!!");
}
}


That means dynamic keyword also failed. We need to use the SetValue and GetValue if we want to use non-zero based arrays.

Non-Zero based arrays and VB.Net


But in VB.Net the story is different.If you are working in VB.Net its all easy.You can use non-zero based arrays in the normal array. I don’t know whether it’s the beauty or curse of unsafe programming.




Dim arrayObject = Array.CreateInstance(GetType(Integer), New Integer() {5}, New Integer() {2})
arrayObject(2) = 10
Console.WriteLine(arrayObject(2).ToString)



I don’t think we need to use non-zero based arrays in any of the situations of our normal programming life. One more thing is this non-zero based array creation is not supported by Silverlight. That means if you are developing in common code base which is targeted for WPF,Silverlight and WP7 you will not encounter this scenario.

Saturday, February 26, 2011

Concepts of PropertyBag and the ExpandoObject

Need for PropertyBag
Lets consider the scenario of dynamic table creation in your database.User is allowed to create screens dynamically and for those screens they can even customize the business entities including creation of new entities.In this scenario you can’t create your business classes concretely.The reason is simple you don’t know what entities will come and how many properties they will have and their types.

The solution to this problem ie “Handling dynamic tables through business objects” is PropertyBag

What is PropertyBag
Property bag is nothing but a dictionary which keeps the property name and their values.Below is a sample implemenation.

public abstract class EntityBase
{
Dictionary<string, object> _propertyBag;
public object this[string propertyName]
{
get
{
return _propertyBag[propertyName];
}
set
{
_propertyBag[propertyName] = value;
}
}
}


Normally there will be one more checking for the typed properties.If the typed property exists the getter will return the value of the typed property and setter set the same.Dictionary will be used only when there is no typed property.

Using the property bag is through the indexer property.If there is a EntityBase derived Customer class with typed properties Name and Id, we can use this property bag to store a new value as Address property without recompiling the Customer class.


public class Customer : EntityBase
{
public int Id { get; set; }
public int Name { get; set; }
}




Customer cust = new Customer();
cust["Address"] = "Cochin";


Works perfect even though we can’t write like which we prefer.

cust.Address = "Cochin";


But this is type safe and from the view of typed language it should not compile.There should be no exemption for any class from having dynamic properties.


ExpandoObject

The above said story became history with the arrival of the ExpandoObject class in .Net 4.0 which allows dynamic properties.


dynamic  eo = new ExpandoObject();
eo.Joy = "My Name";


Joy is not at all a property of ExpandoObject class.But it compiles and works.The backend implementation is dictionary though.Ok there is one more argument that if we re-write our implementation using the new .net4 dynamic keyword will it work?

dynamic eo = new Customer ();
eo.Joy = "My Name";


Yes I meant the above code snippet only.This will compile.But on execution it will throw an exception of type RuntimeBinderException with the message “'Expression_Test.Customer' does not contain a definition for 'Joy'”.

Ok.Now you might be thinking that we can change the base class of our Customer entity class to ExpandoObject.But we can’t because the ExpandoObject is sealed :-(


DynamicObject class

There is another class named DynamicObject.We need to inherit from this class which implements the IDynamicMetaObjectProvider interface.Change the customer class as


public class Customer : DynamicObject
{
public int Id { get; set; }
public int Name { get; set; }
}


Compile the program.No errors…You may be thinking that its done.But actually not.When you run you will get the same RuntimeBinderException.Why we are getting this even after inheriting from a base class.That class should handle it right? Goto the definition of the DynamicObject class.You can see all the methods are virtual.Mean no code is written to handle the properties.ie property bag is not implemented there.Now what to do? Overriding in each and every entity class and implementing property bag is not possible because in a real business application there will be hundreds of business classes.

Return of the EntityBase class

Come back to EntityBase and inherit it from DynamicObject and override methods and use the same old dictionaryto set and get values.Here is the final code.


public abstract class EntityBase : DynamicObject
{
Dictionary<string, object> _propertyBag;
public object this[string propertyName]
{
get
{ //Code to check typed properties,if exists return that value
return _propertyBag[propertyName];
}
set
{ //Code to check typed properties,if exists set that property
_propertyBag[propertyName] = value;
}
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{ //Code to check typed properties,if exists return that value
return _propertyBag.TryGetValue(binder.Name, out result);
}

public override bool TrySetMember( SetMemberBinder binder, object value)
{ //Code to check typed properties,if exists set that property
_propertyBag[binder.Name] = value;
return true;
}
}
public class Customer : EntityBase

{
public int Id { get; set; }
public int Name { get; set; }
}


Now the below code will compile and run without any exceptions.

dynamic eo = new Customer   ();
eo.Joy = "My Name";


Unusual relation between Language and Framework SDK

All is well.Now we can write code normally for even non existing properties.How this magic is happening? The compiler doesn’t show any error message because it all done on a variable declared using dynamic keyword.Come to runtime.How the runtime knows that it should call the TryGetMember method? Some understandings between the framework types and the runtime?

Yes.The key is IDynamicMetaObjectProvider interface.If the class has implemented this interface the runtime will call the TryGetMember and accepts the value. Don’t you smell an unusual relation between runtime and the Microsoft classes? You must,if you had worked in any other languages or technologies.

Monday, September 13, 2010

Difference between dynamic ,var and object keywords

When I heard about the new dynamic keyword in C# 4.0 I was confused.Why there is a new keyword where var works for me if I don’t know the data type. After digging into the concept I could understand the need for dynamic keyword.
var is type safe ie when we click on the dot(.) it will display the public members of the type which the var is currently holding.But dynamic on the other hand will not be able to display the list.There will be no compilation error on the dynamic keyword even if we use some junk characters as its member methods or properties.Its just like the old style programming where there is no type safety.At run time the method or property may or may not be there.
Internally how dynamic is handled is just a reflection code.It checks for the member through reflection and it invokes the member if exists.Else throws exception.If you want to see the reflected code of dynamic keyword just use the reflector.
Object v/s dynamic
Object is just the base class.in other words all the other classes inherits from this and its type safe.That means you can’t compile code ,if the object variable is trying to invoke members other than its defined members.
Criteria Object Var Dynamic
Type safety Yes Yes No
Supports as method argument type Yes No Yes
As source in for each iteration Not supported Supported Supported
Application areas To hold objects as base class. Linq queries, Com interop
Need type casting on assignment Yes No No
Compilation examples Object o = new Button();
o.Width doesn’t compile
var o = new Button();
o.Width will compile
dynamic o = new Button();
o.Width and even o.xyz() will compile where xyz is not a member
I know this is a small list.There may be more scenarios with memory usage and speed of execution.If time permits I would be adding more.
I was able to see a real good application of dynamic when I worked on browser interaction from Silverlight.My Silverlight blog will get that sample soon.