Before we begin - these are few random thoughts and speculations on the possibilities of having a Silverlight Operating System.

If Google can think about an Operating System on top of Linux + Chrome, why Microsoft can’t think about a Silverlight OS, probably on top of MinWin? Especially for Atom PCs, Handheld devices, IP TVs etc. This might be already there in the cards – I don’t know. Just want to take a step back and see what all revelations are happening around the Silverlight + Cloud technology stack, and where that may lead us (the Microsoft developers).

From Net Books To Mobiles To IP TVs  image

Silverlight has emerged a lot in the last couple of years. As I see it, the investment going towards improving Silverlight in an astonishing speed has various reasons.

  1. RIA is growing, RIA is big. Silverlight provides a great RIA platform for Microsoft developers, and this will help Microsoft to combat the efforts from Google and Adobe.
  2. Silverlight is Microsoft’s Trojan horse to get into the Mac world (and to other platforms like Linux if Moonlight is going to click). By providing the entire range of .NET services combined with Azure, you can build first class applications that runs both in Mac and Windows on top of Silverlight, with cloud as the back end.
  3. Very soon we’ll see Silverlight for Mobile, and it is going to be huge. Literally. Silverlight itself is capable enough to serve as a first class alternative run time for Mobile devices, especially with it’s rich UI capabilities and media support. And Silverlight + Cloud can do wonders to mobile computing.
  4. And finally, why not a stand alone, bootable Silverlight Operating System? Probably a Silverlight Runtime implementation on top of MinWin? (Microsoft has created a stripped-down version of the Windows core recently, called MinWin – and MinWin is going to be at the heart of all the new versions of Windows, including embedded Windows [Details] )

Silverlight In Mobile

Recently, I’ve seen a lot of posts about Microsoft’s ‘foolish strategy’ in the Mobile space. And the recent Windows Mobile 6.5 wasn’t a revelation. How ever, I don’t think Microsoft is just concentrating on revamping their mobile OS alone. Of course, the story goes like Microsoft is completely rebuilding their Mobile OS – but along with that, it seems like a considerable investment is also flowing towards porting Silverlight runtime to various mobile platforms, and probably building a new generation apps on top of the Silverlight + Services stack.

I won’t be surprised if Microsoft will announce Silverlight support for few leading mobile platforms in near future (Symbian? Android?) , along with the Windows Mobile 7.0 release.  And along with that, Silverlight platform is also about to get a whole lot of exciting new features with the 4.0 release – including extended out of the browser capabilities, support for Microphone and Cam etc – and you can easily see Silverlight is going to be ‘the platform’ of choice for development in near future, for disconnected apps.

So naturally, when all these things click together, it’ll be of great appeal to the existing Microsoft developers.

Silverlight vs. Chrome Frame

Recently Google released Chrome Frame, to ‘enable open web technologies’ in Internet Explorer. Microsoft, on the other side, announced ‘official’ support for Silverlight on Google Chrome. Just as Microsoft need to push Silverlight to various platforms to increase the adoption of their .NET stack, it is Google’s necessity to push their high performance Java Script run time to opponent platforms.

Observing from another perspective, Google is moving ahead with JavaScript as the primary choice for client side development, complemented by frameworks like Google Gears + their high performance V8 engine that is included in Google Chrome and Chrome Frame. And Microsoft is moving towards a unified .NET stack.

How ever, as we all know “building, reusing, and maintaining large JavaScript code bases and AJAX components can be difficult and fragile” – and this is a gap Google is trying to iron out with Java based frameworks like Google Web Kit.

How ever, Microsoft’s Silverlight platform has a definite edge, because of it’s enhanced media and streaming capabilities, support for a rich development platform, and ability to seamlessly interact with the cloud and application services on top of that (Remember the Live, CRM and SharePoint services). And as I see it, the idea of a ‘Silverlight OS’ will become a real hit – not just for net books, but even for devices like IP TVs, hand held devices and so on.

