Getting Deep into .net

June 1, 2013

Lessons learned with LightSwitch HTML Client project

Filed under: How To,LightSwitch — goldytech @ 9:25 am



LightSwitch as a technology/tool  has always impressed me.I was quite fascinated that how this super cool technology enables us to avoid all that plumbing code and concentrate on the real core busineslessons learneds logic. In a true sense it supports Rapid Application Development. I was already familiar with the Silverlight Client and had developed complete ERP application. LightSwitch team recently shipped the HTML  Client with Visual Studio 2012 Update 2. When I first read about it , the first thought that came to my mind was that it can be a game changer of building LOB apps on mobile.It fully supports adaptive rendering and it based on the Single Page Application concept. I immediately decided that I will try my hands on it but wanted to do some real project rather than some small examples. I decided that I will try to convert one of my modules that were written in Silverlight client to HTML client. So I started the conversion. During the development phase I got stuck up but thanks to Huy Nguyen , from MS who helped me with it. So in this post I share the code snippets of the common scenarios that are required for any LOB apps. I assume if you are reading this post then you are already aware of the basics of LightSwitch client , if not then I recommend you to learn first and revisit this post.


It is one of the common requirements that when the form loads, to increase the usability of the application the cursor should be focused on the first element of the form. This will avoid the user an extra click of focusing the cursor on the control and he/she can immediately start typing. Here you need to target the post_render event of the textbox , of which you need to set focus. One important thing to note in the code snippet is that we are calling the focus method under settimeout method. This is just to ensure that the all the required elements are loaded in DOM.


  1. myapp.AddEditCustomer.CustomerName_postRender = function (element, contentItem) {
  2.     // Write code here.
  4.     var $firstTextBox;
  5.     $firstTextBox = $("input", $(element)); //get the input tag
  6.     setTimeout(function() {
  7.         $firstTextBox.focus(); //set the focus
  8.     }, 2);
  9. };


Imagine you are developing an order data entry screen , You have customer dropdown in this screen and every customer has a fixed percentage of discount associated to it. Now whenever the dropdown value changes you need to retrieve the discount value from the selected customer and do the processing of the discount calculations and update the final price read-only textbox on the screen. Let us see how you can achieve this.


  1. myapp.AddEditOrder.created = function (screen) {
  2.     var order = screen.Orders;
  4.     function updateTotal() {
  5.         var price;
  6.         var discount = 0;
  8.         price = order.Item.Price;
  9.         //if selected customer on order screen is not null
  10.         if (order.Customer) {
  11.             discount = order.Customer.DiscountType;
  12.         }
  14.         order.Total = price * (1 – discount / 100);
  15.     }
  17.     // When the order's Customer changes, update its total by attaching the change event listener.
  18.     order.addChangeListener("Customer", updateTotal);
  19. };



You have the screen of unapproved orders which is data binded to your custom query (where isApproved==false) of Orders entity. All this orders are displayed as Tiles. When any tile is selected a new screen(AddEditOrder) from where the user can set the approved flag equals true. When this screen closes the accepted behaviour should be that the parent screen should no more show that order, unfortunately LightSwitch cannot handle this automatically. And we need to write the custom code for this to get achieved. You cannot use the default EditSelected on the ItemTap event but write your own custom code for it.

  1. myapp.ApproveOrders.Orders_ItemTap_execute = function (screen) {
  2.     // Write code here.
  3.     myapp.showApproveOrdersScreen(screen.UnApprovedOrders.selectedItem, {
  4.         afterClosed: function () {
  5.             screen.UnApprovedOrders.load(); // manual refresh
  6.         }
  7.     });
  8. };



Cheers and Keep learning new stuff :)

May 11, 2013

Transforming WinForms Camera control to WPF in MVVM style

Filed under: .NET,WPF — goldytech @ 1:46 pm



Winforms technology enjoyed its dominance until Windows Presentation Foundation (WPF) made an entry and completely over took this legacy technology. It is now the preferred choice for developing the enterprise scale apps for desktops. It was an easy decision for companies to migrate their existing winforms code by doing simply copy and paste option. As most of the code behind written in winforms would just run in WPF, obviously the UI needs to be redeveloped. But that would defy the purpose of using the rich technology of WPF which supports data binding and eye catching glossy UI. Moreover if you are developing in WPF and are not adapting to the MVVM pattern then you are committing a serious crime. Eventually your app will grow and it would get nightmares for maintaining it.

In this blog post I talk about how I converted existing Winform Camera Control and encapsulated its entire functionality in the WPF User control so it can be reused across the project.


Just let me introduce to you about the functionality of this project. There should be live streaming from the webcam in your application and the user should be able to take the snapshot of the on going frame. The image should be saved in users Pictures library folder. Quite a simple requirement and there are tons of samples out there which can help us to nail this problem, but all those solutions violates the MVVM pattern. My solution follows the MVVM pattern religiously and still achieves the desired functionality.

I’m using Aforge framework to capture the camera output stream. This is quite extensive framework which does more than image processing. You can get more info by reading its documentation.

Create a new WPF application. Download MVVM Light toolkit libraries from the Nuget. Now add the Aforge libraries. You would require the following

  • AForge.Controls
  • AForge.Video
  • AForge.Video.DirectShow

Please note that all these above Aforge libraries can also be obtained from the Nuget.

Now comes the two important assemblies that you would require to reference in your project and they are

  • WindowsFormsIntegration
  • System.Windows.Forms

These two assemblies allow us to integrate winform controls in xaml. You can virtually use any winform control via these assemblies. Just nest it under the WindowsFormHost and you are done.


XAML and MVVM are made for each other. One of the cool features of any XAML based technologies is rich data binding. This feature allows us to bind any visual element. The only prerequisite for data binding is that the property to which you are binding should be a dependency property.

