Top 5 Common programming mistakes .NET developers must avoid !!

image Some time back, I asked a question in Stackoverflow.com, about common programming mistakes .NET developers must avoid. The response was awesome, to say the least. I’m just listing down the top 5 developer crimes I picked, from the answers I received (regardless the votes).

1. Breaking the stack unnecessarily when you re-throw an exception

This a pretty ‘old thing’ - but surprisingly, still a very common mistake. As TheSoftwareJedi mentioned, you don’t really need to break the stack while throwing exceptions. I’ve done this myself when I was a beginner - and I’ve seen this more often than anything else when I do code reviews these days.

To clarify the point - What is the difference between

try { ..} catch (Exception ex) { throw ex; }

and 

try {..} catch(Exception ex) { throw; }  ?

image

And when you lose the stack trace, you can’t debug your app – and even worse, you can’t log your error details properly to your error log.

The MSDN guidelines on exception handling clearly states

Do not rethrow by throwing the same exception object.  This causes the stack trace for the original exception to be lost--use a lone "throw;" statement (without an object following it) to "rethrow" a catch exception.

2. Not using using to dispose objects

When ever you initialize an IDisposable object, it is a good practice to initiate it in a using statement to ensure the object is getting disposed properly, like this.

image

Most developers won’t do that. Greg Dean pointed the same.

image

Here is a little bit of re-cap from MSDN

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and it also causes the object itself to go out of scope as soon as Dispose is called. Within the usingblock, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

Also, do you know that a using statement is expanded by the compiler to a try{..} finally{..} block at compile time? Read more tips about using statement in MSDN.

3. Not unhooking event handlers appropriately after wiring them.

I think Scott Langham brought up a great point about not unhooking event handlers. People don’t really ‘remember’ to unhook events.

image

In C#, when you register an event handler, you are creating a strong reference from the event source to the listener. So, the listener won’t get garbage collected even if you don’t have any pointers to the listener - unless you unhook the event by yourself, and this might even result in a memory leak.

So, if you are thinking about how to deal with situations where your  Source is having a longer life span than the listener – there are multiple ways to deal with it, and Daniel Grunwald covers them nicely in this excellent Codeproject Post.

4. Forgetting that Strings are immutable

In .NET, we know that strings are immutable – which means, once a string is created, its value can’t be changed. All string operations you perform, actually returns a new string containing the modification.

John Sonmez have a nice point with an example.

image

5. Not Overriding GetHashCode when overriding Equals method in C#

Why this is important? If Hashcode of two items does not match, they’ll be never considered equal, and the Equals method will never be called to execute your custom comparison logic – let us say, in scenarios where your objects are used as a key in a dictionary or so. Hence, in first place, you should override GetHashCode and return the same value for two equal objects based on comparison logic. I’ve seen this a couple of times during code review.

So, though Mark Gravell has several interesting points in his answer, my pick is about not overriding GetHashCode when you override Equals method in C#.

image

 

You may read my other Back To Basics posts here, you may find them interesting.

 

Note: As mentioned, these are my favorite picks of common problems, with some custom commentary. I suggest you to go through the entire thread here in Stack Overflow if you are interested. Happy coding!!

Shout it
Read more >>

Share |

What is LINQ to Events a.k.a RX Framework?

I received a mail some time back, asking me to “clarify in simple words the concept of LINQ to Events”. This is a quick post on LINQ to Events a.k.a the RX Framework, and the objective of this post is to high light some of my previous posts on the same topic.

NET Rx team (this is not an official name) found that any push sequence (events, callbacks) can be viewed as a pull sequence (as we normally do while accessing enumerables) as well – or they are Dual in nature. In short observer/observable pattern is the dual of enumeration pattern.

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 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 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. Here is a quick example.

image 

You may go through my previous posts as well to get the head and tail in detail. Also have a look at the related source code as well.

Shout it
Read more >>

Share |

The objective of this article series is to give a quick overview of Behaviors, Triggers and Actions in Silverlight and WPF.  Together, they enable a great deal of design time interactivity for your UI. They also make possible re-use and re-distribution of interaction logic. This is the second article in the series, and I’ll explain about Triggers and Actions. Also, we’ll explore how to create custom triggers.

Note: In this post, we’ll be playing around with Microsoft Expression Blend 4.0 beta a bit, to help us understand the concepts further. So, if you don’t have Blend 4.0 beta,

The completed source code for this exercise is available

 

Triggers and Actions – Scratching the Surface

A Trigger can invoke a set of Actions, when it is fired. For example, you can nest few actions (like PropertyChangeAction to change a property of an element) in an EventTrigger, so that those actions will get executed when a specific Event occurs. You can attach more than one trigger to an element.

If you have some WPF background, you may quickly remember the DataTriggers, MultiDataTriggers etc.