A Note on Live Mesh

If you’ve noted, Live Mesh desktop is already there – it is a kind of online desktop, and you can use it across your devices, if your device supports Silverlight runtime. And you may even use the Live Framework SDK to develop applications/gadgets for your Live Desktop, I just scratched the surface of the SDK over last weekend.

How ever, when it comes to portable devices, I think it makes sense to have a ‘bootable’ Silverlight OS, with a built in desktop, and few utility apps. And vendors can even build their shell apps by consuming the rich UI framework of the SL runtime. And I’m sure that a lot of vendors might be interested to provide net books that hosts only customized apps for their on field employees (probably with cloud as the back end) on top of the light weight Silverlight stack.

And finally, from Microsoft’s point of view, such an OS can really unify the user experiences across devices including Zune, Windows Mobile etc. Platform teams can just focus on porting the run time to specific devices, while high level user facing applications can be developed on top of the Silverlight platform. So I guess, a natural evolution for Silverlight will be, towards a stand alone, light weight OS for mini devices!!

To conclude, these are few random thoughts and speculations, mixed with a little bit of imagination– never mind too much!!

Shout it
Read more >>

Before you being, you may Read Part I and Part II 

Soon after writing my last post on LINQ to Events, I thought about creating a quick text template to automatically generate those GetEventName wrapper methods – so that we don’t end up in hand coding those GetMouseDown(), GetMouseMove() and all again. You may use it to quickly generate extension methods to create event to observable wrappers for a specific type. Here we go. Click 'view plain' to grab the source code

Add a new text file to your project, and name it EventWrapperGen.ttinclude
<#+

  //Generate the Event wrappers to create an observable from
  //an event

 //Generate a GetEventName wrapper method for events in this type
 void GenerateEventGetters(Type type)
   {
       
       var events = type.GetEvents();

       foreach (var e in events)
       {
           Type tDelegate = e.EventHandlerType;
           var parameters=GetDelegateParameterTypes(tDelegate);
			
			 if (parameters.Length==2 
                       && typeof(EventArgs).IsAssignableFrom(parameters[1]))
           {

	#>
			
   public static IObservable<Event<<#=parameters[1].Name#>>> 
   						Get<#=e.Name#> (this <#=type.Name#> el)
   {                        
       var allevents = 
			Observable.FromEvent<<#=GetCorrectTypeName(tDelegate)#>, 
						<#=parameters[1].Name#>>
           (   h => new <#=GetCorrectTypeName(tDelegate)#>(h), 
               h => el.<#=e.Name#> += h, 
               h=> el.<#=e.Name#> -= h
            );

       return allevents;            
   }
			
	<#+
			
			}

       }
       
   }

	//Get the parameter types for delegates
   private Type[] GetDelegateParameterTypes(Type d)
   {
       if (d.BaseType != typeof(MulticastDelegate))
           throw new ApplicationException("Not a delegate.");

       MethodInfo invoke = d.GetMethod("Invoke");
       if (invoke == null)
           throw new ApplicationException("Not a delegate.");

       ParameterInfo[] parameters = invoke.GetParameters();
       Type[] typeParameters = new Type[parameters.Length];
       for (int i = 0; i < parameters.Length; i++)
       {
           typeParameters[i] = parameters[i].ParameterType;
       }
       return typeParameters;
   }

	//Get the delegate return type
   private Type GetDelegateReturnType(Type d)
   {
       if (d.BaseType != typeof(MulticastDelegate))
           throw new ApplicationException("Not a delegate.");

       MethodInfo invoke = d.GetMethod("Invoke");
       if (invoke == null)
           throw new ApplicationException("Not a delegate.");

       return invoke.ReturnType;
   }
		
	// Fixes up a Generic Type name so that it displays properly for output.
    public static string GetCorrectTypeName(Type genericType)
        {

			var fullTypeName=false;
            if (!genericType.IsGenericType) return genericType.Name;

            //Make sure the type is indeed generic in which case the` is in the name
            int index = genericType.Name.IndexOf("`");
            if (index == -1)
            {
                if (!fullTypeName)
                    return genericType.Name;

                return genericType.Namespace + "." + genericType.Name;
            }

            // Strip off the Genric postfix
            string TypeName = genericType.Name.Substring(0, index);
            string formatted = TypeName;

            //Parse the generic type arguments
            Type[] genericArgs = genericType.GetGenericArguments();
            string genericOutput = "<";
            bool Start = true;
            foreach (Type arg in genericArgs)
            {
                if (Start)
                {
                    genericOutput += arg.Name;
                    Start = false;
                }
                else
                    genericOutput += "," + arg.Name;
            }

            genericOutput += ">";
            formatted += genericOutput;

            if (!fullTypeName)
                return formatted;
            return genericType.Namespace + "." + formatted;
        }

