Previous month:
March 2008
Next month:
May 2008

April 2008

Selected posts on CLR, threading, Internationalization and WPF

I have been professionally working in the software industry for over 9 years but I am relatively new to the blogging community. I have only started to blog around 5 months ago. I have selected some of my previous posts which I liked. Please find the links below

CLR Fun Stuff: How is my C# code converted into machine instructions?
This post decribes the process of MSIL being converted to binary instruction bt the JIT compiler.

WeakReference: GC knows the Best
A basic look at the Weak Reference class which helps to re-aquire data left for garbage collection.

Multi-core CPU Caching: What is volatile?
What is the impact of the volatile keyword in the world of multi-cored CPUs

Dll heaven: Executing multiple versions of the same assembly
How can you execute code from different versions of an assembly in a single process.

Spider's Web: Spawning threads in .NET, The Basics
A basic look at threading. It was going to be 1st part of a 5 part series, but it was discontinued as there was a good free e-book available on .NET threading.

Basic WPF: Stylize standard tabs into Aqua Gel
How can you change the look of the standard controls with styles in WPF

Fun with Generics: Using constraints to limit Generics applicability using the 'where' keyword
A less used but powerful architecture tool, type limiting in generics

Internationalization: Creating a custom culture
How can you add support for your language/culture if .NET does not have built in support for the language like my language ' Bangla'

kick it on DotNetKicks.com

Basic WPF: Stylize standard tabs into Aqua Gel

I was making this WPF based application on weekends and wanted it to have a gel like look. I did not want to create a new control instead I wanted to make sure that I used WPF styles to change the look of the tab. I decided to share this experience so that anyone who wants to do this does not have to do any research. The things that I will do to make this happen required very simple and basic WPF knowledge and is thus considered as kid stuff to many WPF pros. But none the less, I am interested to share this. Here goes ...

Download GelTab.zip

Styling and Templates

Basic WPF ControlWPF has the capability of applying styles like css does to html. Any WPF control that we use has something called a control template. The control template defines how the control will look. The control template may contain triggers also. Let try to understand from the diagram below how WPF renders a control UI.

The basic WPF control has a template which it uses to render the UI from the control definition. This can be changed by applying a custom style. In order to do that we must first define a custom style where we can modify the template for the control. By doing so we will able to completely change the look and behavior of the control. We can even make a tab look like a listbox a tree. The possibilities are endless. However today we will only try to make the tab look like blue gel based (Aqua) tab. Which should look like this (by the way. I have not yet decided on the blue shade ... it still looks a little ugly) ...

Tab Look

In order change a tab to look like this I will need to write a style and modify that style.

Basic WPF Control with Styling The control code will stay the same but the style template will change. In order to this we will create a resource dictionary. So we have created a resource dictionary called GelTabStyle.xaml. In order for this to be used by the application the this will need to be added into the application dictionary ( we can also put it in the file with the tab instance, but that is not a good practice). When we add such a resource dictionary from the Visual studio or Microsoft Expression Blend the IDE automatically modifies the App.xaml to include the resource dictionary. Here is how our App.xaml should look like ...

<Application.Resources>        
  <
ResourceDictionary>
    <
ResourceDictionary.MergedDictionaries>
      <
ResourceDictionary Source="GelTabStyle.xaml"/>
    </
ResourceDictionary.MergedDictionaries>
  </
ResourceDictionary>       
</
Application.Resources>

WPF Control Composition & Templates

As I have already stated that a WPF control has templates to define its UI, what are these templates made of? They are made of WPF shapes, other WPF controls, triggers and GDI resource definitions. To have a very simple idea see the diagram below...

WPF Control Anatomy 

A control has a template which is made of WPF basic elements and controls, and each of those controls have templates which have WPF elements and controls in them. We can define a style in a resource dictionary (in our case the GelTabStyle.xaml) and inside a style we can define our custom control template. Before we go any further lets try to look up a tab controls template.

Anatomy of a Tab

If you pry open the template that renders the tab control with Expresssion Blend then you would find that there is a grid with 2 rows. The first row contains the tab item headers and second part contains the tab body. See the diagram below ...

TabControlStructure

Since we want the tab headers to be gradient gel like we will define a style for those and will call them "GelTabItem" and also will need to change the bottom container and will call that "GelTab" style. For our case we only the the tab headers to placed at top ... so we wont bother with placing them at left, right or bottom.

Inside the resource dictionary we have defined some colors and some gradient brushes to do our painting, which looks like this ...

 <Color x:Key="TabItemGradStart" R="#AA" G="#AA" B="#BB"/>
