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

Share |

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

Share |

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

Share |

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

Share |

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

Share |
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 >>

Share |

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

Share |
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 (J avaScript 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)</STRING,STRING>
  • 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>();

Alright, that is it for now. Enjoy coding.

 

Shout it
Read more >>

Share |

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.
Shout it
Read more >>

Share |

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

Share |

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

Share |

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>

 

Enjoy, happy coding!!

Shout it
Read more >>

Share |

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 guess what you get!!


Shout it
Read more >>

Share |

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

Share |

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

Share |

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

Share |

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

Share |


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!!


Shout it
Read more >>

Share |

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.
Read more >>

Share |

Weekend Hacks - .NET Soup for the passionate Soul




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.


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 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
Read more >>

Share |

Skillset required for working in a Silverlight Project


Recently I was requested by the sourcing team to list down the skill set required for candidates for a Silverlight project. Here is something that I wrote as Job Descriptions, for each role.
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
Read more >>

Share |

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
Read more >>

Share |

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}}"/>
Read more >>

Share |

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.
Read more >>

Share |

Back To Basics - Thinking Beyond ToString()



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.




If you want to convert something to string, you might need to find the converter to do the job correctly.

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.
Read more >>

Share |
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
Read more >>

Share |

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.
Read more >>

Share |

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.

Read more >>

Share |

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 !!





Read more >>

Share |

Stack Overflow Spamming

I got almost annoyed with the continuous spamming (still happening at the time of writing) at Stack Overflow. More than anything else, this seems like a limitation with the system itself, which don't seem to have any built in support for preventing spamming.



Well, I know this is very easy to say this, than doing - I also know Jeff and all are not short of ideas, but here are few quick features we need in Stack Overflow asap, so that a lot of us can still continue using that.

The message contained abusive text, but from the behavior,  I infer it is pretty human, it is not an automated bot.


Here are few thoughts
1 - User should not be able to ask more than one question per minute
2 - If user asks more than a limited number of questions in a short time, captcha should be shown
3 - Check for abusive words in the input, and if found a multiple times, suspend that user automatically for some time
4 - If a number of users are getting created from same IP, prevent the activity for some time
Calling @CodingHorror to do something urgently


Update: Seems like SO is working good now, after being down for some ten minutes. The spamming trend lasted for close to 30 minutes, and then Pretty good recovery, but need to think how to prevent this in future.
Read more >>

Share |
top