You can also create your own dependency properties of the user control and program it to the way you want. Create a new folder in your project and name it to ‘Controls’. Add a new UserControl to this folder and name it AForgeWebCam.xaml. Copy the below code in it.

  1. <UserControl x:Class="WPFWebCamMVVM.Controls.AForgeWebCam"
  2.              xmlns=";
  3.              xmlns:x=";
  4.              xmlns:mc=";
  5.              xmlns:d=";
  6.              xmlns:aforge="clr-namespace:AForge.Controls;assembly=AForge.Controls"
  7.              mc:Ignorable="d"
  8.              d:DesignHeight="300" d:DesignWidth="300">
  9.     <StackPanel>
  10.         <WindowsFormsHost Margin="10" Name="WinFormHost" Background="{x:Null}" Width="640" Height="480">
  11.             <aforge:VideoSourcePlayer x:Name="VideoPlayer" Size="640,480" />
  12.         </WindowsFormsHost>
  13.         </StackPanel>
  15. </UserControl>

Switch to the code behind of this user control , where we would create all the required dependency properties. We would require following dependency properties.

1)AvailableCameraSources : This will list down all the attached camera with the device name and unique id. This property will be of type IList<DeviceInfo>. The DeviceInfo is a simple class with two properties.

  1. public class DeviceInfo
  2.     {
  3.         /// <summary>
  4.         /// Gets or sets the display name.
  5.         /// </summary>
  6.         /// <value>The display name.</value>
  7.         public string DisplayName
  8.         {
  9.             get;
  10.             set;
  11.         }
  13.         /// <summary>
  14.         /// Gets or sets the usb string by which OS identifies the hardware.
  15.         /// </summary>
  16.         /// <value>The usb string.</value>
  17.         public string UsbString
  18.         {
  19.             get;
  20.             set;
  21.         }
  22.     }


  1. public static readonly DependencyProperty AvailableCameraSourcesProperty =
  2.             DependencyProperty.Register(
  3.                 "AvailableCameraSources",
  4.                 typeof(IList<DeviceInfo>),
  5.                 typeof(AForgeWebCam),
  6.                 new PropertyMetadata(GetCameraSources())); //set the default value

Have a look at line number 6 in the above code , the last argument of dependency property is PropertyMetaData , whose one constructor accepts one parameter Object type. Using this parameter the developer can set the default value of the dependency property. So here I initialize this property by calling private static method GetCameraSources. This constructor also accepts the other arguments which I will explain later.

  1. private static IList<DeviceInfo> GetCameraSources()
  2.         {
  3.             availableCameraSources = new List<DeviceInfo>();
  4.             var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
  5.             foreach (FilterInfo filterInfo in videoDevices)
  6.             {
  7.                 availableCameraSources.Add(
  8.                     new DeviceInfo { DisplayName = filterInfo.Name, UsbString = filterInfo.MonikerString });
  9.             }
  10.             return availableCameraSources;
  11.         }

2)CameraId : This is of string type . The value is basically the unique id of the camera by which the operating system identifies it. This is used by AForge VideoSourcePlayer control to render the video streaming.

  1. /// <summary>
  2.       /// The camera id property.
  3.       /// </summary>
  4.       public static readonly DependencyProperty CameraIdProperty =
  5.           DependencyProperty.Register("CameraId", typeof(string), typeof(AForgeWebCam), new PropertyMetadata(string.Empty, OnCameraValueChanged, OnCameraCoherceValueChanged));

Notice the two call-back methods OnCameraValueChanged and OnCameraCoherceValueChanged.The first call back methods handles the starting and stopping of the camera.The coerce call-back method allows us to adjust the value if of the property if it is not within the required range and throwing exception.

  1. private static void OnCameraValueChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
  2.       {
  3.           host = (AForgeWebCam)dependencyObject;
  4.           if (e.NewValue == null || string.IsNullOrEmpty(e.NewValue.ToString()))
  5.           {
  7.               StopVideoDevice();
  8.               return;
  9.           }
  12.           if (e.NewValue != e.OldValue)
  13.           {
  14.               if (videoDevice != null)
  15.               {
  16.                   StopVideoDevice();
  17.                   InitVideoDevice(e.NewValue.ToString(), (AForgeWebCam)dependencyObject);
  18.               }
  19.               else
  20.               {
  21.                   InitVideoDevice(e.NewValue.ToString(), (AForgeWebCam)dependencyObject);
  22.               }
  23.           }
  24.       }


  1. private static object OnCameraCoherceValueChanged(DependencyObject dependencyObject, object basevalue)
  2.         {
  3.             host = (AForgeWebCam)dependencyObject;
  4.             if (string.IsNullOrEmpty(basevalue.ToString()))
  5.             {
  6.                 return null; // if basevalue is null then return
  7.             }
  9.             if (availableCameraSources.FirstOrDefault(c => c.UsbString.Equals(basevalue.ToString())) == null)
  10.             {
  11.                 // check if the basevalue exists in the availableCamerasources , if not then assign the first value of the availableCameraSources
  12.                 if (availableCameraSources != null)
  13.                 {
  14.                     var firstOrDefault = availableCameraSources.FirstOrDefault();
  15.                     if (firstOrDefault != null)
  16.                     {
  17.                         return firstOrDefault.UsbString;
  18.                     }
  19.                 }
  20.             }
  22.             return basevalue;
  23.         }

3)TakePictureCommand : This property is of ICommand type. And its default value is set to TakeInteralPictureCommand private property. The action of this command encapsulates all the logic of taking the picture. A thing to note over here is that Aforge framework does not provide this functionality out of the box. I have written the custom code to achieve this. I capture the position of the control and using the apis available in System.Drawing namespace I create new image and save it to the pictures folder. See the code below

  1. public static readonly DependencyProperty TakePictureCommandProperty =
  2.             DependencyProperty.Register(
  3.                 "TakePictureCommand",
  4.                 typeof(ICommand),
  5.                 typeof(AForgeWebCam),
  6.                 new PropertyMetadata(TakeInternalPictureCommand));


  1. private static void TakePicture()
  2.         {
  3.             try
  4.             {
  5.                 const int PanelWidth = 640;
  6.                 const int PanelHeight = 480;
  7.                 string fileName;
  9.                 System.Drawing.Point pnlPoint =
  10.                     host.VideoPlayer.PointToScreen(
  11.                         new System.Drawing.Point(host.VideoPlayer.ClientRectangle.X, host.VideoPlayer.ClientRectangle.Y)); // get the position of the VideoPlayer
  12.                 using (var bmp = new Bitmap(PanelWidth, PanelHeight))
  13.                 {
  14.                     using (var g = Graphics.FromImage(bmp))
  15.                     {
  16.                         // generate the image
  17.                         g.CopyFromScreen(
  18.                             pnlPoint, System.Drawing.Point.Empty, new System.Drawing.Size(PanelWidth, PanelHeight));
  19.                     }
  21.                     // Get MyPictures folder path
  22.                     fileName = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\"
  23.                                + DateTime.Now.ToString().Replace(":", string.Empty).Replace("/", string.Empty) + ".jpg";
  25.                     // save the file
  26.                     bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
  27.                 }
  29.                 MessageBox.Show("Picture saved in Pictures library with filename=" + fileName, "Success");
  30.             }
  31.             catch (Exception exception)
  32.             {
  34.                 MessageBox.Show(exception.Message);
  35.             }
  36.         }



