30 November 2015

Parsing XML to objects in .NET

Introduction

There is a general requirement in many projects to parse XML to an object and vice versa. Instead of using inefficient and error prone method of manual XML parsing, .NET object serialization/deserialization functionality can be used to achieve similar result in a more efficient and elegant manner. This approach is very generic and will work with all types of XML.

Approach

System.Runtime.Serialization provides methods for serializing and de-serializing XMLs.
DataContractSerializer method of System.Runtime.Serialization namespace can be used to achieve functionality of -

  • XML to object conversion (XML Parsing [De-Serialization])
  • Object to XML conversion (Object Serialization)
  • Apart from this, Generics feature of C# has been utilized to make the methods generic and independent of object types. It also enhances type-safety of the code. Actual type needs to be specified only when method is called.
  • The method for ‘Serialization’ accepts type of data to serialize as a parameter ‘T’. This makes the method generic in a sense that it can accept object of any type for serialization and we don’t have to define that at time of method declaration.
  • The method for ‘De-Serialization’ returns de-serialized data. The return type has been specified as generic ‘T’. This makes the method generic in a sense that it can de-serialize and return object of any type.
Implementation

1.    Class declaration
1.1. Create a static class named ‘XmlParserDeparser’.
1.2. Reason for making this class static is that this class acts as a utility class and there will be no need to create instance of this class to access its helper methods.
1.3. Add following namespace in the class file –
1.3.1.   using System;
1.3.2.   using System.Collections.Generic;
1.3.3.   using System.IO;
1.3.4.   using System.Runtime.Serialization;
1.3.5.   using System.Text;

2.    XML to object conversion (XML parsing/de-serialization)
2.1. To achieve this conversion, DataContractSerializer method of System.Runtime.Serialization will be used.
2.2. Declare a static method with name XmlToObject<T>.
2.3. Here ‘T’ will be type of the data object to create after parsing XML using de-serialization techniques.
2.4. This method will return object created from XML.
2.5. It will take two input parameters -
·         XML as string
·         Known types to include in the serializer (can be null too)
2.6. Complete code for the method is presented below –
/// <summary>
/// Deserializes the specified XML string.
/// </summary>
/// <typeparam name="T">The type of the data to deserialise to.</typeparam>
/// <param name="xml">The XML string representing the data to deserialise.</param>
/// <param name="knownTypes">The known types to include in the serializer.</param>
/// <returns>The deserialised data in object form.</returns>
public static T XmlToObject<T>(string xml, IEnumerable<Type> knownTypes)
{
    using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)))
    {
        var serializer = new DataContractSerializer(typeof(T), knownTypes);
        T theObject = (T)serializer.ReadObject(stream);
        return theObject;
    }
}

2.7. Here a memory stream is created using XML as input.
2.8. An instance of System.Runtime.Serialization.DataContractSerializer is created specifying type ‘T’ and enumeration of knownTypes as input. Latter is optional though (can be null).
2.9. Now the object of DataContractSerializer reads the XML and creates a generic object.
2.10. This object is cast to type ‘T’ and then returned.
2.11. We can also create over-load of this method with only one parameter i.e. ‘XML as string’.
2.12. This method will internally call the above method with ‘knownTypes’ passed as null.
2.13. The signature for this method will be as follows –
        /// <summary>
        /// Deserializes the specified XML string.
        /// </summary>
        /// <typeparam name="T">The type of the data to deserialise to</typeparam>
        /// <param name="xml">The XML string representing the data to deserialise</param>
        /// <returns>The deserialised data in object form</returns>
        public static T XmlToObject<T>(string xml)
        {
            return XmlToObject<T>(xml, null);
        }


3.    Object to XML conversion (Object serialization)
3.1. To achieve this conversion, DataContractSerializer method of System.Runtime.Serialization will be used.
3.2. Declare a static method with name ObjectlToXml<T>.
3.3. Here ‘T’ will be type of the data object to convert to XML using serialization techniques.
3.4. This method will return XML as string.
3.5. It will take two input parameters -
·         Type of object to convert to XML
·         Known types to include in the serializer (can be null too)
3.6. Complete code for the method is presented below –