#>
And now, add a new tt file UIElementExtensions.tt to your project, and import the above include file as below. Make sure the Custom Tool property of the tt file is set to TextTemplatingFileGenerator.
<#@ template 
inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" 
language="C#v3.5" debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="System.dll" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="System.Windows.Forms.dll" #>
<#@ Assembly Name="WindowsBase.dll" #>
<#@ Assembly Name="PresentationFramework.dll" #>
<#@ Assembly Name="PresentationCore.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Windows" #>
<#@ import namespace="System.Windows.Controls" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Collections.Generic" #> 

<#@include file="EventWrapperGen.ttinclude" #>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Reflection;
using System.Diagnostics;


namespace ReactiveExtensions 
{

public static class <#=typeof(UIElement).Name#>Extensions 
{

	<#
	GenerateEventGetters(typeof(UIElement));
	#>

}

}

You can replace the UIElement type above with any type, to generate the related extension methods. If you havn’t yet done, Read Part I and Part II as well.  Enjoy Coding!!

Shout it
Read more >>

In my last post, I gave a high level overview about .NET Reactive Extensions (Rx), Push and Pull data sequences, and creating Observables from .NET events. In this post, we’ll explore more Observables from Events, and the ‘LINQ to Event’ aspect. We’ll create a small drawing application in WPF in declarative style. You may want to download the related source code to play with

A note on the source code. I’m using the System.Reactive.dll, that I rebased to .NET CLR using Reflexil. It is just for demo purposes, and is not expected to include in your production deployments.

Event To Observables

To recap, as described in my last post, you may use the Observable.FromEvent method to create Observables from events and subscribe to them, like,

var allKeyDowns = Observable.FromEvent<KeyEventHandler, KeyEventArgs>
                (   h => new KeyEventHandler(h), 
                    h => el.KeyDown += h, 
                    h=> el.KeyDown -= h
                 );

As we’ve seen earlier, allKeyDowns is an Observable, of type IObservable<Event<KeyEventArgs>> .

It is a good practice to wrap the creation of an observable from an event in an extension method. Let us create a handy GetKeyDown() extension method to create an Observable from the key down event, for any UI Element.

public static class UIElementExtensions 
 {							
      public static IObservable<Event<KeyEventArgs>> GetKeyDown 
                                                      (this UIElement el)
        {                        
            var allKeyDowns = Observable.FromEvent<KeyEventHandler, KeyEventArgs>
                (   h => new KeyEventHandler(h), 
                    h => el.KeyDown += h, 
                    h=> el.KeyDown -= h
                 );

            return  allKeyDowns;            
        }
}				