There are various Triggers and Actions that comes ‘out of the box’, residing in System.Windows.Interactivity and Microsoft.Expression.Interactions 

  • Triggers – EventTrigger, TimerTrigger, StoryBoardCompletedTrigger, KeyTrigger etc.
  • Actions - ChangePropertyAction, ControlStoryBoardAction, PlaySoundAction etc.

Let us start playing with some of the existing triggers and actions.

1.  Set The Stage - Create a new Silverlight Application Project in Blend (as explained in my previous post). You’ll see the design surface of MainPage.xaml by default. This time, select the Ellipse tool from Blend toolbar, to draw a ball to the design surface. Give some nice color as well :)

image

Also, at this point, click View->Active Document View->Split View – So that you can view the Xaml along with the designer.

2. Attach a Trigger and Action to an object – Go to the Assets pane in Blend, and click the Behaviors link. Drag the ChangePropertyAction to the ellipse you added, and have a look at the XAML. You’ll find that Blend automatically added an EventTrigger for you with MouseLeftButtonDown as the default event, and sandwiched your ChangePropertyAction inside the same.

image

 

Select the ChangePropertyAction in the Xaml Editor or in the Object and Timelines window. Have a look at the properties Window in blend, to see the properties of your Trigger and Action (See the image below). By default the trigger will be fired for the MouseLeftButtonDown event of our ball. Also, you may note that presently we havn’t specified any parameters for the ChangePropertyAction.

image

3.  Modifying ChangePropertyAction image

Now let us squeeze our ellipse a bit by changing the Width property of our Ellipse - when the MouseLeftButtonDown happens. For this, go to the properties window, and

 

1. Change ‘PropertyName’ parameter of our ChangePropertyAction to ‘Width’.

2. Set the the value to 200 so that Width will increase to 200 when the Action is invoked

3. In the Animation Properties of ChangePropertyAction, set the duration to 4 seconds, and change the Ease property to Elastic Out.

We are done. Run the application, by pressing F5 and move click over the Ellipse. And you’ll see a bit of fun.

Play around with this a bit, to understand how the Triggers and Actions work together. And once you are back, scroll down to read further – about creating our very own Triggers and Actions

 

Creating a Custom Trigger

Time to go under the skin.  Then, we’ll replace the ‘EventTrigger’ we used in our above example with the custom trigger we are creating, to stretch the ball!!.

First, let us create a minimal custom trigger – named KeyDownTrigger, that’ll be fired each time when a key is pressed. Let us continue from where we left our above project.

Step 1 – Create a Trigger: In Blend, right click your project in the Projects pane, and click ‘Add New Item’, to bring up the New Item dialog box. Select ‘Trigger’ from there, give the name ‘KeyDownTrigger’ and click OK.

image

Step 2 – Add some meat. Have a look at the New trigger class that got added to your project. You’ll find that our Trigger class is inherited from TriggerBase<T> in System.Windows.Interactivity. Also, have a look at the override methods, OnAttached and OnDetaching (and the comments below them). Let us add some meat to the code you already see there. Modify the code to this.

Tip: If you have Visual Studio 2010 Beta installed, you can right click on a file in Blend 4.0 project explorer, and click ‘Edit in Visual Studio’ at any point of time, if you prefer writing code in VS rather than in Blend.

public class KeyDownTrigger : TriggerBase<FrameworkElement>
	{
		protected override void OnAttached()
		{
	         base.OnAttached();
	       // Insert code that you want to run when the Trigger is attached to an object.
             this.AssociatedObject.Loaded += (sender, args) =>
            {
                Application.Current.RootVisual.KeyDown +=
                    new KeyEventHandler(Visual_KeyDown);
            };
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();
			// Insert code that you would want run when the Trigger
			//is removed from an object.
            Application.Current.RootVisual.KeyDown -= 
				new KeyEventHandler(Visual_KeyDown);
        }

        //A property for the trigger so that users can specify keys
        //as comma separated values
        public string Keys { get; set; }

        //Invoke the actions in this trigger, if a key is in the list
        void Visual_KeyDown(object sender, KeyEventArgs args)
        {
            var key = Enum.GetName(typeof(Key), args.Key);

            if (Keys.Split(',').Contains(key))
                InvokeActions(key);
        }
    }

The code is self explanatory, but here is basically what we are doing there. When the Associated object is loaded, we hook up to the KeyDown event of the Root visual element. And when KeyDown is fired, we Invoke the Actions inside this trigger, if the key is entered by the user.

Step 3 – Associate the KeyDownTrigger to our Ball.

In Blend, click Project->Build Project menu. Now, go back to our MainPage.xaml where you have your ball. As we did earlier, Select the ChangePropertyAction in the Xaml Editor or in the Object and Timelines window, to bring up the Properties Window - as we did earlier. In the Properties window, Click the ‘New’ button against the TriggerType, in the Trigger Pane (see the image). In the resultant dialog box, select the ‘KeyDownTrigger’ we recently added, and click OK.