The whole idea of wrapping up the entire camera functionality in the UserControl was the code reuse. This control can be now dropped into any xaml window, page or even other user control.


  1. <Window xmlns:Controls="clr-namespace:WPFWebCamMVVM.Controls"
  2.         xmlns=";
  3.         xmlns:x=";
  4.         xmlns:Helpers="clr-namespace:WPFWebCamMVVM.Helpers" x:Class="WPFWebCamMVVM.MainWindow"
  5.         Title="MainWindow" Height="350" Width="525">
  7.     <Window.Resources>
  9.         <Helpers:DeviceInfoConverter x:Key="DeviceInfoConverter"/>
  10.         </Window.Resources>
  11.     <Window.DataContext>
  12.         <Binding Mode="OneWay" Path="Main" Source="{StaticResource Locator}"/>
  13.     </Window.DataContext>
  14.     <Grid>
  15.         <Grid.RowDefinitions>
  16.             <RowDefinition Height="Auto"/>
  17.             <RowDefinition Height="Auto"/>
  18.             <RowDefinition Height="Auto"/>
  19.             <RowDefinition Height="Auto"/>
  20.             <RowDefinition Height="Auto"/>
  21.             <RowDefinition Height="Auto"/>
  22.         </Grid.RowDefinitions>
  23.         <ComboBox x:Name="ComboBox" Grid.Row="0" Margin="10" ItemsSource="{Binding AvailableCameraSources,ElementName=WebCam}" DisplayMemberPath="DisplayName" SelectedItem="{Binding SelectedDevice}"/>
  24.         <!–Displaying the camera stream using the element binding–>
  25.         <TextBlock Grid.Row="1" Text="{Binding SelectedItem, Converter={StaticResource DeviceInfoConverter}, ElementName=ComboBox}" x:Name="UsbString" Margin="10"></TextBlock>
  26.         <Controls:AForgeWebCam x:Name="WebCam" Grid.Row="2" Margin="10" CameraId="{Binding SelectedItem, Converter={StaticResource DeviceInfoConverter}, ElementName=ComboBox}" />
  27.         <!–Comment the above two lines and Uncomment the below line if you want to assign the cameraUSB property from viewModel–>
  28.         <!–<Controls:AForgeWebCam x:Name="WebCam" Grid.Row="2" Margin="10" CameraId="{Binding CameraUsbId}" />–>
  29.         <Button Margin="10" Grid.Row="3" Command="{Binding ConnectCommand}">Connect</Button>
  30.         <Button Margin="10" Grid.Row="4" Command="{Binding TakePictureCommand, ElementName=WebCam}">Take Picture</Button>
  31.         <Button Margin="10" Grid.Row="5" Command="{Binding DisconnectCommand}">Disconnect</Button>
  32.     </Grid>
  33. </Window>

Using the element data binding capabilities I have binded the Combo box. So as a developer who is consuming your control does not have to bother about getting the camera sources because your control already exposes that as a dependency property.

The api of the usercontrol is quite simple , to connect to the camera set the CamerId property to the valid connection string, to disconnect it make it null or set the property to empty string.



Using WinFormHost control in WPF lot of existing controls can be reused. The only challenge lies how you ensure that your MVVM design in not getting compromised with this implementation. If planned smartly then this can be taken care off. I hope you must have enjoyed the reading this article. Please leave your valuable feedback in the comments. Download the sample code from here.

December 12, 2012

Implementing INotifyPropertyChanged in C#5.0 way

Filed under: .NET,How To,Linq — goldytech @ 11:54 am


All XAML developers are well aware of INotifyPropertyChanged interface. This interface is key to the data binding. Every ViewModel class or ViewModelBase abstract class implements this interface. One of the biggest issue with it is that the PropertyChangedEventHandler delegate event argument, PropertyChangedEventArgs constructor accepts the property name as string value. This can introduce bug in your code because of “MAGIC STRINGS” , where by which if developer misspell the property name or you require to rename your property , then it should be done very carefully otherwise your data binding can go completely for a toss and you would go in circles to figure out what the issue is. Let me illustrate what I am talking about with the code snippet below.

Old way implementation
  1. public class CustomerViewModel : INotifyPropertyChanged
  2.     {
  3.         private string customerNameValue = String.Empty;
  4.         private string phoneNumberValue = String.Empty;
  6.         public event PropertyChangedEventHandler PropertyChanged;
  8.         private void NotifyPropertyChanged(String propertyName)
  9.         {
  10.             if (PropertyChanged != null)
  11.             {
  12.                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  13.             }
  14.         }
  16.         public string CustomerName
  17.         {
  18.             get
  19.             {
  20.                 return this.customerNameValue;
  21.             }
  23.             set
  24.             {
  25.                 if (value != this.customerNameValue)
  26.                 {
  27.                     this.customerNameValue = value;
  28.                     NotifyPropertyChanged("CustomerName"); //Magic strings
  29.                 }
  30.             }
  31.         }
  33.         public string PhoneNumber
  34.         {
  35.             get
  36.             {
  37.                 return this.phoneNumberValue;
  38.             }
  40.             set
  41.             {
  42.                 if (value != this.phoneNumberValue)
  43.                 {
  44.                     this.phoneNumberValue = value;
  45.                     NotifyPropertyChanged("PhoneNumber"); //Magic strings
  46.                 }
  47.             }
  48.         }
  49.     }

In this short post I will talk about how you can avoid using these magic strings by using one of C# new 5.0 feature named as CallerMemberName attribute with support of optional parameters. So let us do some code refactoring in the above code and remove these magic strings. Have a look at the code snippet below.

