Understanding Cryptography in WindowsRT

crypto

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.

WHAT PLATFORM HAS TO OFFER

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

HASHING

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

   7:  

   8:            // get the raw input string

   9:            var textToBeHashed = this.TxtInput.Text;

  10:                

  11:            // convert string into binary

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

  13:  

  14:            // declare sha512

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

  16:                

  17:            // hash the binary data using SHA512 algorithm

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

  19:  

  20:            // encode the hashdata to Base64 format

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

  22:            var msgDialog = new MessageDialog(encodeToBase64String);

  23:                

  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.

RANDOM DATA

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();

  15:             

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

  13:  

  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.

SYMMETERIC ENCRYPTION

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

  11:  

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

  16:  

  17:            // convert plain text to binary

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

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

  20:  

  21:            // select the appropriate algorithm

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

  23:            

  24:            // get the key

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

  26:            

  27:            // do the encryption

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

  29:  

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

  16:  

  17:                 // decode the initialization vector

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

  19:  

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

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

  22:                 

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

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

  25:  

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

CLOSURE

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

 

INTRODUCTION

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.

SETTING FOCUS ON FIRST TEXTBOX IN THE FORM

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.
  3.     
  4.     var $firstTextBox;
  5.     $firstTextBox = $("input", $(element)); //get the input tag
  6.     setTimeout(function() {
  7.         $firstTextBox.focus(); //set the focus
  8.     }, 2);
  9. };

PROCESSING BASED ON THE DATABASE LOOKUP VALUES

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;
  3.  
  4.     function updateTotal() {
  5.         var price;
  6.         var discount = 0;
  7.  
  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.         }
  13.  
  14.         order.Total = price * (1 – discount / 100);
  15.     }
  16.  
  17.     // When the order's Customer changes, update its total by attaching the change event listener.
  18.     order.addChangeListener("Customer", updateTotal);
  19. };

 

AUTO REFRESH OF PARENT SCREEN

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. };

 

OTHER GREAT RESOURCES OF LIGHTSWITCH

Cheers and Keep learning new stuff 🙂

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;
  5.  
  6.         public event PropertyChangedEventHandler PropertyChanged;
  7.  
  8.         private void NotifyPropertyChanged(String propertyName)
  9.         {
  10.             if (PropertyChanged != null)
  11.             {
  12.                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  13.             }
  14.         }
  15.  
  16.         public string CustomerName
  17.         {
  18.             get
  19.             {
  20.                 return this.customerNameValue;
  21.             }
  22.  
  23.             set
  24.             {
  25.                 if (value != this.customerNameValue)
  26.                 {
  27.                     this.customerNameValue = value;
  28.                     NotifyPropertyChanged("CustomerName"); //Magic strings
  29.                 }
  30.             }
  31.         }
  32.  
  33.         public string PhoneNumber
  34.         {
  35.             get
  36.             {
  37.                 return this.phoneNumberValue;
  38.             }
  39.  
  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;
  6.  
  7.         public event PropertyChangedEventHandler PropertyChanged;
  8.  
  9.         private void NotifyPropertyChanged([CallerMemberName]
  10.                                            String propertyName = "")
  11.         {
  12.             if (PropertyChanged != null)
  13.             {
  14.                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  15.             }
  16.         }
  17.  
  18.         public string CustomerName
  19.         {
  20.             get
  21.             {
  22.                 return this.customerNameValue;
  23.             }
  24.  
  25.             set
  26.             {
  27.                 if (value != this.customerNameValue)
  28.                 {
  29.                     this.customerNameValue = value;
  30.                     NotifyPropertyChanged(); //Look ma no magic strings
  31.                 }
  32.             }
  33.         }
  34.  
  35.         public string PhoneNumber
  36.         {
  37.             get
  38.             {
  39.                 return this.phoneNumberValue;
  40.             }
  41.  
  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;
  6.  
  7.         public event PropertyChangedEventHandler PropertyChanged;
  8.  
  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.         }
  28.  
  29.         public string CustomerName
  30.         {
  31.             get
  32.             {
  33.                 return this.customerNameValue;
  34.             }
  35.  
  36.             set
  37.             {
  38.                 if (value != this.customerNameValue)
  39.                 {
  40.                     this.customerNameValue = value;
  41.                     NotifyPropertyChanged(() => CustomerName);
  42.                 }
  43.             }
  44.         }
  45.  
  46.         public string PhoneNumber
  47.         {
  48.             get
  49.             {
  50.                 return this.phoneNumberValue;
  51.             }
  52.  
  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;
  8.  
  9.         public MainPageViewModel(IEventAggregator eventAggregator)
  10.         {
  11.             _eventAggregator = eventAggregator;
  12.         }
  13.  
  14.  
  15.        
  16.  
  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.         }
  28.  
  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.         }
  48.  
  49.         protected override void OnActivate()
  50.         {
  51.             _eventAggregator.Subscribe(this); //Register for event
  52.             base.OnActivate();
  53.         }
  54.  
  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.

Dynamic Theme Switching in Silverlight Prism App

 

INTRO

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.

GETTING STARTED

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.

 

blueThemeBlackTheme

 

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>
  13.  
  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.                 }
  23.  
  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.

CLOSURE

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.

Windows Phone geocoding with Rx

INTRODUCTION

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.

WHAT IS RX

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.

USING Rx IN WINDOWS PHONE FOR GEOCODING

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.
1)Microsoft.Phone.Reactive
2)System.Observable
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.

GeoCodewithRxDemo

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.

CONCLUSION

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

How to create Tag Cloud in Silverlight

 

WHAT IS A TAG CLOUD

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.

SCENARIO

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.

top10stocks

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.

SILVERLIGHT IMPLEMENTAION

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.

CLOSURE

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.