Also, you may easily abstract this out. For example, assume that you are building a racing game, and you might need to subscribe only to Arrow Key downs. You may create an extension method GetArrowKeyDown the arrow key down events. 

      //Get the arrow keys down only
       public static IObservable<Event<KeyEventArgs>> GetArrowKeyDown
				(this UIElement el)
       {
	   var arrows = new List<Key> 
                               { Key.Left, Key.Right, Key.Up, Key.Down };
	   var arrowsPressed = from kd in el.GetKeyDown()
				 where arrows.Contains(kd.EventArgs.Key)
				 select kd;
	   return arrowsPressed;

       }	

    //---- 
  
    //Some where in your main application

    var arrowPressed=this.GetArrowKeyDown();
    arrowPressed.Subscribe(arrow=>MessageBox.Show
                    (arrow.EventArgs.Key.ToString() + " Pressed!!")); 

 

Sequencing the events

Let us create a simple drawing application, so that when the user drags, we draw a red line from the initial mouse down position to the current location, and also a blue spot at the current location. Here is what I mean :)

image

And we’ll do the same in a declarative manner, instead of doing it the classical way. Assuming that you have the extension methods GetMouseUp, GetMouseDown, and GetMouseMove for the corresponding Mouse Events, let us see how to handle a drag operation, in a declarative manner. You may see how simple this approach is - instead of having event handlers sprinkled every where

//A draw on drag method to perform the draw
void DrawOnDrag(Canvas e)
        {

            //Get the initial position and dragged points using LINQ to Events
            var mouseDragPoints = from md in e.GetMouseDown()
                                  let startpos=md.EventArgs.GetPosition(e)
                                  from mm in e.GetMouseMove().Until(e.GetMouseUp())
                                  select new
                                  {
                                      StartPos = startpos,
                                      CurrentPos = mm.EventArgs.GetPosition(e),
                                  };


            //Subscribe and draw a line from start position to current position
            mouseDragPoints.Subscribe
                (item =>
                {
                    e.Children.Add(new Line()
                    {
                        Stroke = Brushes.Red,
                        X1 = item.StartPos.X,
                        X2 = item.CurrentPos.X,
                        Y1 = item.StartPos.Y,
                        Y2 = item.CurrentPos.Y
                    });

                    var ellipse = new Ellipse()
                    {
                        Stroke = Brushes.Blue,
                        StrokeThickness = 10,
                        Fill = Brushes.Blue
                    };
                    Canvas.SetLeft(ellipse, item.CurrentPos.X);
                    Canvas.SetTop(ellipse, item.CurrentPos.Y);
                    e.Children.Add(ellipse);
                }
                );
        }

 image

One very interesting point there - we are running a LINQ query against the observables, and creating a new observable of an anonymous type that has two properties, StartPos and CurrentPos. If you examine the type of mouseDragPoints, you'll see this >.

And here are the related GetEventName wrapper methods, for MouseUp, MoveMove and MouseDown. You may read more about Observable.FromEvent method we use below in my previous post about .NET Rx, if you havn't yet read that.

 public static class UIElementExtensions 
{
 
  public static IObservable<Event<MouseButtonEventArgs>> 
                                      GetMouseUp (this UIElement el)
        {                        
            var allevents = Observable.FromEvent<MouseButtonEventHandler, MouseButtonEventArgs>
                (   h => new MouseButtonEventHandler(h), 
                    h => el.MouseUp += h, 
                    h=> el.MouseUp -= h
                 );

            return allevents;            
        }
		
						
   public static IObservable<Event<MouseButtonEventArgs>> 
                                      GetMouseDown (this UIElement el)
	{                        
		var allevents = Observable.FromEvent<MouseButtonEventHandler, MouseButtonEventArgs>
			(   h => new MouseButtonEventHandler(h), 
				h => el.MouseDown += h, 
				h=> el.MouseDown -= h
			 );

		return allevents;            
	}		
	
 public static IObservable<Event<MouseEventArgs>> 
                               GetMouseMove (this UIElement el)
        {                        
            var allevents = Observable.FromEvent<MouseEventHandler, MouseEventArgs>
                (   h => new MouseEventHandler(h), 
                    h => el.MouseMove += h, 
                    h=> el.MouseMove -= h
                 );

            return allevents;            
        }	
		
}