/// <summary>
/// Serializes the specified input data, of type T, to XML string.
/// </summary>
/// <typeparam name="T">The type of the data to serialise.</typeparam>
/// <param name="data">The data to serialise.</param>
/// <param name="knownTypes">The known types to include in the serializer.</param>
/// <returns>The data as an XML string.</returns>
public static string ObjectToXml<T>(T data, IEnumerable<Type> knownTypes)
{
    using (var memoryStream = new MemoryStream())
    {
        var serializer = new DataContractSerializer(typeof(T), knownTypes);
        serializer.WriteObject(memoryStream, data);
        memoryStream.Seek(0, SeekOrigin.Begin);

        var reader = new StreamReader(memoryStream);
        string content = reader.ReadToEnd();
        return content;
    }
}

3.7. Here a memory stream is created first.
3.8. An instance of System.Runtime.Serialization.DataContractSerializer is created specifying type ‘T’ and enumeration of knownTypes as input. Latter is optional though (can be null).
3.9. Now the object of DataContractSerializer reads the object data and writes the output (XML) into memory stream.
3.10. This memory stream is then read by a StreamReader object till end and converted to string which is returned by method.
3.11. We can also create over-load of this method with only one parameter i.e. ‘Type of object to convert to XML’.
3.12. This method will internally call the above method with ‘knownTypes’ passed as null.
3.13. The signature for this method will be as follows –
  /// <summary>
        /// Serializes the specified input data, of type T, to XML string.
        /// </summary>
        /// <typeparam name="T">The type of the data to serialise.</typeparam>
        /// <param name="data">The data to serialise.</param>
        /// <returns>The data as an XML string.</returns>
        public static string ObjectToXml<T>(T data)
        {
            return ObjectToXml(data, null);
        }


Advantages
  • The advantage of using this approach is that you are able to perform XML parsing very easily without writing custom parsing code.
  • Similarly you are able to easily convert an object to XML without need of any custom code.
  • This code is generic and will work for all types of XML and objects. We just need to ensure to specify proper XML and object type (T).

25 November 2015

Introduction to AngularJS

AngularJS is an open source JavaScript framework developed by Google. It helps in extending capabilities of HTML, CSS & JavaScript. It enhances browser based applications with MVC (Model-View-Controller) capabilities which help in making development and testing easier. AngularJS combines both Declarative Programming (used for building UIs and wiring software components) and Imperative Programming (used for building business logic). It provides two-way data binding features (similar to Silverlight/WPF XAML) which helps in automatic synchronization of models & views. It decouples DOM manipulation from application logic thus improving testability of the code.

Features of AngularJS -

Two way data binding – AngularJS provides two way data binding between Model & View. The data between model & view is automatically synchronized on change. This is most important and useful feature of AngularJS. This feature takes care of DOM manipulation and listening to DOM events. Thus application developers can focus on application logic instead of writing boiler plate code for handling DOM manipulation.

Model-View-Controller (MVC) – AngularJS is based on the basic principles of MVC design pattern.

  • In AngularJS, any JavaScript object can act as a Model. 
  • View is the declarative HTML used for UI design. It is based on DOM objects.
  • Controller is responsible for construction of the model and connects it to View. It contains business logic. They can be nested and can handle inheritance. 

Services – They perform small common tasks for your web application. We can use in-built services or create our own using various methods viz. Service API, Factory API or $provide API. In-built AngularJS services starts with “$” symbol.

Dependency Injection – AngularJS has in-built Dependency Injection. AngularJS services can be passed as parameters whenever required. AngularJS identifies the dependencies and automatically creates their instance.

Directives – Directives enables programmers to extend the HTML vocabulary in a declarative way. They help in transforming DOM or creating new behavior.  AngularJS has some in-built directives. It also allows programmers to create their own directives.

Templates – AngularJS enables programmers to create static declarative templates containing HTML, CSS & AngularJS elements. These templates get combined with model and controller at run-time to render the final view.

Filters – Filters helps in performing data transformation and data formatting. They can also be used to filter results.

Validation – AngularJS has many in-built validations for various HTML5 input variables, controls and directives. E.g. – Validations for textbox, number, URL, email, radio, checkbox, required validator, pattern validation, minlength, maxlength, min, max etc. It also enables programmers to create their own validations which can be re-used.

Testability – Applications created using AngularJS are highly testable due to use of MVC pattern and Dependency injection. Unit tests can be created and run against JavaScript code making enterprise application level testing possible.

References and Suggested Readings

http://angularjs.org/

20 November 2015

KendoUI controls not working in all browser versions

