MEF or Managed Extensibility Framework – Creating a Zoo and Animals

MEF or Managed Extensibility Framework is cool. Firstly, it allows you to decouple your components pretty easily. Secondly, it supports various component discovery scenarios, and enables you to write better frameworks. In this post, I’ll cover few basic aspects of MEF. You may also download the source code related to this article (Download Here), to have a look at the same as you read along.

MEF classes reside in the assembly System.ComponentModel.Composition.dll – Creating plug-in frameworks is quite easy with MEF. The main application can Import plug-ins, marked with an Export attribute.

MEF terminology is pretty simple. To start with, you can Export and Import your Parts. A Part is anything you export or import - be it a class, method, or property. Any such composable Part should be attributed with either the Export or Import attributes (You can find those attributes in System.ComponentModel.Composition namespace). For simple scenarios, you may use the Export attribute along with a Contract to mark your part as exportable.

Also, you may use the Import attribute to specify where you want to import the available exported parts. MEF will do the back ground work of dynamically discovering information about parts, to resolve and import them where ever you specify, based on the Contracts. This step is called Composing the Parts. MEF discovers information about these parts from various sources, i.e Catalogs, or you may add them directly to the container. For example - you may use an assembly catalog to point MEF to a specific assembly to grab the exported parts from there, a directory  catalog to point to a set of assemblies in a folder etc.

To make things straight, let us create a simple Zoo example with MEF, and we’ll cover MEF terminologies on the go.

Visiting the MEF Zoo

Alright, so to start with, assume that you are creating a Zoo application, where Animals can be ‘plugged-in’. I.e, if you are creating a new Animal, you don’t really need to rebuild your zoo. Needless to say – that means, your Animals will be loosely coupled with your Zoo.

We have the following projects in our MefZoo solution.

  • MefZoo.Lib – A simple library for keeping our contracts, to identify parts while exporting and importing them.
  • MefZoo.Animals – A couple of concrete animals for our Zoo.
  • MefZoo – Here is where most of the work happens – like grabbing parts from Catalogs, composing them etc.

image

In our MefZoo.Lib project, we’ve a simple IAnimal class. If any one need to create an Animal for your Zoo, IAnimal is the interface or contract they should use, to create their concrete Animal.

The IAnimal interface is pretty simple.

public interface IAnimal
    {
        string Name { get; }
    }

In MefZoo.Animals project, we have a reference to MefZoo.Lib. There we’ve a couple of ‘concrete’ animals. For now, let us have a Lion and Rabbit in our Zoo. If you are curios, here is the Lion and Rabit classes.

  
[Export(typeof(IAnimal))]
    public class Lion : IAnimal
    {
     public string Name
        {
            get { return "Lion1"; }
        }
    }

[Export(typeof(IAnimal))]
 public class Rabbit : IAnimal
    {
     public string Name
        {
            get { return "Rabbit1"; }
        }
    }

If you’ve observed, we are using the Export attribute to ‘export’ our animals, so that they can be ‘imported’ to our Zoo later. Time to visit our MefZoo project. We have a simple Zoo class there – and as you'd expect we’ve a collection of Animals there.

public class Zoo
    {
        [Import(typeof(IAnimal))]
        public IEnumerable<IAnimal> Animals { get; set; }
    }

And before we actually discuss about loading animals to the Zoo, you might want to note that we have the build path of MefZoo as ..\bin and that of MefZoo.Lib as ..\bin\Extensions. Essentially, you need to make sure MefZoo.Lib.dll will be under the Extensions folder in MefZoo.exe's path

Alright, now it’s time for the main action. Here is the Main method in Program.cs.

The Main method simply creates the Zoo object, and pass the same to LoadAnimals.
 static void Main(string[] args)
        {
            Zoo z=new Zoo();
            LoadAnimals(z);
           foreach (var animal in z.Animals)
                Console.WriteLine(animal.Name);
            Console.ReadLine();
        }

As explained earlier, to compose all these parts together, we need to

  1. Specify the catalogs from where these parts are coming.  If you have a look at the below code, you’ll find that we are pointing MEF to all libraries under the Extension folder of the main application, and also to the current assembly, for discovering the parts (Remember, anything that is marked with either Export or Import is a Composable Part).
  2. Create a container, and compose the parts
    static void LoadAnimals(Zoo zoo)
        {            
            try
            {
                //A catalog that can aggregate other catalogs
                var aggrCatalog = new AggregateCatalog();
                //A directory catalog, to load parts from dlls in the Extensions folder
                var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName
                    (Assembly.GetExecutingAssembly().Location) + "\\Extensions", "*.dll");
                //An assembly catalog to load information about part from this assembly
                var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

                aggrCatalog.Catalogs.Add(dirCatalog);
                aggrCatalog.Catalogs.Add(asmCatalog);

                //Create a container
                var container = new CompositionContainer(aggrCatalog);

                //Composing the parts
                container.ComposeParts(zoo);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
        }
