Archive for the ‘C#’ Category

REST/HTTP Services in WCF is nothing new, it’s been there since 2008, version 3.5 of the framework. Yesterday I came across a question that whether a particular operation can support both XML/JSON format and return response in the suitable format as demanded by the client program. To my knowledge the answer was a both Yes & No. Because I did quite extensive study of the System.ServiceModel.Web.WebHttpBehavior and System.ServiceModel.Web.WebGetAttribute back in 2008 as given in the post below:

https://sankarsan.wordpress.com/2008/10/28/wcf-web-model-poxjson-support/

This limitation drew my attention. However there was a solution to the problem.We can always extend the WebHttpBehavior and override the WebHttpBehavior.GetReplyDispatchFormatter method to return our own custom implementation of System.ServiceModel.Dispatcher.IDispatchFormatter. A similar implementation can be found in the post below:

http://damianblog.com/2008/10/31/wcf-rest-dynamic-response/

Wait …..

This kind of an implementation is actually now part of the .NET 4.0. This is controlled by the automaticFormatSelectionEnabled property of the WebHttpBehavior. This property when set to true then the response format of the operation is governed by the Accept , Content-Type header of the request. This feature is called Automatic Format Selection. This is what we will discuss in this post.

I have a simple service with a Add operation as shown below:

[OperationContract] 
[WebGet] 
public int  Add(int i , int j) 
{ 
   // Add your operation implementation here 
   return i+j; 
} 

The client code is a .NET program sending a HTTP request as shown below:

HttpWebRequest request = HttpWebRequest.Create("http://localhost:5072/TestService.svc/Add?i=1&j=1") as HttpWebRequest; 
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None; 
request.Method = "GET"; 
request.ContentType = "text/xml"; 
request.Accept = "text/xml"; 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
using (StreamReader rdr = new StreamReader(response.GetResponseStream())) 
{ 
    Console.WriteLine(rdr.ReadToEnd()); 
}

The response is in JSON format as shown below:

{"d":2}

Now I will turn on auto format selection as shown below using config.

wcfauto

Now the output is XML as shown below:

<AddResponse xmlns="http://sankarsanbose.com/test"><AddResult>2</AddResult></Add 
Response>

Now I will change the Accept header to JSON.

request.ContentType = "text/xml"; 
request.Accept = "text/json";

The response is now again in JSON format as shown below:

{"d":2}

NOTE: If both Accept and Content-Type are specified then Accept takes the higher priority.

What happens if I set the response format in WebGetAttribute? Say I make it Json as shown below:

[OperationContract] 
        [WebGet(ResponseFormat=WebMessageFormat.Json)] 
        public int  Add(int i , int j) 
        { 
            // Add your operation implementation here 
            return i+j; 
        }

The output is driven by Accept Header and is in XML format

<AddResponse xmlns="http://sankarsanbose.com/test"><AddResult>2</AddResult></Add 
Response> 

If I change the headers to JSON obviously the output is JSON.

Now I am changing the ResponseFormat to XML as shown below:

[WebGet(ResponseFormat=WebMessageFormat.Xml)] 

The request headers are set as shown below:

request.ContentType = "text/json"; 
request.Accept = "text/json"; 

The output surprisingly is just 2 neither JSON nor XML.

The request headers are changed back to XML

request.ContentType = "text/xml";
request.Accept = "text/xml";

Now the output is XML is as shown below:

 
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">2</int>

This is clearly different from structure of the XML generated earlier. Seems to be using the different serializer.

I was not able to articulate the reason for the above two anomalies very clearly. But I think when auto format selection is enabled then providing the ResponseFormat does not make much sense.

In Groovy ConfigSlurper is a utility class that is used for reading configuration files written in form of Groovy scripts.Let’s consider the following properties file.

props

We will use a Groovy script to read from this properties file as shown in the snippet below:

package com.test

import java.util.Properties

class Start {

    static main(args) { 
        def p = new Properties() 
        new File("test.properties").withInputStream { 
          stream -> p.load(stream) 
        } 
        println "gfv3.admin.url=" + p["gfv3.admin.url"] 
  
    }

}


