Wednesday, December 22, 2010

Performance Wizard for Silverlight

 
Microsoft has released the first service pack for Visual studio 2010, although the service pack is marked as beta it comes with a “go live” license. Along with it two other service packs are released Team Foundation Server 2010 SP1 Beta and .NET 4.0 SP1 Beta. For Silverlight developers they have packed two update in the Visual studio 2010 SP1 Beta.

1) Silverlight 4 tools for Visual Studio 2010 : “The Silverlight 4 tools are now included along with Silverlight 3 support”, all it means that you will not have to install Silverlight 4 tools separately.

2) Performance Wizard for Silverlight : This will enable the users to profile the silverlight application performance directly through visual studio, user can create profiling reports and save them.

You can get the download links from Brian blog, he has nicely detailed all important updates in the service packs
http://blogs.msdn.com/b/bharry/archive/2010/12/07/vs-tfs-2010-sp1-beta-has-released.aspx 
Once you have downloaded the web installer, be patient as the install will take some time to download the packages and install, for me the process took around an hour from start to finish.  After successful installation you will be ask to restart your computer, now you visual studio is all set to start profiling your silverlight application using the wizard.

The Performance Wizard is very simple let us go set by step through it, open a existing silverlight project or create a new project. To launch the ‘Performance Wizard’ go to the main menu find Analyze –> Launch Performance Wizard…

image

Performance wizard page 1 of 3 should be displayed, CPU Sampling must be selected by default if not the check mark the radio button before CPU Sampling.

image
Performance wizard page 2 of 3, on this page you will find a list of projects depending on the structure of your solution. Typically for a silverlight project you will find the silverlight application and the web application in the list, select your silverlight application and click the ‘Next’ button.

image 

Performance wizard page 2 of 3, is just a summary that say’s all the information needed has been collected. Make sure on this page you have the check mark on the check box labeled as Launch profiling after the wizard finishes. When you click finish the application should open in your default browser.

image

If you are not running as administrator you might get an error saying “ Unable to open profiler driver, would you like to upgrade credentials ..“ . Just click ‘yes’  and provide admin credentials if needed.

image

Once above steps are done the Performance Explore with be populated with a structure similar to the image below. The performance wizard has created two folders  Reports and Targets.

image

Ok now lets do simple performance test,Let us create a simple application and see how performance report looks like.Create a silverlight application, In your main page add a button and on the click of the button we should have a function that does some kind of cpu intensive activity. I have simply created nested loop to keep the cpu busy for a while but you can write any code that will be cpu intensive.

  1:         private void Button_Click(object sender, RoutedEventArgs e)
  2:         {
  3:             for (int i = 0; i < 100000; i++)
  4:             {
  5:                 for (int j = 0; j < 10000; j++)
  6:                 {
  7:                 }
  8:             }
  9:         }

Now follow the steps shown above to generate profiling report using the wizard, run the project and click on the button couple of time and then close the browser. Visual studio will bring up the visual report based on the samples collected during the performance analysis. Below figure show the result of my test, one can clearly identify in the graph the spike in CPU during the first and second click.Interesting fact is Studio will automatically bring show a call tree of the method that are expensive in terms of resource. For our case the event handler Button_Click() does a expensive for loop and studio was able identify the method and display the call hierarchy.


image

 
 

Thursday, November 18, 2010

Context Menu with check mark

In Silverlight 4 it is very easy to create a context menu, basically a context menu appears on right click action and has choices depending on the state of the UI element. Silverlight toolkit has a in build context menu control, if you do not have the toolkit you will have to install it from Microsoft website. Once installed you can add context menu control to your visual studio toolbox by doing a right click on toolbox –> Choose Items…-> Silverlight Components –>select ContextMenu and press ok. Now you can drag and drop the context menu from the toolbox in your layout editor, a name space xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit" should be added to the XAML and three dll’s will be added in the project references

image