image

 

Now, you’ll see that the ‘EventTrigger’ we had there earlier, got replaced with the ‘KeyDownTrigger’. Note that the ‘Keys’ property we added to our Trigger class is visible in the Blend UI - so that some one who may use our trigger can enter the values there to specify what all keys should invoke the actions inside the trigger. Just enter few key names with out spaces (let us say A,B,C) to the Keys field.

image

 

Step 4 – Salvation

Cool, we are done. Press F5 and run your project. Click on the surface to bring focus, and press A,B or C to see the ball getting stretched. Woot!! We just created and implemented a minimal trigger.

Shout it
Read more >>

Share |

The objective of this article series is to give a quick overview of Behaviors, Triggers and Actions in Silverlight and WPF. Together, they enable a great deal of design time interactivity for your UI. They also make possible re-use and re-distribution of interaction logic. This is the first article in the series, and I’ll explain about Behaviors and creating custom behaviors.

Note: In this post, we’ll be playing around with Microsoft Expression Blend 4.0 beta a bit, to help us understand the concepts further. So, if you don’t have Blend 4.0 beta,

Note: Why this post? After publishing my Silverlight and WPF interaction frameworks, Silverlight Experimental Hacks (Slex)  and WPF Experimental Hacks (Wex), I got a number of requests from the community to write few simple posts on these topics, introducing the basic concepts. So here we go.

Behaviors – Scratching the Surface

A behavior is something you attach to an element, modifying the way how the element should present itself, or how the element should respond to user interactions. First, Let us add an existing behavior to an object to see how behaviors work. Later we’ll create a custom behavior and may use the same from Blend.

Step 1. Let us start with a simple Silverlight application. Fire up Expression Blend 4.0 beta, and click File->New to select a Silverlight 4.0 application, and click OK.

image

Step 2. Once you have the project created, just add a rectangle to your MainPage.xaml canvas, and give it a nice back ground color using the color picker (I gave blue:)). Also, at this point, click View->Active Document View->Split View – So that you can view the Xaml along with the designer. You may also press F5 and run the project if you want, and make sure you can’t drag the rectangle around as of now ;).

image

Step 3. Now, our objective is to attach a dragging behavior to our rectangle, so that it can be dragged around by the user in the screen. For this, we’ll attach the MouseDragElementBehaviour to our rectangle. To do this, go to the Assets tab in Blend (See the arrow below), and Click the Behaviors label. Now, from the right pane of the Assets tab, drag and drop MouseDragElementBehaviour to your rectangle. Press F5 and run the project, and you see that you’ll be able to drag your element any where.

image

Step 4. Let us take a step back here, and have a look at the XAML. You’ll see the MouseDragElementBehaviour added to the Behaviors attached property of our dumb little rectangle.

image

Behind the scenes

The System.Windows.Interactivity infrastructure (initially introduced in Blend 3) simplifies the creation of Behaviors, triggers and actions.

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:il="clr-namespace:Microsoft.Expression.Interactivity.Layout;assembly=Microsoft.Expression.Interactions"

The System.Windows.Interactivity namespace has multiple classes to inherit from and to create your own Behavours, triggers and actions. The WPF and Silverlight versions are present at C:\Program Files\Microsoft SDKs\Expression\YourBlendVersion\Interactivity\Libraries. In the same folder, you’ll also find the Microsoft.ExpressionBlend.Interactions.dll which hosts various concrete behaviours and triggers, like the MouseDragElementBehaviour we just applied.

If you have a look at the MouseDragElementBehavior using Reflector, you’ll find that MouseDragElementBehaviour is inherited from the Behaviour<T> abstract class in System.Windows.Interactivity.

image

Creating your own Behaviors

So, let us create a custom behavior. 

Step 1 – Create a Behavior. In Blend, right click your project in the Projects pane, and click ‘Add New Item’, to bring up the New Item dialog box. Select Behavior from there, give a nice name and click OK.

image

Step 2 – See what is inside. Have a look at the New behavior class that got added to your project. You’ll find that our Behavior class is inherited from Behavior<T> in System.Windows.Interactivity as discussed earlier. Also, have a look at the override methods, OnAttached and OnDetaching (and the comments below them).

image

Step 3 – Add some meat. And what we should do in the Behavior? Let us tilt the object a bit, when the mouse moves over an object with this Behavior applied. Just modify OnAttached to have the following code. The AssociatedObject property of the Behavior will provide the current object context, to which this behavior is applied. Let us hook the MouseEnter and MouseLeave events, so that we’ll apply a simple projection to the object when the mouse moves over, and reset the project when the mouse leaves the object.

image