If you havn’t yet done, read my other posts on .NET Rx as well. Also, have a look at this T4 template to generate all those GetEventName wrapper methods for a given type.

 

Enjoy coding!!

Shout it
Read more >>

Recently, a lot of interest is bubbling up in the .NET community about reactive programming. This weekend I played around with this, and created a couple of POCs to get a feel. And I'm loving everything. Reactive extensions (Rx) is really cool, as it introduces lot of new possibilities. The .NET Rx or .NET Reactive extensions (System.Reactive.dll) recently appeared in the latest Silverlight tool kit drop. 

.NET Rx introduces two interfaces, IObservable and IObserver that "provides an alternative to using input and output adapters as the producer and consumer of event sources and sinks" and this will soon become the de-facto for writing asynchronous code in a declarative manner. Also, .NET Rx gives greater freedom to compose new events – you can create specific events out of general events. Let us see these aspects in a bit more detail.

Push and Pull Sequences

Here is a quick recap on Reactive programming - Consider a small example, result = var1 + var2. In a normal scenario, we expect the value of result to be independent of the variables, var1 and var2. Later the values of var1 and var2 might change, but the value of result may remain the same as it was at the time of the initial assignment.

But in a reactive scenario, the value of result is dependant on one or more of the variables we used to compute it’s value. i.e the value of, result would change or evolve over a period of time, based on the changes that might happen to var1 or/and var2.

Event based programming and asynchronous call backs are existing ways of doing Reactive programming in .NET. Consider how you handle a simple MouseMove operation in .NET using an event handler. Let us take a step back, and examine this a bit closer - The mouse cursor’s location value is changing over a period of time, and an event notifies you about that – or the source is pushing the value to you.

image

You may see the data we receive from these events as pieces of data that your event handler (the target) receive from a source over a period of time – a sequence. Also, you may instantly notice that the same is happening when you iterate over a collection, probably using a for loop. In that case too, you are receiving values from a source over a period of time, you are pulling the data. In both cases, the target is receiving the pieces of data from a source over a period of time, the difference is that the program is either pulling the data (a pull sequence) or the source or environment is pushing the data to the program (a push sequence).

What’s cool about .NET Rx?

.NET Rx team (this is not an official name) found that any push sequence can be viewed as a pull sequence as well – or they are Dual in nature. So this also means, there is a Duality between Iterator pattern IEnumerable/IEnumerator (pull) and Observable pattern (push) IObservable/IObserver.

So what is cool about about this duality? Anything you do with Pull sequences (read declarative style coding) is applicable to push sequences as well. Here are few aspects.

  • You can create Observables from existing events, enumerables etc  and then use them as first class citizens in .NET – i.e, you may create an observable from an event, and expose the same as a property.
  • As IObservable is the mathematical dual of IEnumerable, .NET Rx facilitates LINQ over push sequences like Events, much like LINQ over IEnumerables
  • It gives greater freedom to compose new events – you can create specific events out of general events.
  • .NET Rx introduces two interfaces, IObservable<T> and IObserver<T> that "provides an alternative to using input and output adapters as the producer and consumer of event sources and sinks"

If you want to dive a bit more deep in to this, watch this video where Eric Meijer explaining this duality. .NET Rx provides various extension methods for creating observables from Events, Enumerables etc.

Turning Events to Observables

The FromEvent method in System.Linq.Observable class will create an Observable, from  an event. This example shows how to create a observer for the Mouse left button down event, for a given control

  var mouseLeftDown=Observable.FromEvent<MouseButtonEventArgs>
          (mycontrol,"MouseLeftButtonDown");

The above example uses the following FromEvent extension method overload, in the Observable class

        public static IObservable<Event<TEventArgs>> 
	 	FromEvent<TEventArgs>(object target, string eventName) 
			where TEventArgs : EventArgs;

