Getting Deep into .net

July 21, 2014

My thoughts on Xamarin Forms

Filed under: Xamarin — goldytech @ 8:21 am


Xamarin as a product has always delighted me. Imagine writing cross platform native mobile apps with your favorite programming language, C#. As a developer you feel proud that your code is running on more than billion devices world wide. To add icing on the cake frameworks like MvvmCross and CrossLight enables the devs to share more than 60% of their codebase across the platforms. These frameworks provides plugins for common scenarios of mobile development like GPS,Camera,Navigation etc. The only code that remain distinct to the platform specific is UI code. and believe me this was tuff task. On Android you have to deal with XML and on iOS it was XCode proprietary drag and drop styles for creating the UI. But when Xamarin came out with version 3.0 things changed at that front also. Among many other cool features released with the latest version my personal favorite was Xamarin Forms. This is the awesome library where by which you can create mobile apps by almost sharing 90% of your code base. Yes and this includes the UI part also. At runtime the library will generate native UI for each platform.

You have two options to share the UI code

  1. Create UI with XAML markup
  2. Create UI with code behind.

Xamarin Forms supports Windows Phone 8 also.


The code sharing approach can be achieved via Portable class library (PCL) or Shared Project. If you intend to use XAML for your UI then you need to use PCL only.

The library is fully extensible. If you wish to write any platform specific code then you can use Dependency Service and if you want to render custom UI for any platform then you can use custom renderers for the same.

MVVM pattern is supported out of the box. Just set up your INotifyPropertyChanged interface and you are good to go. It has full support of data binding, Command and Messenger. If you don’t want to use built in classes then you can hook up any MVVM Framework. In fact Laurent Bugnion has a very good post about using MvvmLight Toolkit.

The community is quite actively involved in contributing add-ons for Xamarin Forms . Two projects which I’m following very closely are

  1. Xamarin Forms Labs
  2. Acr-Xamarin Forms


Xamarin Forms popularity has really shooted up rocket high. But as a developer this is my wish list

  1. Provide Xaml Ui Designer , something very similar to Expression Blend . At the time of writing this post only Xamarin Studio supports bit of intellisense for XAML markup.
  2. Start support for Windows Store apps (Windows 8.1 and Windows Phone 8.1)
  3. Similar to maps and SQLite database , provide support for push notifications for all the platforms via common code base.
  4. Provide a converter tool which can parse XAML and convert to C# code and vice versa.
  5. Provide better code refactoring tools like Resharper for Xamarin Studio.


I know I may be quite demanding :). This library has a great potential and can be eventually become a game changer. Let us wait for Evolve conference what announcements Xamarin makes for this great library.

May 10, 2014

Understanding Cryptography in WindowsRT

Filed under: How To,Windows 8 — goldytech @ 10:20 am


Security runs in my blood. After extensively working on cryptography on .net platform and have developed couple of mission critical apps. I was given the other challenge for an LOB app in WinRT platform. One of the requirements of the app was of cryptography. I researched it and learned a lot about it, so thought let me share the my knowledge with the community.


Let the readers get this straight, the WinRT platform is still under evolution , hence it does not offer the same number of apis that are available under .net platform. The platform will become more mature in future and you will see more convergence between the two platforms. There are two main api’s available which does most of heavy weight lifting. They are IBuffer, which marshal out the data. I would term it as an alternative to byte array available in .net and the other one is the static class CryptographicBuffer. I shall be talking about three aspects of cryptography

  1. Hashing
  2. Random Data
  3. Symmetric Encryption


WinRT support MD5, SHA-1,SHA-256, SHA-384 and SHA-512 hashing algorithms. The code is pretty simple.

   1: private async void BtnHashConvertTapped(object sender, TappedRoutedEventArgs e)

   2:        {

   3:            if (string.IsNullOrEmpty(this.TxtInput.Text))

   4:            {

   5:                return;

   6:            }


   8:            // get the raw input string

   9:            var textToBeHashed = this.TxtInput.Text;


  11:            // convert string into binary

  12:            var inputBuffer = CryptographicBuffer.ConvertStringToBinary(textToBeHashed, BinaryStringEncoding.Utf8);


  14:            // declare sha512

  15:            var sha512Hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);


  17:            // hash the binary data using SHA512 algorithm

  18:            var hashedData = sha512Hash.HashData(inputBuffer);


  20:            // encode the hashdata to Base64 format

  21:            var encodeToBase64String = CryptographicBuffer.EncodeToBase64String(hashedData);

  22:            var msgDialog = new MessageDialog(encodeToBase64String);


  24:            // show the output in message dialog

  25:            var msg = await msgDialog.ShowAsync();

  26:        }

After conversion of plain input string into binary, we select the algorithm that needs to be applied. The output of which is hashData which is of IBuffer type. And finally converting it back to Base64 format.


It is quite common need of the enterprise apps to generate the random data. In WinRT platform this can be classified in two sections

  • Generating Random Number
   1: /// <summary>

   2:         /// The generate random number.

   3:         /// </summary>

   4:         /// <param name="sender">

   5:         /// The sender.

   6:         /// </param>

   7:         /// <param name="e">

   8:         /// The e.

   9:         /// </param>

  10:         private async void GenerateRandomNumber(object sender, TappedRoutedEventArgs e)

  11:         {

  12:             // generate random number and show it is message dialog.

  13:             var msgDialog = new MessageDialog(CryptographicBuffer.GenerateRandomNumber().ToString());

  14:             var msg = await msgDialog.ShowAsync();


  16:         }

