Archive for the ‘C#’ Category

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…)

In the last post we discussed about the basic steps involved in working with the new Entity Framework CTP 4.0 Code First Approach.Now we will take a look at each of these steps in a bit more detail.We will start with database initialization.
(more…)

It has been a month or two  that Entity Framework CTP 4.0 bits have released.I had read through the feature list back then but could not manage time to take a detailed look until this weekend.I always felt that Entity Framework’s approach towards handling of configuration(object relational mappings) and plain .NET objects was bit restrictive and cumbersome respectively.The mappings are needed to be stored in Entity Data Model(.edmx) files which are nothing but xml files with object to relational store mapping information.There was no proper way to express this mapping through code or attributes.But with code first approach we will able to describe our model using plain .NET objects and map it to the database objects through .NET code.In this post we will discuss the very basic steps involved in doing so.

(more…)