Now, as the event is an observable, we can subscribe to the same

mouseLeftDown.Subscribe
 (arg => Console.WriteLine(arg.EventArgs.ButtonState.ToString()));
Also, another overload for FromEvent exits in Observable class to convert an event to an Observable.
public static IObservable<Event<TEventArgs>> FromEvent<TDelegate,
                    TEventArgs>(Func<EventHandler<TEventArgs>, 
                             TDelegate> conversion, 
                             Action<TDelegate> addHandler, 
                             Action<TDelegate> removeHandler) 
			    where TEventArgs : EventArgs;

You may use this overload for explicitly specifying the event argument type and event handler type, and to enable compile time verification for the event name. Like,
 var mouseLeftDown= Observable.FromEvent<MouseButtonEventHandler, MouseButtonEventArgs>
                (   h => new MouseButtonEventHandler(h), 
                    h => el.MouseLeftButtonDown += h, 
                    h=> el.MouseLeftButtonDown -= h
                 );
Please notice that the type of mouseLeftDown is IObservable<Event<MouseButtonEventArgs>>. And as we discussed above, it is very much possible to use the mouseLeftDown variable they way you need. For example, you may pass mouseLeftDown to this method, where we again abstract out another Observable  just for the points, and subscribe to the same – and note that we use LINQ to do the same.
  
public void SubscribePoints
          (IObservable<Event<MouseButtonEventArgs>> mouseEvents)
{
	var points = from ev in mouseEvents
				 select ev.EventArgs.GetPosition(this);
	points.Subscribe(p => this.Title = "Location ="
                                     	+ p.X + "," + p.Y);
}
 

Further Reads

Shout it
Read more >>

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. image

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
    {
        [ImportMany(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
    {
        [ImportMany(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

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.

The application has two parts:

  1. Server - A WCF service with a polling duplex end point for clients to register, to publish information, and to receive notifications.
  2. Client - A Silverlight client that consumes the end point to register the user, to publish the user's drawing, and to receive and plot the drawing data from other users.

The server side web service interface (IDuplexDrawService) has these important methods:

  • Register - A client may call this to register itself to a conversation.
  • Draw - A client may call this to request the server to pump the drawing information to other clients in the conversation
  • NotifyClients - From the Draw method, we'll invoke NotifyClients to iterate the registered clients, to publish the data.

Also, as we are using Polling Duplex, we need a callback interface too - so that the server can 'call back' or notify the clients. (In Polling Duplex, you may need to note that what is happening is not actually a direct callback from server to client. The client should poll the server periodically over HTTP to fetch any possible information that the server is willing to pass to the client, to simulate a callback.) Anyway, our 'call back' service interface (IDuplexDrawCallback) has a Notify method, for the server to notify the rest of the clients when some client calls the Draw method.

So, in short - a party may publish some information using 'Draw', and others can subscribe to the published information. This is a simple implementation of the Publisher/Subscriber pattern.

When you load the client the first time, you'll be asked for a username to join the session. From there, the logic goes something like:

In client-side:

  • The client will try to connect to the service end point.
  • If success, the client will register itself with the client, by calling the Register method, and by passing the username.
  • The client will hook up a few event handlers in the proxy. Mainly, the NotifyCompleted event. NotifyCompleted will be fired each time you receive a callback from the server.

In server-side:

  • Inside the Register method, the server will grab the client's session ID and callback channel from the current operation context, and add it to a list.
  • Whenever a client submits information by calling 'Draw', the server will pump this information by iterating each registered client, and by calling their 'Notify' method.

 

How To Start:

  1. Read this intro post in my blog, watch this video
  2. Take a live demo here – Silverdraw.com
  3. Read this codeproject article to help you understand the source in detail
  4. Get the source - Click downloads link in Codeplex to grab the source 



Enjoy, happy coding!!
 
Shout it
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 >>

top