Step 4 – Rebuild. Now, click Project->Build Project in Expression Blend menu. And goto the Assets window again and click Behaviors to view MyBehavior there. Just drag and drop the behavior to your object. See that the new behavior is added to our Rectangle in Xaml as well.

image

 

Step 5 – Run. You are done. Press F5 and run your project, and see that when you move your mouse over the rectangle to start the dragging, the rectangle is getting a bit tilted.

 

Continue reading - Part II - Behaviors, Triggers and Actions in Silverlight And WPF Made Simple – Triggers

Shout it
Read more >>

Share |

Some time back, I posted about the Silverlight Extensibility hacks Preview 2.0. I did a quick port of the code base to WPF under the name WEX or WPF Extensibility hacks, and now you have the goodness in .NET 3.5 + VS 2008

image

Just want to have a quick word on what is available. Here are a couple of points about Wex. Wex is built on top of System.Windows.Interactivity infrastructure.

  • Wex allows you to define multiple conditions for invoking triggers (like you can specify a KeyDown event trigger should be fired only if ‘A’ is pressed)
  • You can specify multiple conditions for invoking each action in a trigger
  • Wex introduces few more Triggers and Actions that you’ll see soon.

As of now, Wex Preview 1 Provides the following Triggers

  • EventTrigger – Will be fired when an event is raised. Can listen to events of Elements, or events from your view model
  • ReactiveTrigger – Can ‘import’ an Observable that you may ‘export’ using MEF. Useful to define and use custom events using System.Reactive.

And the following actions

  • InvokeMethodAction – Invoke a method directly in the View model or for a target element, supports passing parameters via Xaml
  • InvokeCommandAction – Invoke an ICommand in the view model
  • StoryBoardAction – Start, Stop, Pause, Resume, or Reverse story boards
  • PropertyAction – Sets a property value (very crude as of now)

Event Trigger

You can hook up the event trigger against your view model, or against an element. For example, assume you want to invoke a command in your view model based on various conditions – let us say, when the user presses the key ‘A’, and if and only if a check box is checked. Here we go

image

Reactive Trigger

The concept of reactive trigger is based on the System.Reactive (LINQ to Events) framework and Managed Extensibility Framework. Basically, you can create an event definition, and import that as an event for a control.

Your exported event definition should match the signature Func<object,IObservable<EventResult>>. You can use the ObservableExport attribute in Wex.Lib to mark your trigger as an exportable part. Also, the name you provide to the ExportName attribute will be later used in Xaml to ‘import’ this trigger.

image

Step 2 – In your application startup, call Compose method in WexPartComposer, and pass your catalogs

In this case I’m simply passing and assembly catalog with the current assembly, because I’ve my trigger as part of my host app. And I’ve this line in the App.xaml.cs constructor.

image

Step 3 – Just use the trigger in your Xaml

Here we go, you can import the exported trigger, and this will get fired when ever a key is pressed.

image

You might have guessed this, but you can create very customized event definitions using System.Reactive. For example, here is how to create an event definition if you want the trigger to fire only when the arrow keys are pressed.

image 

You can read this article on Reactive Extensions, to understand more on this

Actions in Wex

You might have already noticed in the above examples, how to use the actions like InvokeCommandAction, StoryBoardAction etc. What is interesting is, Wex allows you to fire actions based on conditions (See the EventTrigger example where we are specifying the InvokingConditions for the actions.

I specifically want to comment on the InvokeMethodAction in Slex, that allows you to Invoke a method in view model directly. Here we go. Assume that you have an Add method in your view model, like this.

image

Now, this is how to invoke the add method, passing some parameters. Here, we pass the text in txt1 and txt2 as parameters.

image 

A Quick Overview

Have a sneak peak at the actual implementation of Wex. If you examine the Trigger hierarchy, you’ll find that we’ve a WexTrigger abstract base class, from where other triggers are getting inherited.

  • WexTrigger - The base class for all Wex framework triggers
  • EventBasedTrigger - A base class for inheriting event based triggers
  • ObserverTrigger - An abstract class for creating triggers based on an Observable (System.Reactive)

WexTrigger directly inherits from System.Windows.Interactivity.TriggerBase<DependencyObject>. I’m not going to explain the System.Windows.Interactivity infrastructure and how each trigger is implemented, but you can definitely go through the source code and find the same yourself. Probably I’ll explain implementation details in future posts.

 

Triggers

      Actions

Now, let us have a quick look at the Actions involved. Have a look at the actions in the framework. WexTriggerAction is inherited from System.Windows.Interactivity.TriggerAction<FrameworkElement>, and from there on, you can go and explore as of now if you’ld like to :)

Conclusion

As I mentioned, Wex is a quick port of Slex, and seriously, there are lot of areas I still need to re-write to leverage what is already available in WPF (Especially on dependency property hooking and all). How ever, I thought it might be good if I bring out a first cut, so that you can also hack around with me, and leverage some of these concepts in your own apps.