This is a very simple piece of code which makes use of the java.util.Properties class and load the properties file using java.io.File and it’s associated InputStream class.Here the properties are accessed as  a map of name/value pairs. This code can be tweaked bit using the ConfigSlurper class and the values can be accessed as object properties as shown below:

package com.test

import java.util.Properties

class Start {

    static main(args) { 
        def p = new Properties() 
        new File("test.properties").withInputStream { 
          stream -> p.load(stream) 
        } 
        def cfg = new ConfigSlurper().parse(p) 
        println "gfv3.admin.url=" + cfg.gfv3.admin.url 
    
    }

}

We can write a similar ConfigSlurper in C# using the System.Dynamic.ExpandoObject which allows us to add and remove properties to this object at runtime.ExpandoObject implement a IDictionary and IDynamicMetaObjectProvider interfaces as shown in the definition below:

public sealed class ExpandoObject : IDynamicMetaObjectProvider,IDictionary<string, Object>, ICollection<KeyValuePair<string, Object>>, IEnumerable<KeyValuePair<string, Object>>, IEnumerable, INotifyPropertyChanged

We can use the IDictionary implementation to attach properties at runtime as shown below in the ConfigSlurper class.

public static class ConfigSlurper 
{ 
    public static ExpandoObject  Parse(System.Collections.Specialized.NameValueCollection settings) 
    { 
        var config = new ExpandoObject(); 
        var dictConfig = (config as IDictionary<String, object>); 
        foreach (var k in settings.AllKeys) 
        { 
            dictConfig[k] = settings[k]; 
        } 
        return config; 
    } 
} 

The config settings are defined as shown below:

<appSettings> 
  <add key="gfv3AdminUrl" value="http\://localhost\:4848"/> 
  <add key="gfv3Root" value="D\:\\Program Files\\glassfish-3.0.1\\glassfish"/> 
  <add key="gfv3Port" value="4848"/> 
  <add key="gfv3Host" value="localhost"/> 
  <add key="gfv3Username" value="admin"/> 
  <add key="gfv3Url" value="http\://localhost\:8080"/> 
</appSettings> 

This config can be read using the ConfigSlurper class as:

static void Main(string[] args)
{
    dynamic config = ConfigSlurper.Parse(ConfigurationManager.AppSettings);
    Console.WriteLine(config.gfv3AdminUrl);
    Console.Read();
}

In this post we will discuss about different techniques of sorting collections of objects in C# using the functions provided by the base class libraries.This is something very common and there different types of provisions in .NET BCL to achieve the same.We will try to discuss the advantages and limitations of each of these approaches.

I will start with the most simplest of all the techniques that is implementing the interface IComparable<T>. The IComparable<T> has the following methods:

  • int CompareTo(T other) – This method compares one instance of object of type T with another which is passed as parameter.

The following class implements an IComparable<T> interface as shown below:

public class Member : IComparable<Member> 
    { 
        public int ID { get; set; } 
        public String FirstName { get; set; } 
        public String LastName { get; set; } 
        public DateTime DateOfJoining { get; set; }


        public int CompareTo(Member other) 
        { 
            return this.ID.CompareTo(other.ID); 
        } 
    }

Here the comparison is done based on the property ID of the member class. The following snippet is used to demonstrate the usage.

List<Member> ls = new List<Member>() 
                                { 
                                    new Member(){ID=1,FirstName="John",LastName="Doe"}, 
                                    new Member(){ID=3,FirstName="Allan",LastName="Jones"}, 
                                    new Member(){ID=2,FirstName="Martin",LastName="Moe"}, 
                                    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"} 
                                }; 
ls.Sort(); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

Here the output will be sorted by ID as shown below:

Member John:Doe
Member Martin:Moe
Member Allan:Jones
Member Ludwig:Issac

Now if we want to sort by other properties as well like FirstName, LastName etc. One crud approach is to create different subclasses as shown below:

