Previous month:
August 2008
Next month:
October 2008

September 2008

Extend WPF: Add your own keywords and functionality to XAML with Custom Markup Extensions

WPF is highly customizable and flexible. Also what makes WPF even better is XAML, the markup based declaration language, which is often associated to WPF but not limited to it. I am pretty sure whoever is reading this post have already wrote few XAML based UI and many of the readers have created a full blown WPF application. We use many XAML extensions in our day to day applications. All of these extensions derive from the System.Windows.Markup.MarkupExtension class. We use extensions like StaticResource, DynamicResource etc in everyday Xaml.

The curly braces “{ }” notation tells the XAML processor that it has encountered an extension and the Xaml processor responds accordingly by evaluating the text inside the curly braces. Here is an example on how extensions are used.

  <SolidColorBrush x:Key="mybackground" Color="#FF8080C8"/>
<Rectangle Height="84" Name="rect1" Width="162" 
Fill="{DynamicResource mybackground}" />

In the above sample we have declared a rectangle element and we taking the fill color dynamically from the ‘mybackgorund’ solid color brush which is defined within the windows resources. By taking approach this we can also use the same brush in other WPF elements.

Markup Extensions

MarkupExtension is the base class for any Xaml extension. Just like .NET attributes which ends the name with the word ‘Attribute’, the markup extensions end the class name with the word ‘Extension’. They should be used in Xaml syntax without the appended word ‘Extension’ just like attributes.

The above diagram shows how extensions are inherited and how those classes are used with curly brace (“{ }” ) markups.

Custom Markup Extensions

XAML cannot do everything, and in any good application we need to write code. However if there are some code that are repetitive and we want to declare those code in XAML markup we can write our own markup extensions.  In order to do so we need to inherit from the abstract class System.Windows.Markup.MarkupExtension and implement the abstract method ‘ProvideValue’. See the signature of the provide value method below ...

public object ProvideValue(IServiceProvider serviceProvider)

Then we need to reference our namespace in Xaml and use the extension.

Relative Color Markup Extension : A Custom Extension example

There are many cares where we need to have a relatively lighter or darker color of a certain color. For example if we are designing a button and when the mouse moves over the button we want a lighter shade of the normal color of the button and when mouse is down we want a darker color. In order to do these things in XAML we would have to write triggers and 3 different colors. Lets assume we start with color blue and define blue, a lighter shade of blue and a darker shade of blue, then we would be in trouble if we decide to make our button green and have a light green, green and dark green color. We would have to change all 3 colors. Now wouldn’t it be nice if we could define one color and then have darker and lighter shade of it? If we decide to change color then we would have to change the base color only. See the example below

Colro Example

Writing the custom markup extension

Lets name the custom markup extension that we are writing as RelativeColor, so the class name has to be ‘RelativeColorExtension’.

public class RelativeColorExtension : MarkupExtension

Here our class inherits from MarkupExtension and we are explicitly declaring that the return value is a brush. The MarkupExtensionReturnType attribute lets you specify the return type. However this is optional. You might not want to declare that, specially where the return type determined at runtime and can vary.

Before we proceed further lets see and example of just how this extension will be written in Xaml so that we can better explain how we will write the extension.


The Styles

In our custom markup extension we have 3 styles, Lighten, Normal and Darken. We will specify the base color and which style to apply in the Xaml markup. So we define an enum in the custom extension class like this.

public enum MorphStyle
    Lighten, Normal, Darken

We need to define a property that will store this style

private MorphStyle _style = MorphStyle.Normal;
/// <summary>
/// Which style to render 
/// </summary>
public MorphStyle Style
    set { _style = value; }

The Reference Color

Since we need to refer to a color in the resource dictionary, we need to have a property for that as well.

private string _baseColorKey = null;
/// <summary>
/// This is the key of the reference color. This should be defined in a
/// dictionary 
/// </summary>
public string BaseColorKey
    set { _baseColorKey = value; }