And you may hit few bugs with this Preview, fix it yourself or wait for the Preview 2. But please give feedback!!

Enjoy Coding!!

Shout it
Read more >>

Share |

Silverlight Powered Wearable Locket

Can I have a call with all the Project Natal, Win Mob and Silverlight guys to tell them, “Guys, let us get this thing out by next month”?

 

image

Shout it
Read more >>

Share |

In my last post on Dependency Properties (Read here), I explained how to  listen for dependency property change notification of a UI Element. image

Here is a more ‘refined’ extension method - so that you can listen to Property change notifications of a source - by creating and registering a ‘listener’ dependency property in your class ('owner') and setting up a binding with the ‘source’ object. Remember that starting from Silverlight 4.0, you can even have dependency objects as the source.

This is useful when you create your own Silverlight Behaviors, triggers or actions. For example, you may want to listen to the property change notification of an element - to Invoke your trigger when the property value of the ‘source’ changes.

 

    public static class DependencyPropertyHelper 
    {
        /// <summary>
        /// Listen for change of a property of the source, 
        /// and callback the same to the context via the callback
        /// </summary>

        public static System.Windows.DependencyProperty RegisterForNotification
            (this DependencyObject owner, object source,
            string propertyPath, PropertyChangedCallback callback)
        {

            return RegisterForNotification(owner, source, propertyPath, callback, false);

        }

        /// <summary>
        /// Listen for change of a property of the source, 
        /// and callback the same to the context via the callback.
        /// Creates a two way binding if you specify 'twoway' to true
        /// </summary>
        /// <param name="propertyPath"></param>
        /// <param name="element"></param>
        public static System.Windows.DependencyProperty RegisterForNotification
            (this DependencyObject owner, object source,
            string propertyPath, PropertyChangedCallback callback, bool twoWay)
        {

            //Bind to a depedency property
            Binding b = new Binding(propertyPath) { Source = source, Mode = BindingMode.OneWay };
            if (twoWay) b.Mode = BindingMode.TwoWay;

            var prop = System.Windows.DependencyProperty.RegisterAttached(
                "Listener" + propertyPath + DateTime.Now.Ticks,
                typeof(object),
                owner.GetType(),
                new System.Windows.PropertyMetadata(callback));

            BindingOperations.SetBinding(owner, prop, b);

            return prop;

        }
    }

And now, from your 'owner' class (say, from your trigger or behavior class), you can set up a binding to a source like this.

//Register for notification some where
this.RegisterForNotification
    (Source, this.Property, OnPropertyValueChanged);

//...

/// Callback invoked when the property changes
private void OnListenAttachedPropertyChanged(DependencyObject dependencyObject,
      DependencyPropertyChangedEventArgs eventArgs)
   {
           //Do stuff here
   }

If you want to update the source property value to which you are binding, you might want specify that the twoway parameter is true when invoking RegisterForNotification - and keep the dependency property created for updating the value, later like

targetDP =this.RegisterForNotification
              (Target, this.Property, OnPropertyValueChanged, true);


//Later, set the value some where
 SetValue(targetDP, Value);

 

You may find the DependencyPropertyHelper class and a related PropertyChangedTrigger implementation here in Slex project - http://slex.codeplex.com

Shout it
Read more >>

Share |

Couple of weeks back,  I introduced the Slex Project. And thanks to the Christmas holidays; today I checked in the Preview 2 of Slex. Here are few cool features in Slex Preview 2. You can download the same here from CodePlex – http://slex.codeplex.com

 

What is there in Slex?

If you are familiar with Silverlight/Expression Blend, you should be knowing about the System.Windows.Interactions infrastructure – which provides various Behaviors, Triggers and Actions. Slex is an experimental implementation of some additional triggers and actions on top of the same, along with few extension points.

image

 

Triggers in Slex, and actions inside them, can be invoked based on conditions

image

These are some notable aspects in Slex, that are not available in the triggers and actions available with Expression Blend.

  • Slex allows you to define multiple conditions for invoking triggers (like you can specify a KeyDown event trigger should be fired only if ‘A’ is pressed)
  • You can specify multiple conditions for invoking each action in a trigger
  • Slex introduces few more Triggers and Actions that you’ll see soon.

As of now, Slex Preview 2 Provides the following Triggers

  • EventTrigger – Will be fired when an event is raised. Can listen to events of Elements, or events from your view model
  • PropertyTrigger – Will be fired when the specified property changes. Can listen to properties of Elements, or property in your view model
  • ReactiveTrigger – Can ‘import’ an Observable that you may ‘export’ using MEF. Useful to define and use custom events using System.Reactive.

