amazedsaint blogs
anoop's home : spiritual programming - technology to super conciousness!!

Creating A Fluent Interface in C# - For training a bunch of Dogs

A simple post on a simple subject

Today Vin just tweeted "FI(Fluent Interface) - when you use method chaining, after finishing the functionality, "return this", and that's how you make it fluent".

Thought about writing a detailed post on this, just to demonstrate various possibilities of Fluent programming.

Chaining Methods - A Simple Scenario


Assuming that you are interested in training animals, let us start with a simple ITrainable interface. :)

    /// 
    /// Anything that is trainable
    /// 
    public interface ITrainable
    {
        ITrainable Train(string skill);
        ITrainable Do(string skill);
    }

Well, nothing fancy there. Let us go ahead and create a Dog Class, which implements this interface. The only interesting piece you may find in the Dog class is, all methods are returning a type of ITrainable. As long as our Dog class implements ITrainable, we can return 'this', i.e the current Dog Instance.
    /// 
    /// Our simple dog class
    /// 
    public class Dog : ITrainable
    {
        public string Name { get; set; }
        public List Skills { get; set; }

        public Dog(string name)
        {
            Console.WriteLine();
            Console.WriteLine("Dog " + name +
                   " created");

            Name = name;
            Skills = new List();
        }

        //Let us train this skill to our dog
        //Note that we are returning 'this', so that
        //we can continue training or ask the dog to perform
        public ITrainable Train(string skill)
        {
            Console.WriteLine("Dog " + Name +
                    " learned " + skill);
            this.Skills.Add(skill);
            return this;
        }

        //Let us ask the dog to perform this skill
        public ITrainable Do(string skill)
        {
            if (Skills.Contains(skill))
                Console.WriteLine("Dog " + Name + 
                    " is doing " + skill);
            else
                Console.WriteLine("Dog " + Name + 
                    ": Don't know how to " + skill);

            return this;

        }
    }

Now, we are ready to train our Dog fluently. Like,
           //Train one dog, Hope your name is not Bobby ;)
            var dog = new Dog("Bobby");
            dog.Train("Running").Train("Eating")
                .Do("Running").Do("Eating");

As you can see, we are chaining the method calls, because in each call, we are returning an object of type ITrainable. You'll see what Bobby is doing in the console
Dog Bobby created
Dog Bobby learned Running
Dog Bobby learned Eating
Dog Bobby is doing Running
Dog Bobby is doing Eating


Chaining Methods - For Collections


Now, let us do something more interesting. Let us create a couple of extension methods for all collections of ITrainable. We do this by writing an extension method for IEnumerable<ITrainable>. If you see, our extension methods are accepting a bunch of trainable organisms(?) (read, IEnumerable<ITrainable>) and returns the same.

Leave out the Console.WriteLine(), it is there just for some pretty printing.
    /// 
    /// Let us fluently train a bunch of Trainable
    /// animals
    /// 
    public static class TrainableExtensions
    {
        //Note that we are returning the IEnumerable
        public static IEnumerable
            Train(this IEnumerable flock, string skill)
        {
            foreach (var member in flock)
                member.Train(skill);
            Console.WriteLine();
            return flock;
        }

        //Ask all members to perform a skill
        public static IEnumerable
            Do(this IEnumerable flock, string skill)
        {
            foreach (var member in flock)
                member.Do(skill); 
            Console.WriteLine();
            return flock;
        }

    }

Now, let us create few dogs, and train them together :)
           //Let us create the dogs and train them
            var dogs = new List{new Dog("Jimmy"),
                                     new Dog("Sando"),
                                     new Dog("Rob")};

            //Now train them
            dogs.Train("EatingFood").Train("Running")
                 .Do("EatingFood")
                 .Train("JumpingToRing").Do("Running");

And you'll see what they are doing, in this order.
Dog Jimmy created
Dog Sando created
Dog Rob created

Dog Jimmy learned EatingFood
Dog Sando learned EatingFood
Dog Rob learned EatingFood

Dog Jimmy learned Running
Dog Sando learned Running
Dog Rob learned Running