In this variable the key (x:key attribute) of the reference color will be stored.

Overriding the ProvideValue

We simply have to override the ProvideValue method first like this.

/// <summary>
/// Overridden method returns the brush based on style and base color reference
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public override object ProvideValue(IServiceProvider serviceProvider)

By the time this method is called the Xaml Processor have already set the two properties from our Xaml declaration ( we will see the Xaml declaration a little later in the post). So we have the resource key of the base color and how to render it. We are going to keep our resources in the Application resource file and load from there.

// Check if the key is valid
if (!string.IsNullOrEmpty(_baseColorKey))
    object obj = Application.Current.FindResource (_baseColorKey);
    if (obj != null)
        coreColor = (Color)obj;

Deciding based on the style

Since we have found the referenced color, we can create a lighter or a darker version of it. (Disclaimer: The code we used to get darker or lighter version of a color in the static methods DarkenColor and BrightenColor are very simple and basic and may be a very simple and lame implementation. This was done in order to keep the irrelevant code simple so that we can easily transfer the idea of custom markup extension to the reader). Since the style property of the extension was filled by the Xaml Processor we can act on their values. See code

// Lets return a solid color brush 
if (this._style == MorphStyle.Lighten )
    return new SolidColorBrush(BrightenColor(coreColor));
else if (this._style == MorphStyle.Normal)
    return new SolidColorBrush ( CopyColor (coreColor));
    return new SolidColorBrush(DarkenColor(coreColor));

Using our extension in Xaml code

Xaml is not a WPF specific markup language, but it is most widely used in WPF and silverlight. In WFP Xaml files start element you will find code that look like this ...


Then we use x:Key and other “x” based namespaces because the it is generally imported under ‘x’ namespace . We have build our custom extension in a dll and we need to import that as a name space to our code.

Custom Namespaces in Xaml

In order to use classes from another dll in Xaml we will need to introduce a custom namespace. The format for defining a custom namespace looks like this


In our case both the assembly name and the namespace is ‘MyXamlExtensions’ and the namespace that we will use is ‘ce’ which is a short for custom extension. So the entry for our custom extension will look like this in the root element of the Xaml document.


We are going to import the namespace in the application resource file and define a style for a rectangle object

<Color x:Key="MyBackColor" R="#80" G="#80" B="#C8" A="#FF" />
<Style x:Key="ActiveRectangle" TargetType="{x:Type Rectangle}" >
    <Trigger Property="IsMouseOver" Value="True">
      <Setter Property="Fill" 
         Value="{ce:RelativeColor BaseColorKey=MyBackColor,Style=Lighten}"/>
    <Trigger Property="IsMouseOver" Value="False">
      <Setter Property="Fill" 
         Value="{ce:RelativeColor BaseColorKey=MyBackColor,Style=Normal}"/>

You can see in the above example that  we are referencing the ‘MyBackColor’ as a reference and using our markup extension without the word ‘Extension’ at the end and we are also setting the BaseColorKey and Style property. We have defined the style in a way so that a lighter shade of the color is assigned to the rectangle when mouse is over the rectangle at other time the normal shade is used. Also please notice that the properties are defined in the extension with comma separation. Now we will set the style to rectangle like this.

<Rectangle Height="93" Name="rectangle1" Stroke="Black" 
    Width="243" Style="{DynamicResource ActiveRectangle}" >

If we want to change the mouse over and normal colors we could just change the base color defined at ‘MyBackColor’.

Now that we have created an extension we can use it anywhere. We can write our common tasks in code and make them into extensions and re-use them in different Xaml markups.

Sample source code

You can download the custom markup extension code from from here. Have fun and let me know what extension did you make.

kick it on

Make Google Chrome Take Less Memory