<
Color x:Key="TabItemGradEnd" R="#EE" G="#EE" B="#FF" A="#FF"/>
...
...

<
LinearGradientBrush x:Key="TabBackgorundBrush" StartPoint="0,0" EndPoint="0,1" >
     <
GradientStop Offset="0" Color="{StaticResource TabItemGradStart}"/>
     <
GradientStop Offset="1" Color="{StaticResource TabItemGradEnd}"/>
</
LinearGradientBrush>
<
LinearGradientBrush x:Key="TabBackgorundBrushSel" StartPoint="0,0" EndPoint="0,1" >
     ...
     ...

So we have defined the basic drawing resources, lets look at the style header

<Style x:Key="GelTabItem" TargetType="{x:Type TabItem}">

If you look carefully that you would find that this style can only apply to a TabItem object and also it will only apply to those tab items which have their style set to "GelITabtem". By the way if we wanted to make sure all the tab items in the application would use this style (except the ones that has explicit style defined) then we would remove the x:Key keyword from the style. That would ensure that all tab items by default will have the style applied. However that is not our goal.

TabItems

Lets see how the xaml code makes the header part with tab items to be styled. The diagram below will make it clear.

TabHeader

As you can see that we have used a border with rounded corners to make a border for the gel tab item, we have also used a rectangle to fill the gradient area of the button. We used the gradient brush that we defined at the start of the resource file.

Triggers

In order make sure that the selected tab has one color and the unselected tabs have different color we used triggers to change the back color. See the code snippet below

<ControlTemplate.Triggers>
  <
Trigger Property="IsSelected" Value="True">
    <
Setter TargetName="TabItemBackgorund" Property="Fill"
      Value="{
StaticResource TabBackgorundBrushSel}" />
  </
Trigger>
  <
Trigger Property="IsSelected" Value="False">
    <
Setter TargetName="TabItemBackgorund" Property="Fill"
      Value="{
StaticResource TabBackgorundBrush}" />
  </
Trigger>
  <
Trigger Property="IsEnabled" Value="False">
    <
Setter TargetName="TabItemBackgorund" Property="Fill"
      Value="{
StaticResource TabBackgorundBrushDisabled}" />
  </
Trigger>
</
ControlTemplate.Triggers>

When the tab is selected use a brush called "TabBackgorundBrushsel" as the fill value of the rectangle and when it is not selected we use the brush called "TabBackgorundBrush" to have an effect of unselected item. Similarly we use "TabBackgorundBrushDisabled" to fill the rectangle for the disabled tab item. See figure ...

SelectionBrush

Tab Body

If you observe the tab body style then you would see a control with the "controlpresenter" tag which actually contains the controls that we place inside the tab.

<ControlTemplate TargetType="TabControl">
  <
Grid>
  <
Grid.RowDefinitions>
    <
RowDefinition Height="Auto"/>
    <
RowDefinition Height="*"/>
  </
Grid.RowDefinitions>
  <
Border BorderBrush="Transparent" BorderThickness="0" Grid.Row="1"
    
CornerRadius="5,5,5,5" Background="Transparent" Padding
="5,5,5,5" >
     <
Border BorderBrush="Gray" BorderThickness="1" CornerRadius="5,5,5,5"
       
Background="{
StaticResource TabBackgorundBrushSel}"  >
        <
ContentPresenter ContentSource="SelectedContent" />               
     </
Border>
   </
Border>
   <
TabPanel Grid.Row="0" IsItemsHost="true"/>
   </
Grid>
</
ControlTemplate>

If we observe the xaml above we would see that the body resides in second row and the header panel (<TabPanel> in xaml) resides at top row this is how the bottom and top placement of the two different parts are defined. We have made the body rounded and also padded it and used the selected brush to paint it.

Using the styles with the tabs

Styling Strategy  There are two ways to apply the style. Depending on how we want the tabs to look it may change. One strategy is to use css class like style that we made and apply them the control items. Another is to make the apply the style whole application wide. In order to make it application wide we would have to remove the x:key that names the style.

Now if we want to make it specific for a control we use the style tag to specify the style like the code below ( the part marked in bold letters)

<TabControl Style="{DynamicResource GelTabControl}" >            
   <
TabItem Header="Rapid Note" Style="{DynamicResource GelTabItem}">


kick it on DotNetKicks.com

Using Expression Blend with VS2008: Invalid project File Error