New way implementation
  1. public class CustomerViewModel : INotifyPropertyChanged
  2.     {
  3.         // These fields hold the values for the public properties.
  4.         private string customerNameValue = String.Empty;
  5.         private string phoneNumberValue = String.Empty;
  7.         public event PropertyChangedEventHandler PropertyChanged;
  9.         private void NotifyPropertyChanged([CallerMemberName]
  10.                                            String propertyName = "")
  11.         {
  12.             if (PropertyChanged != null)
  13.             {
  14.                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  15.             }
  16.         }
  18.         public string CustomerName
  19.         {
  20.             get
  21.             {
  22.                 return this.customerNameValue;
  23.             }
  25.             set
  26.             {
  27.                 if (value != this.customerNameValue)
  28.                 {
  29.                     this.customerNameValue = value;
  30.                     NotifyPropertyChanged(); //Look ma no magic strings
  31.                 }
  32.             }
  33.         }
  35.         public string PhoneNumber
  36.         {
  37.             get
  38.             {
  39.                 return this.phoneNumberValue;
  40.             }
  42.             set
  43.             {
  44.                 if (value != this.phoneNumberValue)
  45.                 {
  46.                     this.phoneNumberValue = value;
  47.                     NotifyPropertyChanged(); //Look ma no magic strings
  48.                 }
  49.             }
  50.         }
  51.     }

Just have a look at NotifyPropertyChanged method in the above code snippet. This method argument is decorated with CallerMemberName attribute. This will replace the property name in the set accessor of that property. So you don’t need to hardcode any property name.

On the closing note I would also like to say that this is not the only way you can avoid the MAGIC STRINGS in the method name. If you are fan of functional programming like me ;) and have some knowledge of generics you can use Linq Expressions to achieve the same. Let us see one more code snippet which does this.

Smart way implementation
  1. public class CustomerViewModel : INotifyPropertyChanged
  2.     {
  3.         // These fields hold the values for the public properties.
  4.         private string customerNameValue = String.Empty;
  5.         private string phoneNumberValue = String.Empty;
  7.         public event PropertyChangedEventHandler PropertyChanged;
  9.         private void NotifyPropertyChanged<T>(Expression<Func<T>> expression)
  10.         {
  11.             var lambda = (LambdaExpression)expression;
  12.             MemberExpression memberExpr;
  13.             var body = lambda.Body as UnaryExpression;
  14.             if (body != null)
  15.             {
  16.                 var unaryExpr = body;
  17.                 memberExpr = (MemberExpression)unaryExpr.Operand;
  18.             }
  19.             else
  20.             {
  21.                 memberExpr = (MemberExpression)lambda.Body;
  22.             }
  23.             if (PropertyChanged != null)
  24.             {
  25.                 PropertyChanged(this, new PropertyChangedEventArgs(memberExpr.Member.Name));
  26.             }
  27.         }
  29.         public string CustomerName
  30.         {
  31.             get
  32.             {
  33.                 return this.customerNameValue;
  34.             }
  36.             set
  37.             {
  38.                 if (value != this.customerNameValue)
  39.                 {
  40.                     this.customerNameValue = value;
  41.                     NotifyPropertyChanged(() => CustomerName);
  42.                 }
  43.             }
  44.         }
  46.         public string PhoneNumber
  47.         {
  48.             get
  49.             {
  50.                 return this.phoneNumberValue;
  51.             }
  53.             set
  54.             {
  55.                 if (value != this.phoneNumberValue)
  56.                 {
  57.                     this.phoneNumberValue = value;
  58.                     NotifyPropertyChanged(() => PhoneNumber);
  59.                 }
  60.             }
  61.         }
  62.         }

As seen this is also cool way of avoiding the magic strings by using linq expressions. Finally a quick tip always create the base class (ViewModelBase) and encapsulate all the required functionalities in it. Then all your viewmodel classes must inherit this ViewModelBase class.

Hope you must have found this post useful. Please leave your valuable feedback in the comments section.

April 21, 2012

Windows Phone Tasks in Caliburn Micro Way

Filed under: Caliburn Micro,How To,Windows Phone 7 — goldytech @ 2:54 pm
Tags: ,

I had blogged earlier about my windows phone 7 app ,Bollywood ringtones which is now reaching almost 10k downloads. In that post I promised my readers to share my technical findings for my this pet project. I am man of my commitment and here I am to present my first knowledge share to the community. This post shows you how you can use the Caliburn Micro Framework for handling the Windows Phone Tasks. I specifically talk about SaveRingtoneTask but the same funda can be applied to most of the tasks (Launchers and Choosers) like EmailComposeTask,PhoneNumberChooserTask etc.

This blog post assumes that you are already aware of MVVM pattern and has some basic knowledge of Caliburn Micro Framework as this topic deals with some advanced concepts of this framework. I strongly recommend to read the documentation.

Caliburn Micro has much neater way of handling the launchers and choosers in MVVM pattern. The entire heavy lifting is done by IEventAggregator interface which is injected in the constructor of the ViewModel. Let us see the code to make things more clear.

Setting up windows Phone Ringtone in Caliburn Micro
  1. using Caliburn.Micro;
  2. using Microsoft.Phone.Tasks;
  3. using System.Windows;
  4. namespace RingtoneSample {
  5.     public class MainPageViewModel : Screen, IHandle<TaskCompleted<TaskEventArgs>>
  6.     {
  7.         readonly IEventAggregator _eventAggregator;
  9.         public MainPageViewModel(IEventAggregator eventAggregator)
  10.         {
  11.             _eventAggregator = eventAggregator;
  12.         }
  17.         /// <summary>
  18.         /// The Button Handler
  19.         /// </summary>
  20.         public void SetRingtone()
  21.         {
  22.             _eventAggregator.RequestTask<SaveRingtoneTask>(r=>{
  23.                 r.DisplayName="My Ringtone";
  24.                 r.IsShareable = true;
  25.                 r.Source = new System.Uri(@"appdata:/MyRingtone.wma", System.UriKind.RelativeOrAbsolute);
  26.              });
  27.         }
  29.         /// <summary>
  30.         /// IHandle Interface Implementation
  31.         /// </summary>
  32.         /// <param name="message"></param>
  33.         public void Handle(TaskCompleted<TaskEventArgs> message)
  34.         {
  35.             switch (message.Result.TaskResult)
  36.             {
  37.                 case TaskResult.OK:
  38.                     MessageBox.Show("Ringtone is set");
  39.                     break;
  40.                 case TaskResult.Cancel:
  41.                     MessageBox.Show("Save was cancelled");
  42.                     break;
  43.                 case TaskResult.None:
  44.                     MessageBox.Show("No information");
  45.                     break;
  46.             }
  47.         }
  49.         protected override void OnActivate()
  50.         {
  51.             _eventAggregator.Subscribe(this); //Register for event
  52.             base.OnActivate();
  53.         }
  55.         protected override void OnDeactivate(bool close)
  56.         {
  57.             _eventAggregator.Unsubscribe(this); //Unregister
  58.             base.OnDeactivate(close);
  59.         }
  60.     }
  61. }