Earlier I wrote how chrome is taking huge amount of memory because it is running one process for each tab ( It seems that Chrome supports other process models as well. Here are the process models for Chrome browser

1. Process Per Tab (default model)

2. Process Per Site: One process per website. For example a user with two tabs opened at Gmail and another opened at facebook will have the two google tabs running in the same process. (default model)

3. Single Process ( walla! this is what I was looking for)

All this was cleared by blogger Marc Chung at his post Chrome's Process Model Explained. Right now I am running Chrome in a single process.

At the chrome shortcut pass the appropriate command like option to control Chrome’s behavior.


Here is how you edit the shortcut to run with different process model. Open up the properties tab of the Chrome browser short cut and edit it like the image below


So here I have 3 shortcuts to Chrome in my desktop. See the picture below


So now I can run chrome anyway I want. Chrome has become my second browser of choice after Opera. Chrome will occupy less memory now.

Google Chrome: I liked it at first but … its memory usage is ABSURD!.

Update: I am retracting my statement that Chrome takes huge memory and saying that Chrome takes huge memory by default. But you can change that by changing settings. See the update on Make Google Chrome Take Less Memory

There has been a huge ripple in the web since Google released the Chrome browser. At first I really liked chrome, specially its speed and ease of use. As a developer I work on Microsoft technologies and I like the services that Google provides. When Google and MS competes it is a win win situation for me, the consumer.

I am sure you have read many blog posts by now hearing praises of Chrome, and I would have sung praises too … but its memory usage is absurd.

My favorite browser is opera and I use a custom hand written configuration of Opera and I also use the Flock browser beta with the Firefox 3 engine. After using for a day or two I was kind of  thinking that Chrome would replace my use of Firefox.

I have a habit of of going through my daily list of articles in the Google reader and opening the new articles in different windows. By the time I am done selecting the items to read I have about 50 tabs open which is very easy in Opera. Unfortunately I was amazed at Chrome’s irresponsible memory usage. For each single open window or tab it at least has a process running.

Think again … one process for one tab. Are you nuts!!

Here is a screenshot of the tabs I had opened ( only 4 tabs )


Now take a look at the processes and memory usage by chrome


There are 7 processes running for those 4 tabs and taking 161 MB of RAM. I feel scared to even think about how much memory it would have occupied if I had opened 50+ tabs like I usually do.

Unless Google changes this model, I would stick to my good old Opera and Flock for heavy browsing.

kick it on

Secure Yourself: Avoid Hackers & Keyloggers & all forms of malwares

Everyone now days knows the need to secure his computer with millions of virus and other forms of malware running amok on the internet. In this post I will try to recommend the tools that I use for securing myself.  By the way, if you have a Anti-virus running do not think that you are safe. Even if you have firewall running, still do not think yourself as safe. I have many security softwares running and I do not consider myself safe from harm. I am going to recommend a few software that I use in order to secure myself. Some of these are free and some are paid versions.


Avira Antivirus: I use Avira antivirus ( free-edition ) to protect myself from viruses. Avira is probably best free the fast anti-virus with very high detection rate (my opinion). I actually researched a little before selecting this as the anti-virus to  shield myself with. See my post on anti-virus selection : My quest to select a good Antivirus for the year 2008.

One downside of using Avira is the nag screen which itself looks like adware. Avira would pop up a screen a few times a week where it would advertise for its paid version. And that ad looks horrible.  Everything else is good. If you do not want the nag screen to be there then buy it. I did not.

By the way, Avira has already paid off, as I have been protected several times from virus attack by it.


I have used Norton, Zone Alarm and all other crap firewall at point in my life. But for last few years I have switched to better firewalls. I use Outpost Security Suite which gives me superb granular control over the network access of my computer. But before I discuss that I would like to point to the one below

Comodo Firewall Pro (Freeware): Comodo is a free online security company which sells SSL certificates, Identity Projection etc. They give you a barrage of free security softwares which includes free firewall, free anti-malware and  free anti-virus. Now that is what I call a deal, you cant beat free! I have not tried their anti-virus or the anti-malware but I have used their firewall for almost a year and it is rock solid. At that time only outpost had anti leak support. Comodo was the other firewall that gave such detailed control. Now if you are someone who wants to see what is going on at your network then this the the firewall for you.

Check this out: Screenshots of Comodo Firewall Pro running.

Now you might be be thinking … what is their business model and why am I getting a free firewall that is so awesome. This is what they are saying at their web site

You must be wondering - how can we stay in business by giving away high quality solutions that all other software vendors sell. Simply, Comodo's main revenue comes from authenticating web business with SSL certificates (e.g. we put the padlock on websites).

Outpost Security Suite (Not Free): I was instantly in love with the Outpost Firewall. Later on I decided to buy the security suite they provided. And I am still using it. It is so far the best firewall I have seen. Outpost monitors everything – and by everything I mean everything there is to be monitored. It can run in a very easy mode for a novice user or a very secure highly detailed mode for the advanced user.

It has 3 level of rules, Low Level Rules, Global Rules and then the Application rules. You can modify each. It has superb host projection and critical system components like registry and startup items protection. Here are a few screen shots of the host protections configurations screen and the web control configuration screen and finally the application configuration screen. 

outpost outpost2 outpost3

Also outpost has extremely powerful network connections and log views.

Outpost is my first choice, but if you do not want to spend money then you still have option to use Comodo.

Anti Keylogger

Even after you have used anti-virus and firewall software there could be unknown malwares hidden in your PC (outpost detects keylogging attempts usually). Someone could have written a custom keylogger software that no anti-virus would be able to detect. Such event could be your worst nightmare. Not only the hacker will have access to you computer password but he may have your office email passowrd, your personal email password, your credit card number, your paypal account password, your facebook password etc. Think of what would your life if someone has those and used your logins for his benefits. So it is best to have anti keylogging software installed.

Keyscrambler (Free and Paid): KeyScrambler is a software that installs as a kernel mode driver and encrypts the keyboard strokes and decrypts them at the application that you are using. So any keylogger software that is trying to get a hold of the keystrokes will have a set of scrambled meaningless junk.

The free edition of Keyscrambler support IE, Flock and Firefox browser and that should take of most of you. However I use Opera as my primary browser, and flock as secondary browser and do not use IE at all, so had to buy the paid version to support Opera and the messenger softwares like, MSN, GTalk, Yahoo, Skype. The paid version also supports outlook, thunderbird, office applications.

VPN Service

When ever you are using internet on a non secured connection a hacker might intercept the data and steal you data and passwords. Also your ISP can track what site you are visiting, they can see your email messages and IM chat text if they want to. However you can avoid this unsecured scenario with a VPN service. When you are connected to a VPN connection the data is encrypted and cannot be decrypted. There are many VPN services available. When you connect to these VPN service the data is decrypted at the VPN server and sent from there, so no one can track your internet footprint.

I use a 1 year VPN service from a commercial VPN provider and when ever I access sensitive information I connect to the VPN service. One cool thing about this provider was access to Pandora music web site. Pandora only allows you to listen if you are in the US. Since the VPN service is at US, when I connect to it, it detects my location to be in US and lets me listen to songs.

Password Manager & Encrypted Disk (Freeware)

KeePass: There are several password managers available but I use KeePass, an open source password manager which seemed most advances and robust. Try it.


True Crypt: I also use TrueCrypt to mount a drive where I can store all my sensitive data in encrypted format. Truecrupt is also a free open source application. One good feature in TrueCrypt is plausible deniability. You can create hidden volumes within a TrueCrypt volume where you will store the real sensitive data and in the outer volume you can store some sensitive looking files. If someone tortures you and asks you for password then you can tell them the password to the outer volume and they will think you have given the abductor the right password.

FreeOTFE: For storing sensitive data one windows mobile phones you can use Free OTFE which lets you have encrypted drive in a windows mobile phone.


I hope this post have been helpful to solve your security problems.