Recently I had to reinstall my laptop, so I also installed VS 2008 and Expression Blend. Expression Blend is a better WPF designer and VS2008 still has to lot of bumps to fix like frequent crashes on WPF, showing errors that are not there etc. So I tried to use Expression blend but it seemed that when ever I tried to open a VS2008 project I get an error message. The message tells me that the project file is invalid because there in an Import directive there. When I looked closely I found this

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

When Blend finds this tag it cannot load the project. So I tried removing this line and the project loaded with errors. Then I downloaded the Service Pack 1 for Microsoft Expression Blend from this location and installed and Walla! All my problems were gone. Please note that according to MS installing Blend 2 September Preview will also fix this issue.


Dynamic Language Runtime: What is it?

On many blog entries around the world, specially from the bloggers from Microsoft, one would find a numerous mention about the Dynamic Language Runtime (also known as the DLR). Specially since many MS bloggers are writing a lot about IronPython, DLR is reflected in their topics. So I was questioning myself a few days ago about the DLR and how is it different from the CLR? Here are my findings.

Dynamic Programming Languages

The first and most common example of dynamic programming languages is Javascript, where one can define types and its methods at runtime. By definition, a dynamic language is a high level programming language whose behavior at runtime is similar to its behavior at compile type. So the compile time behaviors in normal programming languages can also execute at runtime for the dynamic languages. For example a class (type) can be defined at runtime or its methods can be defined at runtime in JavaScript. So a types behavioral properties can be extended at runtime. The type or the object system may be defined or changed at runtime, even the inheritance tree might be modifiable.    

Dlr1    

These behaviors can be emulated by standard runtime like the .NET CLR but, it takes a lot of work to do that. Thus the DLR is born.

Dynamic Language Runtime

First of all let me state that the CLR already has support for dynamic languages, however adding the DLR on top of CLR makes it much more easier to implement a dynamic language and makes communication between multiple dynamic languages a breeze just the way CLR did it for multiple .NET languages. This added layer on top of the existing CLR provides the following services.

Shared Dynamic Type System (I am calling this DTS)
Unlike the CTS where type safety is a crucial requirement the DTS allows us to morph the types at runtime. So we can add methods to the a type or modify it. Also two dynamic languages can talk to each other with same vocabulary.

Dlr23_2

Dynamic Method Dispatching
Ever heard of C++ virtual function tables? Dynamic dispatching is dynamically being able to change which code executes for a method at runtime. There is also another form of dynamic dispatching which is per instance dynamic method dispatching. For example at runtime we can define what code will execute for the method of a class, which is simple method dispatching. But if we are able to define for an instance of a class which code will execute for the instance of that class type that would be instance based dynamic dispatching.

Dynamic Code Generation
Code generation capabilities at compile time is called dynamic code generation. The generated code may have the capability to modify itself. For example, JavaScript eval() function is very powerful and it is able to compile and modify itself.

Hosting Capabilities
Just like the CLR, the DLR also has a hosting API.

Summary

So the DLR makes it a whole lot easier for two dynamic languages to have shared code. The keyword here is sharing. Also the DLR is built on the existing CLR. Microsoft has its DLR source code available at codeplex with IronPython project. IronPython is the first sample DLR language and MS plans to implement DLR in VB.NET 10 and next Jscript.

kick it on DotNetKicks.com


SQLMetal woes: No sqlmetal.exe with VS 2008 Team Edition

Even despite all the performance issues I wanted to use LINQ queries for one of my pet projects. One of the design goals was to use Sql Server Compact edition 3.5 so that I get to use a file as a database and also that I can port the data access and code logic to compact framework so that it can be used with Windows Mobile devices. Using compact edition of sql server 2005 is kinda like using a comptible microsoft made firebird sql database. A few days ago I reinstalled my OS and wanted to try the Visual Studio 2008 team edition trial and that is when all the trouble started.

First, the linq to sql class generator SqlMetal.exe was nowhere to be found. It seemed that the Visual Studio 2008 Team Edition trial did not come with the SqlMetal.exe. Infact the folder 'C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\' where the executable resides with other executables is empty. But I have changes to my database schema and did not want to hand write the changes.

Then I tried generation by dragging the sql server compact dbatabase tables onto the linq to sql (dbml) designer, but got the message that "The selected object(s) use an unsupported data provider". This is annoying. Tomorrow I will try to download the Visual C# 2008 Express edition and install that to get a copy of SqlMetal.exe. I wish Microsoft were more careful with what content they have in their DVDs.