I would like to bring few things to your mind here from the above code. These are bare minimum piece of code that you must write to make this work.

  • Your ViewModel class must implement  IHandle interface of Caliburn Micro Framework. If the windows phone task class have the TaskCompleted Event then this interface should be something like, IHandle<TaskCompleted<EventCompletedEventArgs>>. The TaskCompleted belongs to Caliburn Micro whereas the EventCompletedEventArgs should be replaced by the appropriate task completed EventArgs .So in my code for the SaveRingtoneTask has the completed event attached to it my IHandle interface is of the TaskEventArgs. This interface has the Handle method which is synonymous to the EventHandler. You can use this method as your callback method once the event is triggered and it is completed.
  • The Viewmodel class constructor should be injected with IEventAggregator.
  • I am using IEventAggregator RequestTask<SaveRingtoneTask> method and passing all the properties of the SaveRingtoneTask class via lambda expressions. The RequestTask method is similar to the Show method of the task ,if you take the classical approach of handling the Tasks.
  • You need to call the subscribe method when your viewmodel loads as my viewmodel is also inheriting from the Screen class I am using the OnActivate override method to do this job. This is very important step otherwise you may not get the callback event handler.
  • And finally you need to unregister so that the memory clean up happens. The good thing over here is that IEventAggregator creates a WeakReference of the events hence there are no chance of memory leaks. But it is always good practice to unregister all the hook events. I am performing this task by overriding the OnDeactivate method.


So you have seen that using ViewModel first approach how innovatively we handled the launchers and choosers in windows phone 7 , keeping the essence of MVVM pattern. You can download the sample code for this post from here.

Cheers and keep rocking.

March 11, 2012

Bollywood ringtones is now available in Windows Phone Marketplace

Filed under: Windows Phone 7 — goldytech @ 4:09 pm


Today I received the email from Windows Phone Marketplace team that  my application, Bollywood ringtones is now published. Well this is my first windows phone 7 app in the market place. This blog post shares my experience right from the conceptual idea to the final publishing. I always intended to keep my blog technical but this post would be a bit exceptional but I assure you that I will share the secrets and some tricks which I discovered during this pet project of mine with the community in future posts. And later or sooner if time permits I will make this app an open source and will publish on codeplex.


You can call me fan boy of Microsoft. The company and its technologies have always inspired me and motivated me to such a extent that even after 12 years of industry experience I feel hard to get detached from the technology. I was early adopter of Windows Phone device as soon as hit the Indian shores. I was also a vivid user of Windows Mobile right from Win CE 5.0 to Win mobile 6.5 . It really amazed me the things I could do on this 4 inch device. So I used to check my emails and surf the net on my mobile device even eight years back Smile. Do you remember those HP-ipaq , Qtek PDA’s. One thing I must admit that those devices were extremely flexible and the SDK or .net Compact Framework had a very rich API’s and you could do wonders with them. Let me give you example of one small feature which was like a big push for me to develop this app. I could make any mp3 file as the ringtone by just long hold or right click on the selected file, a context menu would appear and all I need was to do select and option “Set as Ringtone”.  Windows Phone 7 is designed keeping consumer or end user in the mind rather than the developer (We developers want to do everything impossible Winking smile). So no wonder there wasn’t any such features in WP7 available which could go at OS level. There wasn’t even an api also available in pre mango SDK for setting up the custom ringtone. I hope the SDK will mature in up coming releases which will allow developer to flex their muscles.

I always missed it as I am great music lover and always keep on changing my ringtones every week to my favorite songs. There are other apps also in the marketplace which allows to set ringtones but not the Bollywood songs. Their lists are also pretty static and don’t keep updates. The USP of Bollywood ringtones is that I shall keep updating the ringtones every two weeks . If you as a user doesn’t find you favorite tune in the list just email me with its attachment and take my word it will be available in less than 48 hours. Below are some cool screen shots of the application.


MainPage RingtoneDetails RingtoneDetails1


I know you must be itching by now enough of talking share some tech info with us. So here we go. Bollywood ringtones is my pet project. I used to work on weekends for this. After long week of hard work at my day job somehow I used to get energy to sit down again and do the coding for my dream project. The app uses  Caliburn Micro 1.3.1 framework to achieve the MVVM pattern. Boss this is amazing stuff developed by Rob Eisenberg and has really impressed me. The learning curve was very little as I was already aware of this design pattern and there is an extensive documentation and examples available on the codeplex. The community support is immense I got answers to my queries in less than 24 hours which was really good and I was able to keep the pace of my development. Some of features used from this Framework are Actions, Coroutines, Tasks, EventAggregator ,StorageHandler etc.

The server part was done using Web Api. Again a cool technology from Microsoft makes development breeze. Though I am client side developer it didn’t appear a rocket science to me and I got up and running in less than 1 hour of time. Thanks to Glenn Block for his guidance and help. I used Entity Framework 4.3 with code first approach and MVC 4 Beta (It comes with GO-LIVE license) for developing my api methods / controllers.

I also used the Telerik RAD controls for Windows Phone 7. This is not a breaking news that Telerik is leader in custom controls and their products speak for themselves what more I could say about them. Their examples project which comes as a part of download helped me lot to get started with the controls. I have a confession to be made over here that I am developer and not a designer so the entire artwork was done by my younger brother Nazim (@nazqu5). He was immense help to me for making the application look sexy and sweet. I provided him few guidance in Blend and gave him design time data for developing in Blend. All the images were developed in Photoshop.