And the following actions

  • InvokeMethodAction – Invoke a method directly in the View model or for a target element, supports passing parameters via Xaml
  • InvokeCommandAction – Invoke an ICommand in the view model
  • StoryBoardAction – Start, Stop, Pause, Resume, or Reverse story boards
  • PropertyAction – Sets a property value (very crude as of now)

You can specify one or more InvokingCondition for triggers and/or actions. Also, actions like InvokeMethodAction and InvokeCommandAction has an ActionParameters property, so that you can pass one or more Parameters when invoking methods and commands.

 

Conditionally Invoking Triggers and Actions

Let us see a simple example on a scenario – You need to start a story board when a button is pressed, but you need to do that only if a particular checkbox is checked. Assuming your Button is btnBegin, your StoryBoard is myStoryBoard and your checkbox is chkMain, this is something that you can do. (See the StoryBoardAction demo)

image

If you see the above code, you may find that we are specifying various conditions for the trigger itself – all Actions in the Trigger will fire only if all Invoking Conditions are True. You should be able to place other Actions (that comes with Expression Blend, you own custom actions etc) with in an EventTrigger, PropertyTrigger or ReactiveTrigger – to execute them conditionally.

Also, you may need to specify conditions for invoking each Action in the trigger individually. You can do this as well. For example, the following Property Trigger will execute only if the Text property of the Textbox txtData is Hello, and the checkbox myCheckBox is checked.

image

 

Better MVVM - Invoking Methods and Commands in your View Model and Passing parameters

Have a look at the InvokeMethodAction and InvokeCommandAction (see the demo). There are some changes for these actions from Preview 1.

InvokeCommandAction let you invoke a method against the view model. Assume that you’ve a list box named userList - here is a simple example on how to execute a command when ever the selection is changed, and you can specify a parameter for your ICommand using the ActionParameter. In fact, you can pass more than one ActionParameter – and in that case, they will be passed as an object array to the CanExecute and Execute methods in your command.

 

image

And here is something more interesting - InvokeMethodAction. You can use InvokeMethodAction to invoke methods in your view model directly. Assume that you have a UI with two text boxes and a button, and you’ve an Add method in your view model that takes two arguments of type integer. This is what you need to do to invoke your Add method, when the user clicks the button btnName.

image

 

ReactiveTrigger – Decoupling Triggers with the help of MEF and System.Reactive

One interesting addition in this preview is the ReactiveTrigger. ReactiveTrigger let you import an Observable you exported from some where else. This will let you create customized user input triggers pretty quickly. I’m not going to the implementation details, but assuming you are already familiar a bit with MEF concepts and System.Reactive concepts, here is what you can do (See ReactiveTrigger demo in the Slex.Lib.Demo for entire source code)

Step 1 – Some where in your host application, Create a trigger and export it

Your exported method should match the signature Func<object,IObservable<EventResult>>. You can use the ObservableExport attribute in Slex.Lib to mark your trigger as an exportable part. Also, the name you provide to the ExportName attribute will be later used in Xaml to ‘import’ this trigger.

image

Step 2 – In your application startup, call Compose method in SlexPartComposer, and pass your catalogs

In this case I’m simply passing and assembly catalog with the current assembly, because I’ve my trigger as part of my host app. And I’ve this line in the App.xaml.cs constructor.

image

Step 3 – Just use the trigger in your Xaml

Here we go, you can import the exported trigger, and this will get fired when ever a key is pressed.

image

 

Using Slex with Blend

You should be able to use Blend to modify most Slex triggers and actions. For example, let us see how the above Event Trigger and related action parameters will look like in Blend. You may find that you can modify the Conditions and Parameters of a trigger from with in Blend (Well, they are AttachableCollections to be precise :)).

 

image

 

 

How Slex relates to the already available Behaviors, Triggers, and actions that comes with Expression Blend?

As mentioned earlier, Slex is built on top of System.Windows.Interactions infrastructure, and you will be able to use mix and match existing Expression Blend behaviors, triggers and actions along with Slex triggers and actions.

There are few overlapping areas – For example, Slex has its own implementation for some triggers like EventTrigger, that provides some ‘extra’ features when compared to Blend’s EventTrigger.

 

Slex is very much in a preview stage, and I’ll continue hacking on this with respect to my time.

Shout it
Read more >>

Share |

K-MUG (Kerala Microsoft Users Group) Meet - Dec 19th 2009, Tvm

Plan to attend the K-MUG UG Session, this Dec 19th, Technopark, Kerala. Along with Praveen and Ratheesh, I'll be talking about C# 4.0, .NET Reactive Extensions, and Managed Extensibility framework.

Details below.






Date/Time: 19-Dec-2009 @9:30 AM- 12:30 PM



Venue:
UST Global, Bhavani,
Technopark, Trivandrum, Kerala

Speakers & Topics

Ratish Naroor

Senior .NET Developer / SEO Expert