At this point, if you run the application, you'll find the following output.
Lion1
Rabbit1

Feeding your MEF Animals

Now you have the Zoo, obviously the next problem is feeding your animals. For this, we’ll need our animals to make some grumble sound (a call back), to call the attention of zoo keepers. (If you are tired with story telling, this section will show you how to inject a call back mechanism to the loaded Animals). First of all, let us define a GiveFood method in our Zoo class. It is self explanatory. Only thing you might notice is, we are exporting GiveFood method as a part. How ever, we are using "AnimalFood" as the contract name, instead of a type. This is allowed, and valid in MEF – You can either use a string or a type, or both together, as a contract.

public class Zoo
    {
        [Import(typeof(IAnimal))]
        public IEnumerable<IAnimal> Animals { get; set; }

        [Export("AnimalFood")]
        public string GiveFood(string animalType)
        {
            switch (animalType.ToLower())
            {
                case "herbivores":
                    return "GreenGrass";
                case "carnivores":
                    return "Readmeat";
                default:
                    return "Waste";
            }
        }

    }
Now, we have the facility in our Zoo to give food to Animals. To enable our Animals to consume food, let us extend our IAnimal class a bit. Here is the new IAnimal class - We just added a delegate property, synonymous to the GiveFood method, so that MEF can hook up the GiveFood method later, when importing the exported GiveFood. 
public interface IAnimal
    {
        string Name { get; }
        Func<string ,string> GiveMeFood { get; set; }
    }

And well, let us re-wire the Lion class a bit, so that the Lion can periodically call back the zoo keeper to request some food.

 [Export(typeof(IAnimal))]
    public class Lion : IAnimal
    {
        Timer t;

        //MEF will inject the call back here
        [Import("AnimalFood")]
        public Func<string , string> GiveMeFood { get; set; }

        public string Name
        {
            get { return "Lion1"; }
        }

        //Let us use a timer to get food and eat it regularly
        public Lion()
        {
            t = new Timer(1000);
            t.Elapsed += (sender, args) =>
            {
                string food = GiveMeFood("carnivores");
                Console.WriteLine("Lion eating " + food);
            };
            t.Start();
        }       
    }
Nothing fancy there, we just have a timer there to make the Lion hungry. And let me do the same modifications for rabbit as well. Run the application, and you'll see Rabbit and Lion eating their food (The timer interval for rabbit is lesser than the lion).

image

Also, I just want to point that we havn’t made any modifications to the part composition code, for exporting a call back method for our Animals. One interesting aspect here is, the Zoo can decide what food to supply for each animal (probably based on available stock). And this is an example of how you can use MEF to achieve decoupling even in fine-grained systems.

You may also need to visit the official MEF site, http://www.codeplex.com/MEF

Shout it
Read more >>
In my previous post, I introduced Silverdraw, something that came out of my weekend hacks. Today I managed to push the source code of the same to Codeplex, and finished writing an article about the same in Codeproject






Silverdraw is realtime white board that can sync information between various participants, using Silverlight + WCF Polling Duplex. Presently this is a just a POC implementation. Users can draw together in the white board, and may chat each other. Here is a quick screen shot of the client running in two different browsers. These are the steps to start.


How to start


1 - Read this intro post in my blog
http://amazedsaint.blogspot.com/2009/11/silverlight-wcf-duplex-services.html

2- Take a live demo here - it may or may not work, the server is a bit leaky
http://silverdraw.com

3 - Read this codeproject article to help you understand the source
http://www.codeproject.com/KB/silverlight/silverdraw.aspx

4 - Get the source - Click downloads link in Codeplex to grab the source
http://silverdraw.codeplex.com

Enjoy, happy coding!!
Read more >>

Silverlight + WCF Polling Duplex Services = Awesomeness

Silver light + WCF Polling Duplex services enables you to write Silver light apps that can share information almost real time between users, over HTTP. Last weekend I started experimenting with Tomasz's pubsub sample - And again, this weekend, I ended up coding for the past 12-16 hours, and packaged together a not so bad Real time White board - Silver Draw -  where users can chat and even draw some primitive drawing.

If you are interested, here is the same. If my wife permits me to spend a couple of hours in front of my box this sunday, I'll do some quick refactoring to clean up the code a bit more- and may publish the source with another detailed article. In this Video, you may see I'm logging in from two different browsers, to do some dirty drawing that gets pumped to the other user.






I think recently there is lot of excitement about Google Wave, mainly because of it's ability to share information between various users real time, over HTTP. Real time information sharing is not new - but note that point - " over HTTP" - which makes it accessible to a wider audience.