The GenerateRandomNumber method returns a 32 bit unsigned integer value.

  • Generating Random Byte Array
   1: /// <summary>

   2:         /// Generates the random byte array

   3:         /// </summary>

   4:         /// <param name="sender">The sender</param>

   5:         /// <param name="e">The EventArgs</param>

   6:         void GenerateRandomArray(object sender, TappedRoutedEventArgs e)

   7:         {

   8:             uint len;

   9:             if (uint.TryParse(this.TxtLength.Text, out len))

  10:             {

  11:                 // generate the random byte array of specified length.

  12:                 var buffer = CryptographicBuffer.GenerateRandom(len);


  14:                 // convert the buffer (byte array) into hexadecimal format and show it in message dialog

  15:                 var msgDialog = new MessageDialog(CryptographicBuffer.EncodeToHexString(buffer));

  16:                 msgDialog.ShowAsync();

  17:             }

  18:             else

  19:             {

  20:                 // user inputted invalid number show the message and set back the focus

  21:                 new MessageDialog("Invalid number").ShowAsync();

  22:                 this.TxtLength.Focus(FocusState.Keyboard);

  23:             }

  24:         }

The above code demonstrates to generate random byte array of the specified length and converts back into hexadecimal format.


In this type of encryption we have only one key for encryption and decryption. So we should have a key before hand. Apart from the key we also require the Initialization Vector , which does the job of randomizer. In our case we will be using 1024 bit key and 16 bit for IV. Again we will be using the GenerateRandom method to generate these values. Both these binary values will be converted back to Hex format. Let us dive in code and see it in action.

   1: /// <summary>

   2:         /// Generates a random 1024 bit key

   3:         /// </summary>

   4:         /// <returns>A Hex format key</returns>

   5:         private static string GetKey()

   6:         {

   7:             // generate 1024 bits key

   8:             var buffer = CryptographicBuffer.GenerateRandom(1024);

   9:             return CryptographicBuffer.EncodeToHexString(buffer);

  10:         }


  12:         /// <summary>

  13:         /// The get initialization vector.

  14:         /// </summary>

  15:         /// <returns>

  16:         /// The <see cref="string"/>.

  17:         /// </returns>

  18:         private static string GetInitializationVector()

  19:         {

  20:             // a 16 bit random binary value

  21:             var buffer = CryptographicBuffer.GenerateRandom(16);

  22:             return CryptographicBuffer.EncodeToHexString(buffer);

  23:         }

Code to Encrypt

   1: /// <summary>

   2:        /// The encrypt.

   3:        /// </summary>

   4:        /// <param name="sender">

   5:        /// The sender.

   6:        /// </param>

   7:        /// <param name="e">

   8:        /// The e.

   9:        /// </param>

  10:        private void Encrypt(object sender, TappedRoutedEventArgs e)

  11:        {

  12:            if (string.IsNullOrEmpty(this.TxtPlain.Text))

  13:            {

  14:                return;

  15:            }


  17:            // convert plain text to binary

  18:            var input = CryptographicBuffer.ConvertStringToBinary(this.TxtPlain.Text, BinaryStringEncoding.Utf8);

  19:            var iv = CryptographicBuffer.DecodeFromBase64String(this.IV);


  21:            // select the appropriate algorithm

  22:            var encryptor = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);


  24:            // get the key

  25:            var key = encryptor.CreateSymmetricKey(CryptographicBuffer.DecodeFromBase64String(this.symmetricKey));


  27:            // do the encryption

  28:            var encryptedText = CryptographicEngine.Encrypt(key, input, iv);


  30:            // convert the encrypted text into hex format and show it in textbox

  31:            this.TxtCipher.Text = CryptographicBuffer.EncodeToHexString(encryptedText);

  32:        }

Code to Decrypt

   1: /// <summary>

   2:         /// The decrypt.

   3:         /// </summary>

   4:         /// <param name="sender">

   5:         /// The sender.

   6:         /// </param>

   7:         /// <param name="e">

   8:         /// The e.

   9:         /// </param>

  10:         private void Decrypt(object sender, TappedRoutedEventArgs e)

  11:         {

  12:             if (!string.IsNullOrEmpty(this.TxtCipher.Text))

  13:             {

  14:                 // as the encrypted string is in hex format decode it and convert back to binary

  15:                 var input = CryptographicBuffer.DecodeFromHexString(this.TxtCipher.Text);


  17:                 // decode the initialization vector

  18:                 var iv = CryptographicBuffer.DecodeFromBase64String(this.IV);


  20:                 // specify the algorithm use the same one which was used with encryption

  21:                 var decryptor = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);


  23:                 // get the key , same should be used which was used for encryption

  24:                 var key = decryptor.CreateSymmetricKey(CryptographicBuffer.DecodeFromBase64String(this.symmetricKey));


  26:                 // Do the decryption

  27:                 var decryptedText = CryptographicEngine.Decrypt(key, input, iv);

  28:                 this.TxtPlain.Text = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedText);

  29:             }

  30:             else

  31:             {

  32:                 new MessageDialog("First encrypt").ShowAsync();

  33:             }

  34:         }


I talked about using the cryptography methods when you are developing a WinRT app. Apart from this operating system also has a built in support for bit locker (Only available in Pro and Enterprise versions) which helps to preserve the enterprise data and can be remotely wiped off with the Mobile Device Management Software like Windows InTune. Last but not least when your app depends on the web services it is always good practice to invoke them securely over SSL. The source code accompanying this post article is available on my GitHub account. Do share your valuable feedback.

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.

Next Page »

The Rubric Theme. Blog at


Get every new post delivered to your Inbox.

Join 73 other followers