I also wrote Unit Tests for every viewmodels in the project. I used Jeff Wilcox unit test framework to test them. It was very pleasing to eyes that every tests was green. Last but not least I used Marketplace Testkit for making my app marketplace ready. No wonder that my app got certified in the first attempt itself.


  1. SharpGIS GzipWebClient from Morten
  3. Metro Grid Helper
  4. Isolated storage Explorer


For me developing app for Windows Phone 7 platform was very easy as I already knew Silverlight and WPF. If I calculate the hours spent on developing the fully functional app took twelve hours of coding. This include writing MVC code also. I have not included the art work and unit testing in this. Those are separate. Though Bollywood ringtones is free it supports ads. I know that I wont become millionaire from this but at least I would be able to make enough money to meet my per month fuel expenses Smile. I would strongly emphasize that every developer must try their hands on it and grab this rising opportunity. Microsoft India has great contest for the developers which can won you Windows Phone device. So start rolling your app today.

January 25, 2012

Dynamic Theme Switching in Silverlight Prism App

Filed under: How To,Prsim,Silverlight 4 — goldytech @ 5:10 pm



In my recent consulting assignment I was asked the question by one of the developer , that how can we get dynamic theming working in Prism application.My answer was that you can implement in the same manner as you do in the standard Silverlight application. But then he further asked that there are various regions in the RegionManager and how each views loaded in the different content regions can get unified theme , this encouraged me to try this out and see how it works.I started working on it and viola my answer was correct , there is no difference in implementing dynamic theming in prism specific app. In this blog post I explain you the same. I assume that readers are already aware of Prism library. If you are not then I strongly recommend that you acquire the knowledge of the same. In my example you will see the very basics of Prism app but the library has much more to offer.


I created a very simple PRISM application which had only one Module (ModuleA). This module is loaded on demand when you click on the menu link which is under the ShellView.The application default gets loaded in the BlueTheme but it allows you to change the theme on the fly from the Themes menu. See the screen shot below of both themes.




The application has two content regions (MainContent and FooterContent).

Code Snippet
  1. <menu:Menu Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Top">
  2.             <menu:MenuItem Header="Modules">
  3.                 <menu:MenuItem Header="Load Module A" Command="{Binding LoadModuleCommand}"/>
  4.             </menu:MenuItem>
  5.             <menu:MenuItem Header="Themes">
  6.                 <menu:MenuItem Header="Blue" Command="{Binding Path=ChangeThemeCommand}"
  7.                                        CommandParameter="BureauBlue.xaml"
  8.                                        IsChecked="{Binding IsBlueThemeSelected}"/>
  9.                 <menu:MenuItem Header="Black" Command="{Binding Path=ChangeThemeCommand}"
  10.                                        CommandParameter="ExpressionLight.xaml"
  11.                                        IsChecked="{Binding IsBlackThemeSelected}"/>
  12.             </menu:MenuItem>
  14.         </menu:Menu>
  15.         <ContentControl prism:RegionManager.RegionName="MainContentRegion" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="12" />
  16.         <ContentControl prism:RegionManager.RegionName="FooterContentRegion" Grid.Row="2" Margin="12"/>

Let me show you the code which does the magic of dynamic theming.

Code Snippet
  1. public DelegateCommand<string> ChangeThemeCommand
  2.         {
  3.             get
  4.             {
  5.                 if (_changeThemeCommand == null)
  6.                 {
  7.                     _changeThemeCommand = new DelegateCommand<string>(x =>
  8.                     {
  9.                         Application.Current.Resources.MergedDictionaries.RemoveAt(0);
  10.                         var theme = Application.GetResourceStream(new System.Uri("/Shell;component/Assets/" + x, System.UriKind.Relative));
  11.                         var rd = (ResourceDictionary)(XamlReader.Load(new StreamReader(theme.Stream).ReadToEnd()));
  12.                         Application.Current.Resources.MergedDictionaries.Add(rd);
  13.                         if (x == "BureauBlue.xaml")
  14.                         {
  15.                             IsBlueThemeSelected = true;
  16.                         }
  17.                         else
  18.                         {
  19.                             IsBlackThemeSelected = true;
  20.                         }
  21.                     }, y => _moduleLoaded);//only allow to change themes when module is loaded
  22.                 }
  24.                 return _changeThemeCommand;
  25.             }
  26.         }

The ChangeThemeCommand is DelegateCommand of String type. The command argument excepts the filename of theme. All theme files are located in Assets folders of the Shell project. The default theme is initialized in the App.xaml file with special syntax. It removes the current theme and loads the selected theme and merges it into the Resource Dictionary.

Code Snippet
  1. <Application.Resources>
  2.         <ResourceDictionary>
  3.             <ResourceDictionary.MergedDictionaries>
  4.                 <ResourceDictionary Source="/Shell;component/Assets/BureauBlue.xaml" />
  5.             </ResourceDictionary.MergedDictionaries>
  6.         </ResourceDictionary>
  7.     </Application.Resources>

This special syntax allows to access the files across different assemblies or xap files via relative paths.


This was super simple to implement it and I highly recommend the devs to implement this feauture in their apps. Last a ninja tip. Always mark your assemblies in the module projects to CopyLocal=false if they are already referenced it in the Shell project. Download the sample code from here.

November 30, 2011

Windows Phone geocoding with Rx

Filed under: How To,Reactive Extensions,WindowsPhone — goldytech @ 4:38 pm

I had heard lot about Reactive Extensions (Rx) in the past but never got a chance to play with it until recently one of my project requirements were idle to make use of this great library.In this post I share my experience on how I used this library. Before we jump into code I would like to summarize the definition of Rx for the readers who haven’t known about it.


Up till now we had heard that computers came up with multiprocessors and gigabytes of memory but now we are hearing the same for even mobile devices. The new models do come with dual core processers and enough memory. As a developer you need to adopt some special programming techniques to unleash this power. You must write concurrent and asynchronous code to scale up to the hardware. When we talk about the asynchronous programming lot of caution needs to be taken for threading and deadlock issues. Fortunately Rx.NET does all this heavy lifting for you and gives you a fluent api for Async programming with LINQ flavour.Rx.NET is developed at Microsoft Labs and comes for full .net Framework, Silverlight, Windows Phone and JavaScript.
Rx is based on the Observer pattern from the world of object oriented programming. This pattern is based on the Observable collection, known as a Subject. You register or subscribe as an Observer for this Subject and you get notified whenever there is a change in the collection. Let me explain you this with example code.