(Some time back, to understand how Wave works, I even made a small Wave Robot based on Jon Skeet's API - Read about the same here if you missed it.)

Long point made short - If you are in MS camp, and if you are looking forward to develop RIA apps that can seamlessly share information between users real time, you may have a look at Silverlight + WCF Polling Duplex. I still need to explore scaling and performance related aspects


Read more >>
This post will give an introduction to JSON, and also I'll share a couple of handy C# extension methods to handle serialization and de-serialization of JSON (Java Script Object Notation) Data. from your Silverlight apps

To know more about JSON format, check out the http://www.json.org - To quote,
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. These properties make JSON an ideal data-interchange language.

Understanding JSON


In JSON, any object can be serialized to
  • A collection of name/value pairs. (For eg, from C# point of view, a simple example is Dictionary)
  • An ordered list of values. (An array or a list)
JSON is used widely by various web apps, and is ideal for light weight data transfer over REST protocol. For example, Twitter. The following URL gives you the current twitter trends as a JSON string.

URL: http://search.twitter.com/trends/current.json - You may get something like this as reply (I've shortened it a bit :)).

{ "as_of" : 1256965326,
  "trends" : { "2009-10-31 05:02:06" : 
         [ 
          { "name" : "Happy Halloween",
            "query" : "\"Happy Halloween\" OR #Halloween"
          },
          { "name" : "#foofighterslive",
            "query" : "#foofighterslive"
          },
          { "name" : "#Backnthedaycartoon",
            "query" : "#Backnthedaycartoon"
          },
          { "name" : "Follow Friday",
            "query" : "\"Follow Friday\""
          }
        ] }
}

And for your information, here is a quick Online Json Formatter to format your JSON data a bit so that it'll look pretty

JSON In Silverlight


JSON serialization support is provided in Silverlight for long time. Let us have a close look at how an object gets serialized to JSON. Consider a simple Human class.

 public class Human
    {
        public List Children { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

Let us create a simple Human object and try serializing the same.
  var human = new Human() { Name = "Joe", Age = 10 };

If you serialize the human object using JSON serializer, you'll get something like
{"Age":10,"Children":null,"Name":"Joe"}


You may find that each property/value is represented using a Key Value pair. Now, Let us try with an object graph.
  var human = new Human() 
                { 
                    Name = "Joe", Age = 30 ,
                    Children = new List<Human> 
                    {
                        new Human() {Name="Jim", Age=3},
                        new Human() {Name="July", Age=2}
                    }
                };
And here is the result if you serialize the human object now. Note how the elements in Children collection of human object is serialized and represented in JSON.
{ "Age" : 30,
  "Children" : [ { "Age" : 3,
        "Children" : null,
        "Name" : "Jim"
      },
      { "Age" : 2,
        "Children" : null,
        "Name" : "July"
      }
    ],
  "Name" : "Joe"
}

Serialization and De-Serialization In Silverlight


Now, let us get back to the initial point, how to serialize and deserialize objects to/from JSON in Silverlight? You may use these extension methods I've put together. They are pretty straight forward. The first method adds an extension method to strings for deserializing them, and the second one adds an extension methods to objects for serializing them.
using System;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;


namespace JSONHelper
{

    public static class JsonSerializerHelper
    {
        /// <summary>
        /// Adds an extension method to a string
        /// </summary>
        /// <typeparam name="TObj">The expected type of Object</typeparam>
        /// <param name="json">Json string data</param>
        /// <returns>The deserialized object graph</returns>
        public static TObj JsonDeserialize<TObj>(this string json)
        {
            using (MemoryStream mstream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = 
                         new DataContractJsonSerializer(typeof(TObj));

                return (TObj)serializer.ReadObject(mstream);
            }
        }

        /// <summary>
        /// Serialize the object to Json string
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>Serialized string</returns>
        public static string JsonSerialize(this object obj)
        {
            using (MemoryStream mstream = new MemoryStream())
            {
                DataContractJsonSerializer serializer =
                        new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(mstream, obj);
                mstream.Position = 0;

                using (StreamReader reader = new StreamReader(mstream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}


You may import JSONHelper namespace to use these extension methods, like this. Caution: Please make sure that you've valid JSON string or a serializable object when you use these methods
var human = new Human() 
{ 
    Name = "Joe", Age = 30 ,
    Children = new List 
    {
        new Human() {Name="Jim", Age=3},
        new Human() {Name="July", Age=2}
    }
};

//Serialize the object.
var hstr = human.JsonSerialize();

//Create a cloned object by deserializing the same
var cloned = hstr.JsonDeserialize<Human>();

Read more >>

Back To Basics - Anonymous Types In C# 3.0



About Back To Basics - It's often good to look back and fill any gaps we might be having, in certain aspects of the language or framework we use. I'll be examining and blogging about some well known features of C# and .NET, in Back To Basics series - Probably in a bit more detail.




This post is about the Anonymous types in C#, and the object initializer syntax.

It is well known that starting from C# 3.0, you can initialize an object like this.
var boy = new { Name = "Jim", Age = 2 };
You specify the properties of an object, and at compile time, the compiler will create a new (anonymous) type, with the properties you specify, and with a constructor that can take the same number of arguments.

Now, let us examine our anonymous type in detail by using reflection. We'll examine whether the type is a class, along with the type's name. If you run this,
static void Main(string[] args)
        {

            var boy = new { Name = "Jim", Age = 2 };

            Console.WriteLine("Name=" + boy.GetType().Name);
            Console.WriteLine("BaseType=" + boy.GetType().BaseType.Name);
            Console.WriteLine("Asm=" + boy.GetType().Assembly.FullName);
            Console.WriteLine("IsClass=" + boy.GetType().IsClass);
        }

You'll get some output like
Name=<>f__AnonymousType0`2
BaseType=Object
Asm=AnonymousTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
IsClass=True

Needless to say, the Name will be a random name, and the Assembly's name depends on your own project name. The key point is, we just established that the type is there in the assembly - which means, as I mentioned, the compiler created a type at compile time itself. You can have a look at the IL if you are interested.

Now, let us examine the observation that the anonymous type has a constructor that takes the same number of arguments as that of properties (i.e, in this case, the number of constructor arguments will be equal to the number of properties we specified in the object initializer, of types string and int). We can do that easily by creating a new instance of the anonymous type we have, using reflection. Add this to the tail end of the last piece of code.
//These two calls will fail with a run time exception, Just keep them commented
//var newboy = Activator.CreateInstance(boy.GetType(), null);
//var newboy = Activator.CreateInstance(boy.GetType(), new object[] { "Joe"});

//Only this will work. Creating a new boy
var newboy=Activator.CreateInstance(boy.GetType(),new object[]{"Joe",2});

//Just write back the name of new boy
Console.WriteLine(newboy.GetType().GetProperty("Name").GetValue(newobj, null));


You can see that only the last call will work, as we need to pass the same number of arguments while instantiating.

Note that you can have arrays of anonymous types as well, like this.
   var guys = new[]
            {
                    new {Name="Joe", Age=10},
                    new {Name="James", Age=22},
                    new {Name="Jim", Age=23},
                    new {Name="Jerard", Age=10},
            };

Further more, I just want to mention one more point. You may not need to assign the property explicitly, when you use the object initializer syntax. Consider this code.
            var guy1 = new { Name = "Ken", Age = 30 };
            var guy2 = new { guy1.Name, Age = 30 };

            Console.WriteLine(guy1.GetType().Name + " - " + guy1.Name);
            Console.WriteLine(guy2.GetType().Name + " - " + guy2.Name);


The key point to note here is, for guy 2, we are not explicitly specifying the Name property. Instead, we are just specifying that the name of Guy2 is same as Guy1. The compiler will assume the property name from the given parameter's name (in fact, the last part of the specified parameter, in this case 'Name') - This is called Projection. Obviously, you'll find that both guy1 and guy2 are of the same type as well.

Can you guess the output of this code as well?
            string Name = "Guy2";

            var guy1 = new { Name = "Ken", Age = 30 };
            var guy2 = new { Name, Age = 30 };

            Console.WriteLine(guy1.GetType().Name + " - " + guy1.Name);
            Console.WriteLine(guy2.GetType().Name + " - " + guy2.Name);


Why anonymous types are interesting? Because we use them in various ways, especially while using LINQ syntax. Here is a basic example

  var oldGuys = from guy in guys
                            where guy.Age > 20
                            select new { guy.Name };



Here, you'll probably find that we are using projection in the select new block. And as the last pointer, just debug and observe the type of oldGuys, and have a look at the base's type. I'll cover more on LINQ and Expression trees later.
Read more >>

Weekend Hacks - Surface SDK, Silverlight, Math and Data Visualizations




About Week End Hacks - Most weekends I do some digging around new and emerging technology and geek stuff. I do this by picking the links I bookmarked, or by going through the tweets I Favorited in Twitter.


For this Weekend, mostly these are the links I'll be going through.


  1. Anoop Madhusudananamazedsaint Here is where to download the Microsoft Surface SDK https://partner.surface.com... from web
  2. Jon Gallowayjongalloway Chris Harrison is consistently awesome. Scratch input is a recent example. http://www.chrisharrison.ne... from Witty
  3. Pete Cashmoremashable PhotoSketch: Photoshop + Image Recognition = Awesome - http://bit.ly/tBPKv from bit.ly
  4. Brad Abramsbrada Blog: Building The Basics: Silverlight 3, .NET RIA Services, & NHibernate (Fluent) http://bit.ly/2BGjrW from TweetDeck
  5. JoeStagnerMisfitGeek New blog post: http://tinyurl.com/yd2gpjk - SQL Azure Explorer for Visual Studio from API
  6. Google CodeGoogleCode Surf's up! Read the latest on Google Wave:http://bit.ly/207oXA (via @google) from Brizzly
  7. Dan WahlinDanWahlin RT @timheuer: A must watch video series on#channel9. Hear from @scottgu and others. Visual Studio-A documentary - http://bit.ly/1BtLG from TweetDeck
  8. Anoop Madhusudananamazedsaint APP Architecture Guide 2.0 book -http://www.codeplex.com/App... from web
  9. Scott Guthriescottgu New post from @Haacked about the new Auto HTML Encoding syntax coming w/ ASP.NET 4 Beta2:http://tinyurl.com/autoencode from web
  10. Anoop Madhusudananamazedsaint MIT Free online courses - http://bit.ly/QwD4J from web


Read more >>

Any software or technology, in it's final form, is expected to solve a business problem for an end user. And hence, it makes perfect sense to enable the end user to validate the requirements visually, before the actual construction - to ensure that there are no surprises in the end.

 
Yes, this sounds so obvious, but it is often amazing to see how teams neglect such a powerful technique like prototyping

Prototyping the user interfaces and workflows early enough will ensure
  • There are no frequent change requests and release time hotch-potch
  • Requirements are captured properly
  • There is clarity in functional scope (in scope and out of scope)
  • Analysis is good enough to start the construction phase.
Why you need Prototyping?

In most scenarios, customers are not really aware about what they need. Capturing the requirements also means working with the customer to envision the final system, and at times, to suggest possible alternatives.

Let us take an example. Assume that you have a whole-sale carrot distributor as your customer, who is owning the company "Thick Red Carrots" and he is having a requirement.
"I need a simple program to manage the distribution of carrots I purchase from my suppliers. I also need to view and track the location of all my sales guys in the field; to know the number of shops they are covering a day, and to track the number of carrots they are selling in each shop. I also need the software to give my tax statement from my sales data"

When you dissect the requirements for this 'simple' software - obviously you can see the scope is increasing. And after several rounds of discussions with your carrot whole seller, you understood the actual requirements - still on a high level.

Briefly, the system should include
  • A user management and payroll module to enter and manage sales staff details.
  • An allocation module to allocate a geographical boundary for each of his sales guys on a daily or weekly basis.
  • A module for interfacing with sales guys - the sales guys will use their mobile device to enter the collection data back to the system, from the field.
  • A supplier management module
  • A stock management module to track the in house stock, allocated stock etc to foresee and report possible stock deficits
  • Admin module to enter master data - including employees, stocks, suppliers, shops (customers) etc
  • Reports for reporting all this
You also found that you need to address specific conditions, like overlapping of sales regions, back-collection of damaged carrots etc. Gasp. Gasp. Gulp, Gulp.

Prototyping To Help

You have several challenges. To mention a few, you need to
  • Make sure your carrot seller understands the features required for the final system, so that he won't cry about the scope creep.
  • Ensure your design and development teams are understanding the requirements, so that they won't miss out any functionality, and at the same time they won't over engineer.
  • Ensure all workflows and specific business cases are documented
  • Ensure all customer expectations are clearly identified and captured (remember, the tax calculation part)
You turn to a white board, and start visualizing the screens and user actions. (For an illustration, I'm using http://www.balsamiq.com/ for some quick drawings). You decided that the main screen should allow easy navigation to all modules, and hence should be having a tabbed interface. The entry screen will display a summary of statistics, and will may have few quick links as shown.

You go further, and sketch up few individual screens as well, based on each requirement. To enable the end user to define sales regions, you might create a user interface with a map - so that the end user may draw a sales region with in the map, to specify the allocated stock for the sales guy to sell in that region, and the date of allocation.

With these sketches, you might goto your end customer, and take him through these screens. You might get straight forward comments like "The dashboard screen looks awesome, but I need to view my current stock there in numbers". Few comments might definitely alter the scope, like "I need to import my employee contacts from outlook".

And once the end customer agrees on the screen protoypes and how he may switch back and forth between them, you are good to pass it to your design and dev guys, to take it to the next step.

Another key point to have in the back of your mind - When you present the prototypes, make it clear that it is just a wire frame to demonstrate the functionality. And if possible, present a real life snapshot of atleast one of your screens, to clarify your point.

Tools for doing prototyping

There are various online and offline tools for doing prototyping. You can google around to find a few. I use Balsamiq for quick and static UI prototyping, http://www.balsamiq.com/ - and Microsoft Expression Sketchflow for some serious prototyping.

The good thing about Sketchflow is that it supports workflow prototyping and behaviour prototyping to some extent. What's catchy about Expression Sketchflow is its ability to provide a dynamic, 'clickable' interface for the user - so that the user can get a some what realistic experience.
Read more >>

After spending my last weekend hack on the API, I've rolled together my first simple .NET bot, the Bingy Bot. You can try Bingy either in the Google Wave Sandbox (add bingybot@appspot.com to your wave), or in these public test waves.


See Bingy in action.



Bingy bot answers user's questions, and even allows users to create FAQ waves collaboratively.

See this Google WAVE FAQ here, built by asking questions to Bingy.

If you've wave sand box access, you can invite bingybot@appspot.com to your wave.


Google Wave exposes an excellent API to create extensions, and to embed Waves. Some time back, I had a quick look towards the Wave Robot API, and thought it'll be great if I've a .NET client API to work on. So, when I saw Jon Skeet tweeted about his C# Wave Bot API Port some time back, I found it interesting.


About Bingy

Sing in the tune "Twinkle Twinkle.."

"Bingy Bingy what you say, How I wonder what you say,
Up above the bots of Wave, Like a wavelet in the Web"

A little bit of Irony here - Bingy bot tries to find answer for your questions using Bing APIs, and post it back if it knows. Type a question, like "what is an elephant?" or just key in a flight number to get the status. Bingy will answer if it knows. Bingy interfaces with Bing using the XML APIs to do instant searches. I'll spend more time on Bingy to make it smarter, so that it can process tokens, and give better information other than flight status etc.

Though Jon has a well written tutorial (his code itself is simple enough to start hacking), I'll post a detailed example with my experiments with the wave bot api, specifically on the Bing interfacing. As I already mentioned, the best part of Bingy is that it is implemented in .NET.


Basically, a python proxy is hosted in google app engine that routes all calls to your custom domain. These steps are already mentioned in Jon's wiki post. I'll upload the code soon so that this can be a reference point for a first cut implementation.

Resources For You To Start With


Here are a couple of references
By the time you start exploring the wave model, I'll write another detailed post about the implementation of Bingy, with source code.
Here is the code for embedding the wave if you like. But no guarantee that I'll continue to host it for another 10 years!!
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> 
  <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <title>Bingy Bot Wave Test</title> 
    <script src="http://wave-api.appspot.com/public/embed.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
    function initialize() {
      var wavePanel = new WavePanel('http://wave.google.com/a/wavesandbox.com/');
      wavePanel.loadWave('wavesandbox.com!w+4T_YGl-u%BH');
      wavePanel.init(document.getElementById('waveframe'));
    }
    </script> 
  </head> 
  <body onload="initialize()" style="background:white"> 
  <font face="arial"> 
    <h1>bingybot@appspot.com</h1> 
    <div id="waveframe" style="width: 100%; height: 90%;background:white"></div> 
  </body> 
  </font> 
</html>
Read more >>
About .NET 4.0 Series - I'll be covering various aspects of .NET 4.0 and related technologies in these posts


In my previous post and related article, I gave a quick introduction towards creating and using your own custom dynamic types, inheriting from the DynamicObject class.

.NET framework 4.0 has a cool new ExpandoObject class, in System.Dynamic namespace. What makes this special is, it allows you to create an object with members that can be dynamically added and removed at run time. To clarify the point, have a look at this example.

  
            dynamic obj = new ExpandoObject();
            obj.Value = 10;
            var action = new Action<string >((line) => Console.WriteLine(line));
            obj.WriteNow = action;
            obj.WriteNow(obj.Value.ToString());
And you'll get 10 as output in your console. As you can see, the property 'Value' and method 'WriteNow' is attached at runtime, when the invocation happens.

The objective of this post is to examine how the ExpandoObject itself is implemented. To make this clear, let us create a MyExpando class, a minimal implementation of ExpandoObject.

We are inheriting MyExpando class from the DynamicObject, and these are the major methods we are overriding.

  • TrySetMember- Provides the implementation of setting a member.
  • TryGetMember-Provides the implementation of getting a member.
  • TryInvokeMember- Provides the implementation of calling a member.
  • GetDynamicMemberNames- Returns the enumeration of all dynamic member names.

And Here is our minimal MyExpando class, inherited from DynamicObject, and overrides the above methods.
  public class MyExpando : DynamicObject
    {

        private Dictionary < string, object > _members = new Dictionary < string, object > ();


        /// 
        /// When a new property is set, add the property name and value to the dictionary
        ///      
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (!_members.ContainsKey(binder.Name))
                _members.Add(binder.Name, value);
            else
                _members[binder.Name] = value;

            return true;
        }

        /// 
        /// When user accesses something, return the value if we have it
        ///       
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_members.ContainsKey(binder.Name))
            {
                result = _members[binder.Name];
                return true;
            }
            else
            {
                return base.TryGetMember(binder, out result);
            }
        }

        /// 
        /// If a property value is a delegate, invoke it
        ///      
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if (_members.ContainsKey(binder.Name) && _members[binder.Name] is Delegate)
            {
                result = (_members[binder.Name] as Delegate).DynamicInvoke(args);
                return true;
            }
            else
            {
                return base.TryInvokeMember(binder, args, out result);
            }
        }


        /// 
        /// Return all dynamic member names
        /// 
        /// 
        public override IEnumerable&ltstring> GetDynamicMemberNames()
        {
            return _members.Keys;
        }
    }
When ever a property set operation happens, the runtime will invoke TrySetMember, and there, we are pushing the property name and value to a dictionary. Similarly, when ever a get operation happens (TryGetMember), we are simply returning the value object if available in the dictionary. Also, when a method call is made (TryInvokeMember), if the value type is a delegate, we just invoke the same by passing the arguments we received. Pretty simple, huh?

Well, that is it. Now, let us try the above scenario with our MyExpando object

           dynamic obj = new MyExpando();
            obj.Value = 10;
            var action = new Action((line) => Console.WriteLine(line));
            obj.WriteNow = action;
            obj.WriteNow(obj.Value.ToString());
Run the application, and you'll get 10 as output. Cool :)
Read more >>

Fun with Dynamic Objects and MEF in C# 4.0





About .NET 4.0 Series - I'll be covering various aspects of .NET 4.0 and related technologies in these posts

C# 4.0 introduced the dynamic keyword, to support dynamic typing. If you assign an object to a dynamic type variable (like dynamic myvar=new MyObj() ), all method calls, property invocations and operator invocations on myvar will be delayed till the run time, and the compiler won't perform any type checks for myvar at compile time.

So, if you do something like myvar.SomethingInvalid(); it is valid at compile time, but invalid at runtime if the object you assigned to myvar doesn't have a SomethingInvalid() method.
The System.Dynamic namespace has various classes for supporting dynamic programming, mainly the DynamicObject class from which you can derive your own classes to do run time dispatching yourself.

A couple of points to note.
  • A dynamic call will be slower for the first time, and your calls will be jited and cached if possible for subsequent calls. As a first step, the DLR checks the cache to see if the given action has already been bound wrt to the arguments. If not, the DLR checks to see if the receiver is an IDynamicObject, and if so, asks the receiver to bind the action. If the receiver is not an IDO, then DLR calls into the language binder (i.e, the C# runtime binder), and cache this.
  • C#'s underlying type system has not changed in 4.0. As long as you are not using dynamic keyword, you are still statically typed (i.e, the types are known for the compiler at compile time).
  • Error handling when you use dynamic features is a bit difficult and can't be very specific, as you don't know much about the foreign objects to which you dispatch the calls.
Recently, I published this article in Codeproject; 
This article demonstrates a couple of interesting techniques, including.
  • Creating a dynamic wrapper around the file system so that we can access Files and Directories as properties/members of a dynamic object
  • A way to attach custom Methods and operators to our dynamic wrapper class and dispatch them to a plug in sub system.

Read more >>

MVVM - Binding Multiple Radio Buttons To a single Enum Property in WPF

I had a property in my View Model, of an Enum type, and wanted to bind multiple radio buttons to this.

Firstly, I wrote a simple Enum to Bool converter, like this.

public class EnumToBoolConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, 
            Type targetType, object parameter, 
            System.Globalization.CultureInfo culture) 
        { 
            if (parameter.Equals(value)) 
                return true; 
            else 
                return false; 
        } 

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            return parameter; 

        } 
        #endregion 

    }


And my enumeration is like

public enum CompanyTypes
    {
        Type1Comp,
        Type2Comp,
        Type3Comp
    }
Now, in my XAML, I provided the enumeration as the ConverterParameter, of the Converter we wrote earlier, like
<Window x:Class="WpfTestRadioButtons.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTestRadioButtons"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:EnumToBoolConverter x:Key="EBConverter"/>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <RadioButton IsChecked="{Binding Path=Type, 
                Converter={StaticResource EBConverter}, 
                ConverterParameter={x:Static local:CompanyTypes.Type1Comp}}" Content="Type1"/>
            <RadioButton IsChecked="{Binding Path=Type, 
                Converter={StaticResource EBConverter}, 
                ConverterParameter={x:Static local:CompanyTypes.Type2Comp}}" Content="Type2"/>
        </StackPanel>

    </Grid>
</Window>


Now, in the view model, I exposed a property named Type, which is of the CompanyEnum type. Like,
public CompanyTypes Type 
        {
            get
            {
                return _type;
            }
            set
            {
                _type = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Type"));

            }
        }
And it seems that I'm pretty much done. Alternatively, you can use the same idea to pass an integer, but in that case, you need to change the converter a bit. See the NumToBool converter I mentioned earlier :)
Read more >>

Creating an Operating System using C#



Have you ever wrote an Operating System, even if it is very simple? If you've ever tried, you know that it is a fun thing to do.



Long time back, in college, when I was doing my diploma and later my B-Tech graduation in Computer Science, I remember most of us got fascinated and inspired by the Linux kernel - and eventually most of us rolled out our own simple boot loaders and Operating Systems!!


And most of us used Asm + C. As C is a very low level language - you can do a lot of things directly. Any of the C library methods (like malloc, printf, crlscr etc) need to be implemented first, to invoke them from C




I'll give an example below.


Let us see how the C library methods are implemented under the hood. We'll go with a clrscr example. When you implement such methods, you'll access system devices directly. For ex, for clrscr (clearing the screen) we know that the video memory is resident at 0xB8000. Hence, to write to screen or to clear it, we start by assigning a pointer to that location.
In video.c
void clrscr()
{

   unsigned char *vidmem = (unsigned char *)0xB8000;
   const long size = 80*25;
   long loop;

   for (loop=0; loop<size; loop++) {
      *vidmem++ = 0;
      *vidmem++ = 0xF;
   }
}
Let us write our mini kernel now. This will clear the screen when the control is handed over to our 'kernel' from the boot loader. In main.c
void main()
{
   clrscr();
   for(;;);
}
To compile our 'kernel', you might use gcc to compile it to a pure bin format.
gcc -ffreestanding -c main.c -o main.o
gcc -c video.c -o video.o
ld -e _main -Ttext 0x1000 -o kernel.o main.o video.o
ld -i -e _main -Ttext 0x1000 -o kernel.o main.o video.o
objcopy -R .note -R .comment -S -O binary kernel.o kernel.bin
If you noticed the ld parameters above, you see that we are specifying the default load location of your Kernel as 0x1000. Now, you need to create a boot loader. From your boot loader logic, you might want to pass control to your Kernel, like
jump 08h:01000h
You normally write your boot loader logic in Asm. Even before that, you may need to have a look at how a PC Boots - Click Here.
Better start with a tinier Operating system to explore. See this Roll Your Own OS Tutorial
An Operating System in C#??
Now, what about writing an Operating System in C#? I recently came across Cosmos, an excellent "Operating System Project". A cool idea. After you install the Cosmos User Kit, you create a Cosmos boot project in Visual Studio, and run it.

Cosmos includes a compiler IL2CPU which'll convert your IL code to x86 code on the fly (it generates raw asm files and later uses NASM to assemble the same). The build task will also create a boot disk for you, to boot your OS from various emulators. Here you can see Cosmos running from my Virtual PC




After you install the Cosmos user kit, you can Create a new Cosmos boot project from Visual Studio's New Project dialog box. I just went ahead and wrote some code in the Init method in the Program.cs file.

  
       // Main entry point of the kernel
        public static void Init()
        {
            Cosmos.Kernel.Boot.Default();
            Console.WriteLine("Hi, From Amazedsaint Cosmos");
            Cosmos.Kernel.TextScreen.NewLine();
            Cosmos.Kernel.TextScreen.SetColors(ConsoleColor.Red, ConsoleColor.White);
            Console.WriteLine("Something red");
  
            while (true)
                ;
        }

Run the project, and what is more interesting is the behind the scenes work the build will do for you. It'll show you a dialog box, so that you can choose from various build options. In my case, I've selected to deploy the 'OS' to Microsoft VPC.



If you want to take it to the next level, have a look at Cosmos source code, in Codeplex - http://cosmos.codeplex.com/. Also, you might find this developer documentation handy.

In fact, I blogged earlier a bit about Cosmos and few other interesting projects. Check out that post also, if you find this interesting.

Read more >>

Weekend Hacks - Cool Links For Silverlight, CLR, VS2010




About Week End Hacks - Most weekends I do some digging around new and emerging technology and geek stuff. I do this by picking the links I bookmarked, or by going through the tweets I Favorited in Twitter.



Links I explored this weekend.

Read more >>


About Back To Basics - It's often good to look back and fill any gaps we might be having, in certain aspects of the language or framework we use. I'll be examining and blogging about some well known features of C# and .NET, in Back To Basics series - Probably in a bit more detail.






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<string> Skills { get; set; }

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

            Name = name;
            Skills = new List<string>();
        }

        //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<ITrainable>
        public static IEnumerable<ITrainable>
            Train(this IEnumerable<ITrainable> 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<ITrainable>
            Do(this IEnumerable<ITrainable> 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<ITrainable>{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!!
Read more >>
top