Recently we faced a strange problem with KendoUI controls. While most of the controls were working fine, KendoUI tab control was not working in all versions of Internet Explorer. It was loading fine on first page load but when we tried to click any other tab, nothing was happening. After quite a bit of research, we found a simple solution to the problem.

Add following tag in your HTML file -

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

This will ensure that your HTML code works fine in all browsers as required. Especially the latest browser that you are using.

Apart from this solution, we also recommend to use latest version of Kendo UI controls as far as possible. We were using one year old version of Kendo UI (2014 Q2) while the latest version was 2015 Q3 SP1. Kendo is very good in fixing minor bugs like these in their progressive releases. So its always a better idea to use the latest version.

02 November 2015

FabricJs - Top features

FabricJs is a simple and powerful JavaScript library for HTML5 which helps in working with HTML5 canvas objects. It is an open source library. HTML5’s native APIs to work with canvas are low level and provide limited functionalities. FabricJs helps in manipulating and animating objects in HTML5 canvas in a much powerful manner without losing the canvas state. It creates an interactive layer above HTML5 canvas which enables easier manipulation of canvas objects. It renders canvas in a much faster manner as compared to HTML5 due to use of SVG.

Features of FabricJs:

Interactivity – FabricJs enable users to interact with objects on HTML5 canvas using mouse. Interaction can be dragging object, rotating object, scaling object etc.

Paths – In FabricJs, paths represent an outline of a shape that can be stroked, filled or modified in other ways. It consists of a series of commands (move, line, curve, arc etc.) which can help in producing complex shapes.

Groups – In FabricJs, we can group multiple objects together using ‘Groups’. These objects can then be manipulated together as a single unit.

Animation – FabricJs provides powerful animation capabilities like rotate, move, shrink, grow, fade-in, fade-out etc.

Image Filters – FabricJs provides methods to apply filters to images. It provides some inbuilt filters. E.g. – Brightness, Tint, Sepia, Convulate, Grayscale, Invert, Pixelate, Noise etc. It also gives option to apply custom filter. It also give option to remove a filter from image or apply multiple filters to images.

Gradient – FabricJs provides methods to apply gradients to objects. Gradient can be applied using multiple colors as well.

Text – FabricJs supports text abstraction and enables to work with text in object oriented model. It also supports rich text which enables to change various text properties like font style, font shadow, alignment, height, background, height, multiline support etc.

Events – FabricJs is based on event driven architecture. It supports lots of events from low level hardware (mouse, keyboard) events to high level object events.

Sub-classing – FabricJs supports inheriting from existing classes. We can also create our own classes and even extend existing classes.

Free drawing – FabricJs has excellent support for free hand drawing on the canvas.

Canvas Serialization –FabricJs supports serializing canvas into object/string which can be easily transmitted or stored.  FabricJs supports 3 types of serialization –

  • To JSON – This converts canvas object into JSON string.
  • To Object – This converts canvas object into an array of point objects.
  • To SVG – This converts canvas object into SVG (Scalable Vector Graphics) text format using SVG parser.


Canvas Deserialization – FabricJs supports two ways to render canvas from string –

  • From JSON – This recreates the canvas from a JSON string
  • From SVG – This recreates the canvas from SVG string.


References and Suggested Readings:


01 November 2015

Dynamically generate header in SilverLight Telerik RAD Grid using MVVM approach

In this post, we will discuss how to dynamically change the grid headers in SilverLight Telerik RAD Grid using MVVM approach.

Create simple Silverlight project ‘DynamicGridHeader’. Create two folders name it as “View” and “View Model”. Add Silverlight user control to the View folder name it as “MyView”. MyView page will have all my user controls to show the data.

Create simple Telerik grid in the page and add one button to change the headers.  Grid should have Four columns showing data for country Names, Country ID, Population for current year and last year population.















Create a class in view model to add data to the grid.  And implement INotifyPropertyChanged
Interface to get notification when property changes.














Populate dummy data in the constructor.


























Till now the grid will show the data for current year and previous year. With column headers as 2012 and 2011.














Now when user want to check data for 2011 and 2010 the column header will not change. It is always show 2012 and 1011. To change the column dynamicaly create two properties one showing selected year and other showing previous year. Bind these properties to textblock and then to the grid headers.









Now when user select previous year the headers will changed dynamically.





















That's it. Simple and elegant solution !