In the main page XAML add the below code, here we have a text box with a context menu it has two items one has a Icon and the next item does not have a icon. Our intention is to show a check mark in front of the menu item when a user first time clicks on the menu and toggle it on consecutive clicks. To display a icon in front the toolkit has element called <MenuItem.Icon> the icon is of type content so it can be anything like a image, textbox, grid. I could have select a Image of a check mark and used it as icon but the problem is my application has numerous themes where the user can change the color of every item in UI, so in this case we will have to create different image for each an every color. Instead of Image I use a textblock that will have the ascii equivalent of the check mark and surround the textblock with a Border. To display ascii character in textblock we should use the format “&#<ascii code>;”

  1:   <Grid x:Name="LayoutRoot" Background="White">
  2:         <TextBox Text="Context Menu test" Height="200" Width="200" >
  3:             <toolkit:ContextMenuService.ContextMenu>
  4:                 <toolkit:ContextMenu>
  5:                     <toolkit:MenuItem x:Name="AlertWindow" Header="Display Window" 
  6:                                       Click="AlertWindow_Click" >
  7:                         <toolkit:MenuItem.Icon>
  8:                             <Border BorderBrush="Blue" Background="LightBlue"
  9:                                     BorderThickness=".5"  >
 10:                                 <TextBlock Text="&#8730;" FontWeight="Bold" 
 11:                                      Foreground="Green" TextAlignment="Center"/>
 12:                             </Border>
 13:                         </toolkit:MenuItem.Icon>
 14:                     </toolkit:MenuItem>
 15:                     <toolkit:MenuItem x:Name="Close" Header="Close" >
 16:                     </toolkit:MenuItem>
 17:                 </toolkit:ContextMenu>
 18:             </toolkit:ContextMenuService.ContextMenu>
 19:         </TextBox>
 20:     </Grid>

Now you can add a click event on the menu item, and in the xaml.cs add a event handler. The code shown below will basically toggle the visibility of the border.

  1:     private void AlertWindow_Click(object sender, RoutedEventArgs e)
  2:     {
  3:         Border border = ((sender as MenuItem).Icon as Border);
  4:         if(border.Visibility==Visibility.Collapsed)
  5:             border.Visibility = Visibility.Visible;
  6:         else
  7:             border.Visibility = Visibility.Collapsed;
  8:     }


The final output in the browser will look like this
image
Additional benefit of this technique is modularity and maintainability because you do not need different images for differently themed application.One can easily match the color of the context menu check mark icon with the theme of your application as the colors are stored in resources. For simplicity I will keep the theme color’s in the <UserControl.Resources> but for your application the theme location might in a resource dictionary, the final XAML should look like this .

  1:     <UserControl.Resources>
  2:         <SolidColorBrush x:Name="MenuTickBorderColor" Color="Brown"/>
  3:         <SolidColorBrush x:Name="MenuTickFillColor" Color="Yellow"/>
  4:         <SolidColorBrush x:Name="MenuTickFontColor" Color="Brown"/>
  5:     </UserControl.Resources>
  6:    
  7:     <Grid x:Name="LayoutRoot" Background="White">       
  8:         <TextBox Text="Context Menu test" Height="200" Width="200" > 
  9:             <toolkit:ContextMenuService.ContextMenu>
 10:                 <toolkit:ContextMenu>
 11:                     <toolkit:MenuItem x:Name="AlertWindow" Header="Display Window"
 12:                                       Click="AlertWindow_Click" >
 13:                         <toolkit:MenuItem.Icon>
 14:                             <Border BorderBrush="{StaticResource MenuTickBorderColor}"
 15:                                     Background="{StaticResource MenuTickFillColor}"
 16:                                     BorderThickness=".5"  >
 17:                                 <TextBlock Text="&#8730;" FontWeight="Bold"
 18:                                            Foreground="{StaticResource MenuTickFontColor}"
 19:                                            TextAlignment="Center"    />
 20:                             </Border>
 21:                         </toolkit:MenuItem.Icon>
 22:                     </toolkit:MenuItem>
 23:                     <toolkit:MenuItem x:Name="Close" Header="Close" >                      
 24:                     </toolkit:MenuItem>
 25:                 </toolkit:ContextMenu>
 26:             </toolkit:ContextMenuService.ContextMenu>
 27:         </TextBox> 
 28:     </Grid>