var numbers = Observable.Range(1,50);
numbers.Subscribe(x =>
textBlock1.Text += String.Format(" OnNext: {0}", x),
ex => textBlock1.Text += String.Format(" OnError: {0}", ex.Message),
() => textBlock1.Text += " OnCompleted");

In the above example the numbers collection is between 1 to 50. I subscribe to this collection for getting notifications. This is achieved by specifying the first argument of the subscribe method which is OnNext action method. The second argument is OnError , which is again the action method, you can handle the errors here and finally the OnCompleted, where you can do the cleanup if required or do the final processing.
Rx is entirely based on the LINQ and support all its extension methods like Where,Take,Skip etc. LINQ works with collections that implement IEnumerable,which are known as enumerable collections. Rx works with collections that implement an extension to IEnumerable, IQueryable, which is refer to as observable collections. Hope you must have got the fair idea of Rx by now for further study I would redirect you to Rx official site where there are great tutorials and samples to get you started.


As mentioned above Rx library is available for Windows Phone 7 also, It is part of the SDK itself and you don’t need a separate download. All you need to add reference to your project two assemblies.
In the sample application we display the GPS status and its coordinates coming from the location emulator. The user clicks on the Start button and then clicks on the location emulator to see the coordinates getting changed in the phone emulator. See the screenshot below for more clarity.


To capture the latitude and longitudes you need to handle the PositionChanged event of GeoCoordinateWatcher class. The eventargs of this event is of prime importance to us as we will be using it to get the positions. See the code below.

var positions = Observable.FromEvent>(watcher, "PositionChanged").Where(g => !Double.IsNaN(g.EventArgs.Position.Location.Latitude) && !Double.IsNaN(g.EventArgs.Position.Location.Longitude));