Social Media

Search Engine Optimization / Search Engine Marketing
Social Media Marketing
Blogging

Anoop Madhusudanan

Solution Architect at UST Global

C# 4.0 and Silverlight


VS2010 + C# 4.0 features, including dynamic programming
LINQ to Events
Managed Extensibility framework
Silverlight 4.0 features.

Registration:
Event is Free, but limited seats. Please register here and ensure you bring the confirmation ticket.




Read more >>

Share |

For the last couple of week ends, I was hacking around Silverlight interactions and behaviors. Mainly, the objective was to learn the Interactivity system in depth, and in the process, I’ve done few interesting hacks.

And thus born Slex project, Silverlight Experimental hacks. :). Slex is built on top of System.Windows.Interactivity framework, and supports a couple of interesting Triggers and Actions.

This is the intro screen of the related demo, and I’ll explain a bit on each item. The download link is towards the end of this post.

 

image

 

As an introduction, here are few cool things you can already do with Slex.

1 – Simple example of an Event Trigger in Slex

Assume that you need invoke a command, when an event is fired. You can do the same by hooking up an InvokeCommandAction inside an EventTrigger (Note that this EventTrigger is a custom implementation in Slex namespace).

 <i:Interaction.Triggers>
            <slex:EventTrigger ElementName="txtData" EventName="KeyUp">
                <slex:InvokeCommandAction CommandName="UpdateDataCommand" />
            </slex:EventTrigger>
        </i:Interaction.Triggers>
Alright, I hope that looks cool. Now, what if you want to invoke the command if and only if a check box (named myCheckBox) is checked, and the user is pressing the 'A' key? Here we go.
 <i:Interaction.Triggers>
            <slex:EventTrigger ElementName="txtData" EventName="KeyUp">
                <slex:InvokeCommandAction CommandName="UpdateDataCommand">
                    <slex:InvokingConditions>
                        <slex:InvokingCondition Property="Argument.Key" Value="A"/>
                        <slex:InvokingCondition ElementName="myCheckBox" Property="IsChecked" Value="True"/>
                    </slex:InvokingConditions>   
                </slex:InvokeCommandAction>
            </slex:EventTrigger>
        </i:Interaction.Triggers>

2 – Simple example of a Property Trigger in Slex

Now, what if you want to fire a command, when a property of an element (or even a property in your View Model changes)? Here we go. You can do the same by using PropertyTrigger.

 <i:Interaction.Triggers>
            <slex:PropertyTrigger ElementName="txtData" Property="Text">
                <slex:InvokeCommandAction CommandName="UpdateDataCommand">
                    <slex:InvokingConditions>
                        <slex:InvokingCondition Value="Hello"/>
                        <slex:InvokingCondition ElementName="myCheckBox" Property="IsChecked" Value="True"/>
                    </slex:InvokingConditions>
                </slex:InvokeCommandAction>
            </slex:PropertyTrigger>
        </i:Interaction.Triggers>

 

As you can see, this will fire your UpdateDataCommand, when the Text Property changes. Also, you may or may not specify the conditions for the PropertyTrigger, just like we did for the EventTrigger.

3 – Simple example of InvokeMethodAction

In the previous examples, we’ve seen how to use InvokeCommandAction to invoke an ICommand in your view model. What about Invoking methods directly in your View Model? Here we go. Consider the following view model, that has a simple Add method to add two numbers.

image

Now, this is how to Invoke Add, so that ‘Data’ will get updated. Here is the UI and the XAML part.

image

As you can see, we have two text boxes where the user can enter the value, and a button where the user clicks to invoke the Add operation. Let us see the Xaml for this.

image

You may notice that, we are sandwiching an InvokeMethodAction inside an EventTrigger for the button click, and specifying the parameters in the order expected. Please note that the number of parameters should match the number of arguments of your Method.

Also, you can either tie your MethodParameterValue against properties of any other UI Element, or may point it to the view model. (Check out the SourceType property of MethodParameterValue).

Concepts - Brief Overview

Presently Slex supports a couple of triggers including

  • EventTrigger – You can tie an event trigger against an element, or against your view model. Fired when an event is raised
  • PropertyTrigger – You can tie a PropertyTrigger against an element’s property, or against a property in your view model. Fired when the property value changes

Also, Slex has a couple of abstract classes, including EventBasedTrigger and ObserverTrigger, and you may use the ObserverTrigger to create custom triggers that make use of System.Reactive extensions. More later.

You can sandwich Actions inside your Triggers. Few actions presently available are

  • InvokeMethodActionInvokes a method in your view model, or a method of a UI Element. You can have a collection of Method parameters in your InvokeMethodAction. See example below.
  • InvokeCommandActionInvokes a command in your view model

All Slex actions supports a set of Invoke Conditions, where you can specify multiple conditions for Invoking the commands.