Dog Jimmy is doing EatingFood
Dog Sando is doing EatingFood
Dog Rob is doing EatingFood

Dog Jimmy learned JumpingToRing
Dog Sando learned JumpingToRing
Dog Rob learned JumpingToRing

Dog Jimmy is doing Running
Dog Sando is doing Running
Dog Rob is doing Running


Now, as LINQ methods are essentially extension methods on top of IEnumerable<T>, you can mix and match the extension methods we just wrote, with LINQ methods. For example, if we decide only Rob should learn a special skill (JumpingRing), you can do this.
            dogs.Train("EatingFood").Skip(2)
                 .Train("JumpingRing").Union(dogs)
                 .Train("TakingPaper");

And you'll see how this works
Dog Jimmy learned EatingFood
Dog Sando learned EatingFood
Dog Rob learned EatingFood

Dog Rob learned JumpingRing

Dog Rob learned TakingPaper
Dog Jimmy learned TakingPaper
Dog Sando learned TakingPaper

And finally, Fluent APIs can be used for much more useful tasks (If you havn't yet realized, lol). Few fluent API's I've come across


Happy coding!!

WCF Instance Context Mode and Bindings


As well known, the instance context mode property of Service Behavior can have these three values.

  • PerCall - New instance is created for each client request.
  • PerSession -  New instance is created for each new client session, and will be available throughout the session
  • Single - Only one instance handles for all client requests throughout the application 
Example:

[ServiceBehavior(
     InstanceContextMode = InstanceContextMode.PerSession)]
 public class Service1 : IService1
    { 
       ...
    }

Now, what is the default value for the InstanceContextMode? I wrote a quick WCF app, and drilled down in debug mode.













As you might see, if you examine OperationContext.Current.InstanceContext and examine the Behaviour, you'll find useSession set to true, which means, it is PerSession.

But wait, let me change the binding to basicHttpBinding from wsHttpBinding - and let us have a look again.












Now you'll find that useSession is false, which means, the context mode is defaulting to PerCall, because basicHttpBinding can't support sessions. So the inference is, for bindings that support session, the default is PerSessions, other wise it is perCall.

Now, change the context mode in your service attribute to Single, and see what happens to the singleton variable in Behavior, in the above watch.

Weekend Hacks - .NET Soup for the passionate Soul



This weekend, it was some real fun and seems that I was frantically going through various stuff, partly related to a fun project I'm doing with SL and Live Mesh.

I was just going through my browser history, and got amazed with the stuff I went through this weekend. Here is a couple of useful links you might want to check out.








1Managed Extensibility Framework - Home


    • MEF enables greater reuse of applications and components. Using MEF, .NET applications can make the shift from being statically compiled to dynamically composed. If you are building extensible applications, extensible frameworks and application extensions, then MEF is for you.
2.NET "must-have" development tools - Stack Overflow


    • A good list of free tools available for .NET development
 3Microsoft Health Common User Interface - Release: Release 6.6.43.00


    • An LOB reference application in Silverlight
4Silverlight 3 Out-of-Browser Apps vs. Live Framework Mesh-Enabled Web Application


    • Good read if you are interested in Silverlight and Live Mesh 
5Live Framework SDK and Tools


    • Started with a weekend hack on creating a Live Mesh application. If you want to start with Live Mesh, download this SDK and tools
6Glimmer: a jQuery Interactive Design Tool - Home


    • Glimmer helps you create nice JQuery interfaces quickly and easily. Must see if you are a fan of JQuery
7Coding4Fun : Twitterlight: A Silverlight Twitter client


    • Have a look at this silverlight twitter client.
Building a Live Mesh Silverlight Application | WPF Dev 


    • Some good intro towards starting building your on Live Mesh silver light application.

Planning to update cool links from my history on every weekend, Subscribe or Follow me on twitter

Dynamic Language Runtime and Lambda Expressions

Something interesting about the Dynamic Language Runtime API in .NET 4.0

Dynamic objects can't be used with LINQ queries. If you look at it one way, this seems obvious. Consider this following code

dynamic dogList =GetMyDynamicList();

//Trying to find first dog with age 2, but this doesn't work
var result = dogList.FindFirst(dog => dog.Age==2);


If FindFirst is an extension method, there is no way DLR can detect that, because dogList is a dynamic object.

Even for instance method calls of a dynamic object, you can't pass a lambda expression, as lambda expressions cannot appear as arguments to a dynamic method call. The compiler cannot bind an anonymous function without knowing what type it is converted to.

Update:


In my reply to this question @ stack overflow, John Skeet pointed that



You can use anonymous functions, you just have to cast them first:
dynamic list = new List<string>() { "10", "20" };
dynamic converted = list.ConvertAll((Func<string, int>) (x => int.Parse(x)));
See the above question in stack overflow, for more interesting tips from Jon

Staffing a Silverlight Project


Here is something that I wrote as JDs for staffing a Silver light Project.
UX Designer Profile
  • Ability to visualize and create user experiences, and to translate them to UI designs using Expression Blend
  • Excellent understanding of XAML and capabilities of Silverlight
  • Excellent understanding of creating and applying styles and templates
  • Ideal candidate will have been working with Silverlight 1.0 since its inception, with examples showing level of expertise with an understanding of enhancements made with 2.0 and 3.0.
Silverlight Architect
  • Ability to guide the team by putting in place the required tools and frameworks (end to end) for Silverlight specific projects
  • Experience using Expression Blend and Visual Studio for Silverlight application development
  • Good understanding of XAML Styles, Triggers, Observable Collection, Data Binding Methods, Model View View-Model (MVVM) pattern, Navigation patterns
  • XML and LINQ within Silverlight
  • All aspects of Silverlight framework including DLR, Isolated storage etc
  • Understanding about essential application blocks like Composite application block (Prism) Excellent understanding on using RIA, WCF services and ADO.NET Entity framework services with Silverlight
  • Excellent knowledge of development within .NET 3.0 & 3.5 Framework
  • Must understand the fundamentals of software development, including best practices and OOP design patterns. An understanding of cross-browser Front-end development issues is important
  • Knowledge about 3rd party UI libraries
  • Familiarity in Live Mesh technologies
Silverlight Developer
  • Experience using Expression Blend and Visual Studio for Silverlight application development
  • Excellent C# and XAML skills
  • Experience in using MVVM
  • Strong JavaScript skills
  • Working knowledge of development within .NET 3.0 & 3.5 Framework

Published Software Design Patterns For Everyone Ebook

Aggregated some of my earlier articles on design patterns (I published in code project), and published an e-book on the same over Scribd. The objective is to introduce software design patterns to you in a simple, human readable, and funny (?) way - in the context of designing a soccer engine - By discussing the thought process behind applying design patterns

Software Design Patterns Made Simple Software Design Patterns Made Simple Anoop Madhusudanan Introducing software design patterns to you in a simple, human readable, and funny (?) way - in the context of designing a soccer engine - By discussing the thought process behind applying design patterns

Commanding in Silverlight via Prism

One major feature that lacked in Silverlight implementation when compared to WPF infrastructure is support for Commanding. The Composite Application Block for Silverlight [Here] provides Commanding support for Silverlight using attached behaviors. The implementation is quite simple.

Here is how to create reference to the CAL from your Silverlight Project

  1. Download Prism from here
  2. Open and build the solution CompositeApplicationLibrary.sln
  3. Add a reference to the following dlls from your Silverlight application
      • Microsoft.Practices.Composite
        • Microsoft.Practices.Composite.Presentation
          • Microsoft.Practices.Composite.UnityExtensions
            • Microsoft.Practices.ServiceLocation
              • Microsoft.Practices.Unity
            Now, to use Commanding, you can simply create a command by implementing ICommand interface (available from Silverlight 2.0 onwards), and expose your command as a property of your View Model or something (to the context you are binding to).

            Now, to bind to your command to a control, you need to use the Microsoft.Practices.Composite.Presentation.Commands. See this example
            <UserControl x:Class="MyApp.Toolbar"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                xmlns:cmd=
                 "clr-namespace:Microsoft.Practices.Composite.Presentation.Commands; 
                 assembly=Microsoft.Practices.Composite.Presentation"
                >
            
            </UserControl>
            

            And once you have the Commands namespace imported in Xaml, you can bind your command to an element like this.

             <Button cmd:Click.Command="{Binding OpenCommand}" 
                cmd:Click.CommandParameter=
                          "{Binding SelectedItem, ElementName=cmbForm}">
             </Button>
            

            Note that I'm using Element binding to pass the command parameter, obviously I'm using Silverlight 3.0 beta. :)

            NumToBoolConverter - A simple IValueConverter implementation

            Some 'Beginner's' stuff. One good thing about WPF is the ability to specify custom converters, when you do the binding.

            Here is a simple IValueConverter implementation, to convert an int value (1 or 0) to corresponding bool values (true or false).

            Useful if you want to bind a check box or something to a property of numeric type.

             
            public class NumToBoolConverter : IValueConverter
                {
            
                    #region IValueConverter Members
            
                    public object Convert(object value, Type targetType, 
                        object parameter, System.Globalization.CultureInfo culture)
                    {
                        if (value!=null && value is int )
                        {
                            var val = (int)value;
                            return (val==0) ? false : true;
                        }
                        return null;
            
                    }
            
                    public object ConvertBack(object value, Type targetType, 
                        object parameter, System.Globalization.CultureInfo culture)
                    {
                        if (value!=null && value is bool )
                        {
                            var val = (bool)value;
                            return val ? 1 : 0;
                        }
                        return null;
                    }
            
                    #endregion
                }
            

            Now, to do the binding in Xaml, you can just create a resource,

            <Window.Resources >
                    <local:NumToBoolConverter x:Key="IntConverter"/>
                </Window.Resources>
            

            And then do the binding. Simple and easy.

            <CheckBox Name="chkBox" 
            IsChecked="{Binding Path=IntProperty,Mode=TwoWay, 
            Converter={StaticResource IntConverter}}"/>
            

            PDF to XAML Conversion - Alternate Thoughts

            Today I did a small experiment to see how we can use PDF to generate XAML files. I wanted to mimic the pdf form entry in Silverlight.

            Here is the summary of what I've done.

            • Created a new Silver light Project in Expression Blend 3.0 Beta
            • As Expression Blend can import adobe illustrator files, I simply renamed a pdf file's extension from pdf to ai
            • Clicked File-> Import Adobe Illustrator files in Blend, and imported to my active window.
            • Cool, I've the whole form imported as graphical paths, preserving the whole layout.




            I just modified the layout a bit so that it can be embedded it in a canvas in a scoll viewer. So that I can place Silverlight controls (textbox/checkbox etc) on top of that to Mimic form entry. Looks good.

            Thinking Beyond ToString()

            If you want to convert something to string, what is the best way?.

            Here is a neat extension method for all your objects, so that it'll find the appropriate converter if one exists, or otherwise, fall back to ToString() :)

            
            public static class ConverterExtension
                {
                    public static string ConvertToString(this object value)
                    {
                        TypeConverter converter = 
                          TypeDescriptor.GetConverter(value.GetType());
            
                        // Can converter convert this type to string?
                        if (converter.CanConvertTo(typeof(string)))
                        {
                            // Convert it
                            return converter.ConvertTo(value, 
                                    typeof(string)) as string;
                        }
            
                        return value.ToString();
                    }
                }
            
            
            Now, try this code, and find out what is the result
            
            Color val = Color.Red;
            
            //Call our extension method
            string result1 = val.ConvertToString();
            
            //Try with ToString()
            string result2=val.ToString();
            
            
            See what is in result1 and result2, so that you can make out what I'm talking about. Simple, but useful when you work with scenarios where you want to serialize your object's properties.

            Mixtify 10K Gallery is cool

            This weekend I was playing with some entries in Mixtify 10 K Gallery, and it is cool. Really got some fresh thoughts. Loving it. Click here to check out

            Here are a couple of interesting stuff.

            Silverlight Turtle

              

            The Silverlight Turtle looks really cool  - It supports around 12 commands, and it is good fun if you wrote some LOGO script earlier.


            Chain Reaction

            The moment I saw this, I started coding something similar in Silverlight. Very addictive, very simple.

              

            A Twitter Visualizer

            The application may not be that high-fi, but this gives a good conceptual draft of creating a great visualizer for Twitter using Silverlight. Worth going through this.

              

            Worth having a look

            The above are some quick picks, here is much more for you to explore

            TFS API Insights

            As I was recently working with TFS Client APIs, here are few thoughts on the same.

            Logging Into TFS Server

            To log in to the TFS Server using the TFS Client APIs, you can either use the domain authentication, or provide the username or password explicitly

            - Logging in using the current windows user

            TeamFoundationServer _tfsServer = new TeamFoundationServer("serverUrl");
            _tfsServer.Authenticate();
            

            - Logging in using a specific network credential

             _tfsServer = new TeamFoundationServer(
                                    "serverUrl", 
                                   new System.Net.NetworkCredential
                                           ("userName", "password", "domain"));
             _tfsServer.EnsureAuthenticated();
            

            Getting all the projects - Using VersionControlServer

            After logging in, you can get all the projects and project items in TFS as shown below. We are reading the latest version for each item

            VersionControlServer _versonControlServer=_tfsServer.GetService
                            (typeof(VersionControlServer)) as VersionControlServer;
            
             foreach (var teamProject in 
                         _versonControlServer.GetAllTeamProjects(true)) 
             {
                   //Get all the items in the project
                   ItemSet items = 
                          _versonControlServer.GetItems
                           (teamProject.ServerItem, VersionSpec.Latest, 
                                                     RecursionType.OneLevel);
                   foreach (Item item in items.Items)
                                    { //do your stuff with each project item }
             
            
             }
            

            Reading all users - Using GroupSecurityService Now, you can read all users using the IGroupSecurityService, as shown.

               IGroupSecurityService _groupSecurityService = 
            _tfsServer.GetService(typeof(IGroupSecurityService)) 
                         as IGroupSecurityService;
            
            Identity identity = _groupSecurityService.ReadIdentity
              (SearchFactor.EveryoneApplicationGroup, null, QueryMembership.Expanded);
            
            foreach (Identity user in _groupSecurityService.ReadIdentities
                      (SearchFactor.Sid, identity.Members, QueryMembership.None))
                            {
                               //do something with the users
                            }
            
            TFS API is very simple and intuitive, and in next post I'll explain some work item related methods.

            Haha, How to develop software.

            This is a nice one. Click Full screen mode and enjoy

            Re-visit my article on Architecture Considerations, it might be interesting.

            ADO.NET data services, WCF and Entity Framework


            This weekend I was doing some digging around ADO.NET data services, WCF and Entity Framework
            ADO.NET Data Services:
            You can use ADO.NET Data services (you need SP1) to expose your Entity framework over the wire, with almost zero code. But as I understand, the only limitation is, the transaction is over HTTP, and at this point, I can't find any solid way of exposing data services over net.tcp.

            That means, there is a small over head in terms of serialization (we all know binary serialization is faster), but the advantage is the speed of implementation for our services. We don't really need to write any services at all - You can just hook our validation and security logic around the data services and entity framework and we are done. Ideal if you are consuming data centric services over http - in scenarios like having a silverlight client, or a winform/wpf front end over http. Also on the con side - you should be aware that you can't put any serious business logic or work flow inside services 
            Exposing Entity Framework over WCF:
            With SP1, there is lot of support for employing entity framework in layered architectures. This includes support for eager loading and context management. Of course, in this case, you need to write the services (and the logic behind your methods). 
            Recommending you to read this MSDN article from John which provides an end to end example for demonstrating Entity framework with a layered architecture.
            Another alternative might be to use EFPocoAdapter , to have a plain POCO wrapper on top of the entity framework for dtos, instead of exposing entity framework classes directly. Right now it is a compass project for next version of Entity framework. 
            Performance Differences


            I got an unofficial word from John  on this - "Definitely more options with wcf. More work in most cases too. Astoria exposes entities easily. Perf diffs are negligible in most cases"

            Well, sounds interesting !!