positions.ObserveOnDispatcher().Subscribe(geo =>
this.txtPositon.Text = string.Format("{0:###.0000N;###.0000S;0}, {1:###.0000E;###.0000W;0}"
, geo.EventArgs.Position.Location.Latitude
, geo.EventArgs.Position.Location.Longitude


In the above code one thing to look is the Observable.FromEvent(watcher, “StatusChanged”). I am telling the Rx to Capture all the values coming from the observable collection of GeoPositionChangedEventArgs on the watcher object which is of type GeoCoordinate and the event name is PostionChanged. This will dump all the values of incoming coordinates in the positions variable. And then further I am interested in this collection so I will subscribe to it and will be notified whenever this collection gets changed. If you remember on the top I mentioned that Rx goes hand in hand with Linq and supports all its extension methods. Here in the above code I using Where to get only valid lats and longs which is having proper double values rest will be discarded. On receiving the notification that is onNext Action method ,I simply update my TextBlock Text in proper format of gps position.To avoid the cross thread issues I am using the ObserveOnDispatcher extension method.


I have barely scratched the surface of Rx there is a lot to it. I strongly recommend that all devs should acquire its knowledge and used it in their projects.Rx makes Async programming breeze which makes it as an idle choice to work with webservices.
Download the sample code of this post from here.

Cheers :)

October 10, 2011

How to create Tag Cloud in Silverlight

Filed under: How To,Silverlight 4 — goldytech @ 2:25 pm



A tag cloud is a collection of texts that gets classified into the level of the importance. Text with greater importance are shown in the bigger size followed by the preceding importance , in short they are arranged in descending order. The importance is identified by one of the property usually a numeric value. It is one of the popular way for data visualizations. It is really gaining great heights in Business Intelligence 2.0 world. In this post I shall teach you how you can create tag cloud in Silverlight.


To showcase my example we will take the top ten stocks that were traded on the stock exchange by their last trading price. See the screen shot below.


As you can see from the above picture. The company names text font size are appearing based on their last trading price. I have taken only two colors (Magenta and Blue) but the developer can implement a random color logic also here.


To generate the tag cloud in Silverlight is super simple. I have taken a wrap panel control available in Silverlight toolkit. I then add each textblock as children of this wrap panel. All this is done using MVVM Light Toolkit version 4 , which is still in Beta state but it is pretty stable. Let us dive into the code to have better idea.

public class MainViewModel :ViewModelBase

        public MainViewModel()

            GenerateCommand=new RelayCommand(()=>
                                    var stocks = GetStocks();
                                    double minLastPrice = stocks.Min(a => a.LastPrice);
                                    double maxLastPrice = stocks.Max(b => b.LastPrice);
                                    double diffLastPrice = maxLastPrice - minLastPrice;
                                    const double minFontSize = 15.0;
                                    const double maxFontSize = 40.0;
                                    const double diffFontSize = maxFontSize - minFontSize;
                                    for (int i = 0; i < stocks.Count(); i++)
                                        Messaging.RaiseAddTextBlock.Send(new TextBlock { Text = stocks[i].Company, Foreground = i % 2 == 0 ? new SolidColorBrush(Colors.Magenta) : new SolidColorBrush(Colors.Blue), Margin = new Thickness(3), FontSize = minFontSize + stocks[i].LastPrice * diffFontSize / diffLastPrice });


        public RelayCommand GenerateCommand { get; private set; }       

        private List<Stock> GetStocks()
            var stocks = new List<Stock>
            new Stock { Company = "TATAPOWER", LastPrice= 105.25},
            new Stock { Company = "TATAMOTORS", LastPrice= 169.90},
            new Stock { Company = "DLF", LastPrice= 228.55},
            new Stock { Company = "SESAGOA", LastPrice= 214.35},
            new Stock { Company = "IDFC", LastPrice= 121.15},
            new Stock { Company = "TATASTEEL", LastPrice= 434.70},
            new Stock { Company = "INFY", LastPrice= 2597.50},
            new Stock { Company = "STER", LastPrice= 117.40},
            new Stock { Company = "RELIANCE", LastPrice=829.20},
            new Stock { Company = "WIPRO", LastPrice= 344.65}
            return stocks;


The above code is not a brainer and it is self explanatory . The only thing that needs to be considered is the FontSize property of the textblock where I put the logic of displaying the size as per the LastPrice property of the stock class. The datasource of my Tag Cloud is hard coded collection but it could be dynamic also.


Silverlight as a platform as a tremendous potential to develop BI apps. You can create great data visualizations from the toolkit available or from the third party controls from the different vendors. I encourage developer to explore this area and create a appealing user experience for your BI users. Download the sample code from here and enjoy Smile.

September 16, 2011

What is stored for developers in Windows 8

Filed under: Windows 8 — goldytech @ 1:46 pm

Now that the BUILD conference comes to end. It time to reflect what were the announcements made in it. I would especially give my thoughts from the developer perspective. I will summarize it in few points that matter most to the developers.

  • SILVERLIGHT IS ALIVE AND KICKING : I think Microsoft has silent its critics who were telling that Silverlight is dead and HTML 5 and JavaScript would be native development technology for Windows 8. With new version of Silverlight about to release by this fall. Tons of new features and improvements have been done in new version and I’m looking forward to develop my first production app. Microsoft has also given importance to new trend where the competition is heading that is HTML 5 and JavaScript. The developer has the option to develop in this language also. My old friends of C++ don’t get disheartened your skills are still in demand and you can program on Windows 8. So this summarizes that there is not one technology on which you can develop apps. Folks at Microsoft has kept their promise of backward compability.


  • WINDOWS RUNTIME (WINRT): Welcome to this new acronym. Uptill now you must have heard about .net framework but to develop the apps for Win8 you would require to enter new arena of Windows Runtime. This still will be managed code according to the speculations it is the subset of .net framework only where MS has picked and choose the namespaces and classes which could very well gel with new platform. Tim has a great blog post mystifying the facts and speculations of new runtime. You can read it over here.


  •  METRO STYLE APPS : Get yourself acquainted with this new style. As windows 8 natively support touch input natively. All the apps that you would be developing should support this style. This is something that is derived from Windows Phone 7. I had always loved Metro theme, smooth and fluid. All the apps should be touch centric and chromeless. You need to get your application certified before publishing it to the store. There are guidelines available and once you follow them there are 100 % chances that your application would pass in one attempt. As mentioned above keeping the backward compability in mind you can still continue to develop the apps in traditional old style like desktop or standard web apps running in the browser. MS has committed that whatever that is running in Windows 7 will run in Windows 8. All you need is to switched to the desktop mode. You have Visual Studio 2011 IDE for doing the development of this types of apps. It comes with preinstalled templates and each template comes with lot of boiler plate code to get you quickly started. Blend 5 now support HTML authoring also.


  • HARDWARE AGNOSTIC : This is the perhaps the best feature I like about new platform. As windows 8 runs equally well on all the form factors (various screen sizes ranging from dual monitors to tablets). It will run on Intel based processers as well as ARM based. I was mesmerized when I saw the demo where Steven Sinofsky showing Win8 running on ATOM based processor with 1 GIG of RAM. Awesome simply awesome. Imagine here the opportunities that lies for you as a developer, your app running on laptops,desktops and now even tables or slates. You can always monetize your efforts and earn few extra bucks besides your day job. I am not saying that it will make you millionaire Smile , but opportunity is definitely there.


I have been in this industry now for more than decade and this is probably the best time I am having in my career span. Lot of excitement times ahead and huge opportunities for developers to seize.

So start brushing up your skills


August 5, 2011

Creating Fault Tolerant Silverlight Applications



As an enterprise application developer you have to face lot of challenges. You are responsible for designing and developing highly scalable and fault tolerant systems. The systems that you develop are life line for your enterprise any downtime in it can cause a rippling effects and sometimes even loss of revenue. Your worries get more when you come to know that the application that you are working on shall be deployed on shared hosting environment. Though you have the SLA with the hosting company of  99.9 % uptime but servers do get crash and they backup or failover servers gets replaced so that your users get minimum downtime. I recently overcome this challenge and wants to share my experience with the community. The application that I developed was deployed on shared hosting environment with SQL Server on a separate box. The hosting company had a failover mechanism in place where by which if the server on which my database was running had some problems it will be taken over by the failover server. Now the question over here how will my application know that the main server is down and I have to switch over to the failover server because the connection string was already hardcoded in the web.config file which was pointing to the main server.This application was developed using Silverlight and WCF Ria Services. I took up this challenge and in the end came out with the elegant solution. So keep reading.


I need to device a solution by which my app knows that which sql server it needs to point out before retrieving or submitting the data. For the  readers information both the database servers were always sync with the data , there was bi-directional synchronization mechanism already in place by the hosting company. So I was assured that my users would never get any stale data. After doing a bit of head scratching I found the way out. As I was using Entity Framework ,Visual Studio generates code based on your logical model when the solution was build. This generated code can be found under your .edmx file. It has the extension .designer.cs . Refer to the figure below.


If you open this file you would find one partial class which inherits from the ObjectContext. As this class was partial I can always extend it in other class and use its existing partial methods. In my case I used the partial method OnContextCreated . The code of this this extended partial class is shown below.



The above code is no teaser. In the OnContextCreated method I check for the main server connection is working or not by calling the function CheckIfSqlServerisRunning() . If this function returns me false then I call another function which gets me the alternate connection for the failover sql server. CheckIfSqlServerisRunning function will return me true if I am able to open the connection successfully else it will return false. But the real potatoes and meat is in GetAlternativeConnection function. This function builds up the dynamic Sql connection string using SqlConnectionStringBuilder class and then I use the EntityConnectionStringBuilder class to make the Entity connection string.

The OnContextCreated method will be called whenever your domain service methods wants to perform any database operations and that is the catch. You always ensure that you give a valid sql connection to the service so it doesn’t fails and your user can get data seamlessly without knowing from which database server the data is coming from. You change the connection on the fly if the main server is down.


As the saying goes “WITH GREAT POWER COMES GREAT RESPONSIBILITIES” , the same thing applies to a developer. You carry a loads of responsibilities on your shoulder for the enterprise to become successful. Any bad code written by you can not only ruin you but your organization too. So first think and then code.


Next Page »

The Rubric Theme. Create a free website or blog at


Get every new post delivered to your Inbox.

Join 69 other followers