Now one can change the three SolidColorBrush in resources to change color of the icon on the context menu. Here I have shown three differently themed icons of the context menu.

  1:    <UserControl.Resources>
  2:         <SolidColorBrush x:Name="MenuTickBorderColor" Color="Blue"/>
  3:         <SolidColorBrush x:Name="MenuTickFillColor" Color="LightBlue"/>
  4:         <SolidColorBrush x:Name="MenuTickFontColor" Color="Green"/>
  5:     </UserControl.Resources>

image

  1:     <UserControl.Resources>
  2:         <SolidColorBrush x:Name="MenuTickBorderColor" Color="Red"/>
  3:         <SolidColorBrush x:Name="MenuTickFillColor" Color="LightPink"/>
  4:         <SolidColorBrush x:Name="MenuTickFontColor" Color="Red"/>
  5:     </UserControl.Resources>

image

  1:    <UserControl.Resources>
  2:         <SolidColorBrush x:Name="MenuTickBorderColor" Color="Brown"/>
  3:         <SolidColorBrush x:Name="MenuTickFillColor" Color="Yellow"/>
  4:         <SolidColorBrush x:Name="MenuTickFontColor" Color="Brown"/>
  5:     </UserControl.Resources>

image

The above technique might not be suitable for every scenario and using images might be more easy. I am not a big fan of writing code in backend rather I prefer to follow MVVM pattern where ever possible, In future post I will write about how to connect context menu using the view model

Monday, August 9, 2010

Cloning a generic List<T>

Today we had to do a copy operation on a generic list to accomplish a business logic on our server. The situation was such that we had retrieved some data from the database and then store it in a List<T> which was on our corporate servers. Based on a formula we had to remove some elements from the list , a copy of the original collection should be persisted so in case of any error/exception the original data can be resorted.

You might already knows how to implement IClonable interface but for those who are not aware, I will explain the method to clone the generic list.
To make a copy of generic list we need to perform this steps

1) Derive our data class from IClonable
2) Implement the members of IClonable
3) Write a extension method .on List<T>

IClonable is the way C# implements the copy constructor the basic fundamental is to create a copy of the object . The System.ICloneable interface defines a method of create a new instance of a class with the identical value as an existing instance. There are two ways of cloning

1) Shallow Cloning – all objects are copied but only link of the referred objects are copied
2) Deep Cloning- all the object are copied along with the referred objects

shallow_cloning

The above figure describes a shallow copy of objects looks in memory, we have a class object called DataClassObj1containing two objects which we call as the ContainingObject. In the second part of the figure we have another object DataClassObj2 which is a shallow copy of DataClassObj1. DataClassObj1 and DataClassObj2 are having reference to same object, so changes made through any of the DataClassObj will be reflected in the other on the other hand if it was a deep copy then both the objects would have their individual ContainingObjects and changes made in one would not be reflected in the other.

A shallow copy is by far the easiest way to clone your class, shallow copy in .net can be done by MemberwiseCloning and every object inherited from Object class can use this method to get a shallow clone. Below is the sample code illustrating how to use ICloneable and MeberwiseClone();

  1:    [Serializable]
  2:     public class ContainingObject
  3:     {
  4:         public string sName;                
  5:     }
  6: 
  7:     [Serializable]
  8:     public class DataClass:ICloneable
  9:     {
 10:         
 11:         public ContainingObject ContainingObject1;
 12:         public ContainingObject ContainingObject2;
 13: 
 14:         public DataClass()
 15:         {
 16:             ContainingObject1 = new ContainingObject();
 17:             ContainingObject2 = new ContainingObject();
 18:         }
 19:         public object Clone()
 20:         {
 21:             return MemberwiseClone();
 22:         }
 23:     }

