Introduction to Core 1.0

I had a privilege to be invited by Agile Testing Alliance , Vadodara chapter to talk about Core 1.0 . It was very interactive sessions and the participants asked some really good questions.

Here is the synopsis of my talk

What is Core ?

It is a lean stack from Microsoft to develop the modern web apps built from ground up and is most revolutionary version since first was released in 2002
Today it is available RC1 update 1 which comes with golive license so this means that this framework is production ready.

Cross platform

This is a game changer and USP about this framework.  It works seamlessly on Windows, OSX and Linux. The same code base runs directly on the metal, and remember this is different from the Mono Framework. In fact the CoreClr is around 11 meg and is shipped along with your application as a nuget package

Unified programming model

In previous versions of MVC 5 and webapi 2 each API existed in different namespaces but there are now one. So if you remember in previous version of mvc you need to inherit the class from the controller and when you need to develop a webapi you need to inherit from apicontroller. But now everything comes under one controller class. same applies to routing, actions, filters etc.

Modular components

Every feature now is shipped as a single nuget package. So if you want to use mvc features download it and register as middleware, You want identity authentication do the same and you are up and running. ConfigureServices where your register your middleware services and Configure is where you use them.  You can write your own custom middleware too.The sample code below give you fair idea of these methods

Middleware and built in Ioc

In previous versions of DI and IOC were optional but now it is part of the framework and it comes as a built in feature out of the box. You are free to replace it with your own favourite DI framework too.

Modern tooling

You can take the advantage of all the modern tooling which JavaScript world supports, In fact bower can be used for all client side packages whereas nuget can take care of server side packages and dependencies. Use Gulp or Grunt for task runners. Remember that in the older versions you had bundling and minification feature in mvc this is no more there now and it is replaced by this task runners to care of it

DNX context


DNX stands for Dot net Execution. The DNX and middleware works in hand to hand to process the request pipeline. Below diagram represents the complete picture.


Actually, when the request is made, it first arrives at the web server,web server then invokes the DNX which will load the CLR and then looks for an entry point, the Main method, in your application and executes it. The main method configures the pipeline by using the Startup class, and the request is pushed through the pipeline, processed by the middleware which will produce the response.

Cloud Optimized

As it has low footprint deployment it is your best choice for cloud based solutions.

Github OSS


We all know that Microsoft has embrace the OSS in a big way and core is no more different. If you wish to contribute to this you can very well do it. Just create a pull request or fork it on Github. There are really some very good contributions from community.

Easy install site is a single source of truth for core. Right from documentation to tools everything is available here. It is quite smart to recognize your OS version and suggest the appropriate download link.

Multiple choice of IDEs

Though I gave the demo on Visual studio. You have plethora choice for IDE like Code , Atom and many others.

Presentation materials

The sample demo application and slide decks can be downloaded from my Github repo. I’ve heard that recording has also been done. I would check out with the organizers and will upload later once it is available to me.


My thoughts on Xamarin Forms


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.

Understanding Cryptography in WindowsRT


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.

Lessons learned with LightSwitch HTML Client project



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 🙂

Transforming WinForms Camera control to WPF in MVVM style



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.

Implementing INotifyPropertyChanged in C#5.0 way


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.

Windows Phone Tasks in Caliburn Micro Way

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.