Conclusion

About the source code - A first source drop is available at http://slex.codeplex.com. Go and click the Download link. Presently the drop is a VS2010 project, but you should be able to make the code run in VS2008 as well, by copying the source files and doing a bit of hacking, and modifying the references here and there.

This is a very very crude version, almost a POC. There are lot of things to do (there are quite a few bindings getting created as of now :)), lot of optimizations to be done, lot of unit tests to be written (I know, there is a suicidal absence of unit tests as of now). Also, I still need to see how this works with Blend :(.

I was talking to Vin for some time about this, and thought I’ll push the first cut any way. And also, blame Jeff too a bit.

I’ll blog soon on some other enhancements I’ve in mind, so follow me in twitter. Also, I’ll explain further few hacks I made around the Rx API, and the Dependency property listening side, by next week end. Happy Coding!!

Shout it
Read more >>

Share |

Wow, the new Bing Maps (beta) Rocks. First impressions here

I was about to sleep, but just stumbled up on Bing’s new Silverlight Powered Map site. Really cool interactive features there. Once quick thing I noticed is the integration of apps like Photosynth with the Bing maps, along with a lot of location sensitive information like local tweets, traffic information etc, overlaid in a great way. To start with, I just started searching Chicago.

image

And clicked the image thingy in the left panel, and that opened a photo synth, to display a perspective 3D Photosynth of Chicago.

image

And more surprises. Click on that orange ‘>’ button (bottom right on the left panel), and Bing will show you the Map Apps you can add to your Map (Map Apps). This includes various apps, including a restaurant finder, a real time twitter updates viewer in the map in that location, a traffic land app to view live traffic etc, a current traffic app to show the traffic status etc..

image   image

I just enabled a couple of them, including Twitter maps, Current traffic etc, and found that Mitchmaddox had a meeting with some one, and he should have started really early to get there, because the red lines shows high intensity traffic. Also, found that along with the Automatic, Road, Aerial and Bird’s eye views, Bing also provides overlaying content like tweets, on top of the Street view. Now this is cool, I can just look around and see what people are doing here.

  image image

This is just a quick post, probably there are lot more features there to explore. Here is a post from Bing team. Also, get Bing for your mobile here

Shout it
Read more >>

Share |

I was digging a bit around Silverlight Dependency properties, mainly to see how to receive change notification when ever a dependency property is changed. In WPF, this is straight forward, you may use the DependencyPropertyDescriptor, and call AddValueChanged. Like this.

DependencyPropertyDescriptor desc = 
  DependencyPropertyDescriptor.FromProperty
    (UIElement.VisibilityProperty, typeof(UIElement));

desc.AddValueChanged
  (this.myLabel, new EventHandler(VisibilityChanged));

 

Now, how to do this in Silverlight? I roamed around a bit, but can't really find a good way of doing that. So, here is a quick hack. The trick is to use DependencyProperty.RegisterAttached(..) to instantiate a dependency property type (Ahem). This is what we are doing below.

  • Create a binding with the FrameworkElement as the source
  • Use DependencyProperty.RegisterAttached(..) to create a DependencyProperty instance
  • Use FrameworkElement.SetBinding(dp, binding) to associate the dependency property with the element, via the binding.

So, we’ll get a call back when ever the dependency property changes. The RegisterForNotification summarizes what I explained above.

         
        /// Listen for change of the dependency property
        public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
        {

            //Bind to a depedency property
            Binding b = new Binding(propertyName) { Source = element };
            var prop = System.Windows.DependencyProperty.RegisterAttached(
                "ListenAttached"+propertyName,
                typeof(object),
                typeof(UserControl),
                new System.Windows.PropertyMetadata(callback));

            element.SetBinding(prop, b);
        }

 

Create a new Silverlight project, and add the above code to the code behind. And add the following controls to your xaml page..

   <Grid x:Name="LayoutRoot" Background="White">
        <TextBox Text="hello" x:Name="txtMain" />
        <Slider Value="10" Minimum="0" Maximum="100" x:Name="sliderMain"/>
    </Grid>

 

Now, just call RegisterForNotification from where ever you need (I’ve it in the Constructor of my MainPage.cs, just under the InitializeComponent() call), like

//Shows a message box when the text of Textbox or value of Slider changes.

RegisterForNotification
	("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
RegisterForNotification
	("Value", this.sliderMain, (d,e) => MessageBox.Show("Value changed"));

 

Fire up your project, and you’ll see the message boxes when ever the value change happens. So, now it looks pretty interesting, I guess. Opens up possibilities like having Data triggers in Silverlight, probably via an attached behaviour. Need to evaluate the pros and cons of this approach, came across this scenario while doing some other hacks. What do you think?

Stay tuned, follow me on twitter.  Happy Coding!!

Shout it
Read more >>

Share |

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