Now the problem with shallow cloning is that if you change a reference object in the clone the original reference is also changed. for example in below line of code when the line 4 is executed both d1.ContainingObject1.sName and d1.ContainingObject1.sName are changed to “Amin”.

  1: DataClass d1 = new DataClass();
  2: d1.ContainingObject1.sName = "Vikas";
  3: DataClass d2 = d1.Clone() as DataClass;
  4: d2.ContainingObject1.sName = "Amin";



For a deep cloning of the object we can use below extension method that will deep copy any object

  1:   using System.IO;
  2:     using System.Runtime.Serialization.Formatters.Binary;
  3:     public static class DeePCloneExtensionMethod
  4:     {
  5:         public static T DeepClone<T>(this T a)
  6:         {
  7:             using (MemoryStream stream = new MemoryStream())
  8:             {
  9:                 BinaryFormatter formatter = new BinaryFormatter();
 10:                 formatter.Serialize(stream, a);
 11:                 stream.Position = 0;
 12:                 return (T)formatter.Deserialize(stream);
 13:             }
 14:         }
 15:     }

Monday, July 12, 2010

Test custom silverlight installation without uninstalling silverlight


How many times have you came across situation where you need to test how your custom silverlight installation would look on a client’s PC who do not have the sivlerlight plug-in installed. Recently one of my friend had this problem and found him self in trouble by trying to uninstall the silverlight plug-in and manually changing the registry entry he wasted couple of hours uninstalling and installing silverlight and cleaning windows registry.

A very simple solution to this problem is to disable the silverlight plug-in from the browser settings.

We will see how to disable the silverlight plug-in for popular browsers like
1) IE 8
2) Firefox
3) Chrome

For IE 8 running on Windows 7 you need to right click on IE and select run as administrator, once the IE is opened click on tools tab and select Manage Add-ons.

RunAsAdministrator      ManageAddOn

After that you need to select the ‘Toolbar and Extension’ then on the right side panel under Microsoft Corporation you will find Microsoft Silverlight. At the bottom of the dialog box a click on the Disable button will do the trick, once the plug-in is disabled the browser will behave as if the plug-in is not installed.

disable

For IE 6 and Windows XP the steps are  more or less the same, open IE 6 go to the Tools menu
and select the Internet Options.

IE6_1 

Now click on the button named as “Managed Add-ons…” that will open a the Add on Manger window , scroll down to select the Microsoft Silverlight and then in the settings section select the disable radio button.

IE6_2IE6_3

 

For Firefox version 3.6.3 on Windows 7 it is more simple all you need to do is just go to the tools menu select the Add On option and a dialog box will pop-up,

fox_plugin

now click on Plugins and scroll to find the Silverlight Plug-in there you will find the Disable button.fox_plugin1

 

For Google Chrome version 5.0.375.99 we will have to write some command line arguments because chrome has not provided any fancy UI to disable/enable plugin’s. Already many people has requested/complained about getting nice UI.

Anyway to disable the silverlight plugin all you need to do is run this command line but there is a little problem it this will disable all the plugin’s for Chrome.

chrome.exe -disable-plugins

and to enable as you might have guess the command line is

chrome.exe -enable-plugins

for my Win 7 machine the chrome.exe is installed at this location

C:\Users\loginname\AppData\Local\Google\Chrome\Application\

 

Well i found out two more things while writing this post
1) First is that silverlight cannot be installed on 64-bit version of IE8 you will get a message as below.

cannot be installed on 64 bit version

2) Second is that  IE 7 installed on Windows 7 cannot have silverlight

IE 7 and Win 7