public class MemberByFirstName : Member, IComparable<MemberByFirstName> 
    { 
        public int CompareTo(MemberByFirstName other) 
        { 
            return this.FirstName.CompareTo(other.FirstName); 
        } 
    }

Then when we need to sort by say FirstName we will use List of this sub class as shown below:

List<MemberByFirstName> ls = new List<MemberByFirstName>() 
{ 
            new MemberByFirstName(){ID=1,FirstName="John",LastName="Doe"}, 
            new MemberByFirstName(){ID=3,FirstName="Allan",LastName="Jones"}, 
            new MemberByFirstName(){ID=2,FirstName="Martin",LastName="Moe"}, 
            new MemberByFirstName(){ID=4,FirstName="Ludwig",LastName="Issac"} 
}; 
ls.Sort(); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

The output will be alphabetically sorted by FirstName as shown below:

Member Allan:Jones
Member John:Doe
Member Ludwig:Issac
Member Martin:Moe

But this is a cumbersome and rigid approach.Similar stuff can be implemented in a much more cleaner way using the IComparer<T> interface.This interface defines the following method:

  • int Compare(T x,T y) – This method takes two objects of type T and compares between them.

We can implement IComparer<T> as shown below:

public class MemberSorterByLastName : IComparer<Member> 
   {

       public int Compare(Member x, Member y) 
       { 
           return x.LastName.CompareTo(y.LastName); 
       } 
   } 
   public class MemberSorterByFirstName : IComparer<Member> 
   {

       public int Compare(Member x, Member y) 
       { 
           return x.FirstName.CompareTo(y.FirstName); 
       } 
   } 
  

We can use the method Sort(IComparer comparer) as shown below to sort the List of Member by FirstName and LastName respectively:

List<Member> ls = new List<Member>() 
                                { 
                                    new Member(){ID=1,FirstName="John",LastName="Doe"}, 
                                    new Member(){ID=3,FirstName="Allan",LastName="Jones"}, 
                                    new Member(){ID=2,FirstName="Martin",LastName="Moe"}, 
                                    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"} 
                                };

ls.Sort(new MemberSorterByFirstName());

ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

ls.Sort(new MemberSorterByLastName());

ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

This approach is clean but has the overhead of creating separate classes for each different sort criteria.This can be achieved much more simply using the Comparison<T> delegate. The Comparison<T> delegate has the following signature:

  • public delegate int Comparison<in T>(T x,T y) – This is used to compare two objects of generic type T.

We can use the Sort (Comparison<T> comparison) method as shown below:

List<Member> ls = new List<Member>() 
                    { 
                        new Member(){ID=1,FirstName="John",LastName="Doe"}, 
                        new Member(){ID=3,FirstName="Allan",LastName="Jones"}, 
                        new Member(){ID=2,FirstName="Martin",LastName="Moe"}, 
                        new Member(){ID=4,FirstName="Ludwig",LastName="Issac"} 
                    };

ls.Sort((x, y) => x.FirstName.CompareTo(y.FirstName)); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

ls.Sort((x, y) => x.LastName.CompareTo(y.LastName)); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName)); 

By far this approach is the most simplest one. In other languages like Java the first two options are there e.g. Java Comparer interface is similar to IComparable and Comparator interface is similar to IComparer in C# respectively. But Java is yet to have support for Closures so the third approach is still not possible.

In this post and couple of posts to follow, we will discuss about the different type casting mechanisms supported by CLR and the three primary CLR supported languages C#,VB.NET and C++/CLI.To start with, lets take a look into the two possible kinds of conversion scenarios, that generally we come across.

(more…)

In my last post I had discussed about entity relationships,navigational properties and how we can fetch data from database into the entities.In this post we will examine the many to many relationships and how this can be modeled using POCO and the CTP 4.0 Code First Approach.We will consider three tables Person,Club and ClubMember where each Person can belong to multiple Clubs as shown below:

(more…)

In the last two posts I have discussed about Entity Framework CTP 4.0 Code First Approach and Database Initialization.Now we will take a look at how to define relationships and navigational properties between the Entities and how data fetching is impacted by these.

(more…)