Favor Composition over Inheritance

Even though you “could” solve a problem by inheriting, see if there’s another option that doesn’t require you to inherit and compose your object of other helper object instead.
The above statement sounded so sophisticated when I read it first, that I wanted to put it in my blog. Yet there is something deep in my heart that tells me: don’t through away your years of experience and achievements gained by reusing objects through inheritance.

Original Thought

When 2 classes, let’s say Car and Vehicle implemented as follows:
    public class Vehicle
        public void Drive()
            Debug.WriteLine(“Vehicle is driving.”);
    public class Car : Vehicle
        public void Drive()
            Debug.WriteLine(“Car is driving.”);
By default the new implemented Drive method in the Car class hides the implementation in vehicle for any reference of Car type. So the following instances are expected:
    Vehicle v = new Vehicle();
    // output : Vehicle is driving.
    Car c = new Car();
    // output : Car is driving.
But the next one might cause unexpected situations when the construction occurs in a method far from calling the drive method.
    Vehicle x = new Car();
    // output : Vehicle is driving.
The output for the last call (Vehicle x) changes to “Car is driving.” when the Drive method in Vehicle is defined as virtual and in the Car defined as override.
Looks like the problem is solved.
But sometime I have a factory class creating some instances for me and I simply declare my variables and request for an instance:
Vehicle x = Factory.GetBMW();
This means that the place I use the instance might have no knowledge of how the instance is created and might not even know how they are implementing the Drive method.
For me, the ideal situation might be when I have a reference to a class of type Vehicle, I like it to drive as Vehicle. And when I want to have a Car that drives as a Car, I will define my reference as a Car.
Vehicle x = Factory.GetBMW();
Car y = Factory.GetBMW();
I can see that my point might not be important for BMW factory and they would rather to create a Car that drives the same way, no matter who is driving it.

Suggested Solution

The Composition over inheritance suggests that Car and vehicle does not inherit from each other. To make sure that they both are sharing functionality, the BMW class needs to implement both interfaces.
Let’s say that the following code is where we like to achieve:
    x.Drive();                  // output : Simply driving.
    (x as ICar).Drive();        // output : Car driving.
    (x as IVehicle).Drive();    // output : Vehicle driving.
To get there I have introduced three interfaces as follows:
    public interface IDrivable
        void Drive();
    public interface IVehicle : IDrivable
        void Drive();
    public interface ICar : IDrivable
        void Drive();
The BMW needs to implement them as it suites. This implementation has nothing to do with the way they are overloaded.
public class BMW : IVehicle, ICar
        void IVehicle.Drive()
            Debug.WriteLine(“Vehicle is driving.”);
        void ICar.Drive()
            Debug.WriteLine(“Car is driving.”);
        void IDrivable.Drive()
            Debug.WriteLine(“Simply driving.”);

Notify Database changes to ASP.NET pages

In the old times there were two ways of getting notifications from the database into the ASP.NET pages.

  1. writing to a file (simply create or delete an empty file) in a specific location where a CacheDependency can listen to and callBack a method on change.
  2. implement an HttpHandler that gets the notification with a parameter of what is changed, and let the database send an http request to the IIS server on a trigger.
I am sure there could be worse methods but even these two have a lot of complications in a secured architecture with high performance requirements, like we have these days.

Fortunately, since SQL-Servet 2000, there is a new component implemented into SQL-server called Service Broker that act on changes in tables that are marked to be notified on change. Internally they write to a specific table mentioning about the change.
In order to configure a database for Service Broker you can call a statement like this:
Use Northwind
For more information about Service Broker see the MSDN.
Next, you need to set the ASP.NET to recieve the notification via dependencies. To do so , you need to add the command object to the dependency:
// Create the dependency.
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);
// Add a cache item that will be invalidated if one of its records changes
// (or a new record is added in the same range).

Cache.Insert("Employees", ds, empDependency);
To start the notification on application service you need to add the following to the Global.ascx.cs in Application_Start
It is a good practice to stop the notifications on Application_End
Once this is implemented, you can get the notifications through the OnChange event of the SqlDependency class.

Localizing ASP.NET Tips

There are two kind of localizations:

  • Local resources are specific to a page.
  • Global resources are shared throughout the site

If your site contains many folders, you might have an App_LocalResources subfolder in each folder of your site.

<asp:Button ID="ButtonFind" runat="server" Text="Find" CssClass="submitButton" meta:resourcekey="ButtonFindResource1" />

<asp:Localize ID="LabelTitle" runat="server" Text="Customer Lookup" meta:resourcekey="LabelTitleResource1"></asp:Localize>

The Text property of the Button control is to aid the developer at design time.

ASP.NET will use the key to find and match on any property that might be set inside the resource file as meta:resourcekey.<PropertyName> or ButtonFindResoure1.Text:

<data name="ButtonFindResource1.Text" xml:space="preserve">



<data name="ButtonFindResource1.Tooltip" xml:space="preserve">

     <value>Click this to start the search action</value>


Accessing a Local resource in C# could be done as follows:

Textbox1.Text = GetLocalResourceObject(“Textbox1.Text”).ToString();

Accessing a shared global resource in C# could be done in one of the two followings:

Textbox1.Text = Resources.ResourceFileName.Textbox1Text;

Textbox1.Text = GetGlobalResourceObject(“ResourceFileName”, “Textbox1Text”) as string;

The methods GetGlobalResourceObject  and GetLocalResourceObject can come handy when the resources does not exist at compile time and might be provided as a separate dll at runtime.

Show an object instance as an xnl on your page

This sample code demonstrates how to show an instance of an object in XML format on a page. It encodes the xml serialized string and dumps it as a code into a placeholder.
    public void ShowXmlObject<T>( T instance)
        var ms = new MemoryStream();
        System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, Encoding.Unicode);
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        serializer.Serialize(writer, instance);
        ms.Position = 0;
        var reader = new StreamReader(ms);
    public string IndentXml(string xml)
        var p = xml.LastIndexOf(“?>”);
        if (p > 0)
            xml = xml.Substring(p + 2);
        var doc = new System.Xml.XmlDocument();
        var settings = new System.Xml.XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = ”  “;
        settings.NewLineChars = “rn”;
        settings.NewLineHandling = System.Xml.NewLineHandling.None;
        var  sbOutput = new StringBuilder();
        var writer = System.Xml.XmlWriter.Create(sbOutput, settings);
        return sbOutput.ToString();
    public void LogCode(string message)
        placeResult.Controls.Add(new Literal() { Text = "<pre><code>" + message + "</code></pre>" });

jQuery.Ajax versus Server-side event handler

This sample demonstrates two ways of getting address from the server: using server-side event handler versus calling jQuery.Ajax

The following is the markup that provides two fields with javascript call on the change event. It also provides a button that is wired to a server side methode:


         <h3> Address Test</h3>

         tabbing from the textboxes will verify if calling the webservice is required.

         <table  width="100%"><tr><td><table><tr>

                             <td> Huisnummer *</td>

                             <td><div class="FieldContainer">

                                     <asp:TextBox  runat="server"  ID="textboxHousenumber"  ClientIDMode="Static"

                                         CssClass="TextField TextField02" onchange="VerifyAddress();"

                                         ValidationGroup="KlantAddress" />



                             <td> Postcode *</td>

                             <td><div  class="FieldContainer">

                                     <asp:TextBox  runat="server"  ID="textboxPostcode"      ClientIDMode="Static"

                                                 CssClass="TextField TextField02"  

                                                 MaxLength="7"  onchange="VerifyAddress();"






                   Server side call:<br  />

                     <asp:Button  ID="Button1"  runat="server"  OnClick="ShowAddress"  Text="Get Adres"  ToolTip="CustomerDataController"  />

                     <asp:Label  runat="server"  ID="lblAddress"  />



Assume we have a we DBLLayer that provides an address or throws an exception.
The event handler would be something like this:


     /// <summary>Server side event handler</summary>

     public  void  ShowAddress(object  sender, EventArgs  e)




             var  adres = DBLayer.GetAddress(textboxPostcode.Text, textboxHousenumber.Text);



         catch  (Exception  ex)


             LogError("Error :- "  + ex.Message);




And the Javascript will look like this:


     function  VerifyAddress() {

         // This method is calling the ShowAddress only if both parameters are filled in.  

         $("#<%=lblAddress.ClientID %>" ).text("" );

         var  postcode = $("#<%=textboxPostcode.ClientID %>" ).val();

         var  huisnummer = $("#<%=textboxHousenumber.ClientID %>" ).val();

         if  (postcode && huisnummer && parseInt(huisnummer) > 0) {

             $("#<%=lblAddress.ClientID %>" ).text("calling the server" );

             var  data = "{ postcode:’"  + postcode + <span’ , huisnummer: "  + huisnummer + " }" ;


                 type: <span’ ,

                 contentType: <span’application/json;’ ,

                 data: data,

                 dataType: <span’ ,

                 url: <span’ ,

                 success: OnGetAddressComplete,

                 error: OnErrorReceived




     function  OnErrorReceived(xhr, ajaxOptions, thrownError) {

         var  message = jQuery.parseJSON(xhr.responseText);

         $("#<%=lblAddress.ClientID %>" ).text(

             "ERROR ("  + xhr.status + ") – "  + message.Message);


     function  OnGetAddressComplete(result) {

         // display the result

         var  adres = result.d;

         $("#<%=lblAddress.ClientID %>" ).text(

             adres.Straat + <span”  +

             adres.Huisnummer + <span’,’  +

             adres.Postcode + <span”  + adres.Plaats);


And finally the webservice will be like:


     [System.Web.Services.WebMethod ()]

     public  static  Adres GetAddress(string  postcode, string  huisnummer)


         if  (!IsPostcode(postcode))

             throw  new  Exception ("Invalid Postcode." );

         int  hNr = 0;

         if  (!Int32 .TryParse(huisnummer, out  hNr))

             throw  new  Exception ("Invalid house number." );

         var  result = DBLayer .GetAddress(postcode, huisnummer);

         if  (result == null )

             throw  new  Exception (" Unknown address." );

         return  result;



     public static bool IsPostcode(string  zipcode)


         var  ZipcodeRegex = @"^[1-9][0-9]{3}[a-zA-Z]{2}[\s]*$" ;

         Regex  r = new  Regex (ZipcodeRegex, RegexOptions .IgnoreCase);

         Match  m = r.Match(zipcode);

         return  m.Success;



How do I secure my browser – Part

I came across a web address that has phishing software. It was www.secure-logins.com. I figured out that this is not the only address in tis domain that has the worm, any address ending to the same domain is doing the same harm. So I had to find a way to stop all the requests going from my browser (or even better from my house) to this domain. This is what I did:

I. Tell your browser never go to that domain.
II. let your router know that this domain should be filtered.

Although the second way is enough to stop the worm but I thought some people might not have the feature in their router to do that, so I also mentioned the first one.

1. In the Internet Explorer go to Menu Tools->Internet Options and when the Internet Options pops up click on the Security tab.
2. You will see different zones. The important zone is : Restricted sites. Click on it.
3. Once you selected the Restricted sites click on the Sites button. This will pop up another window called Restricted Sites which holds a list of sites that you don’t want your browser coincidently or willingly go there.
4. In th text box under “Add this site to the zone:” type the following:
5. Press the Add button and you will see that the address is added to the list
6. Press the Close button and you will be back to the Internet Options.
7. Click OK,
that’s it

My router is a D-Link and have an option to filter any requests going to a specific address from any machine at my home. You should check your router’s website which is often to e accessed by
In the Advanced menu you will find a link to go to Website Filter. When you get there you will see an empty list where you can add your preferences. The ‘Website Filter‘ option allows you to set up a list of Web sites you would like to deny through your network.
Add the same address there:

thats all.

Common Buses and their Max Bandwidth

Nice article from: http://networking.ringofsaturn.com/PC/pciexpress.php

PCI Express in all it’s flavors: 1x, 2x, 4x, 8x, 16x and 32x all have much greater bandwidth than basic PCI.

Common Buses and their Max Bandwidth
PCI 132 MB/s
AGP 8X 2,100 MB/s
PCI Express 1x 250 [500]* MB/s
PCI Express 2x 500 [1000]* MB/s
PCI Express 4x 1000 [2000]* MB/s
PCI Express 8x 2000 [4000]* MB/s
PCI Express 16x 4000 [8000]* MB/s
PCI Express 32x 8000 [16000]* MB/s
IDE (ATA100) 100 MB/s
IDE (ATA133) 133 MB/s
SATA 150 MB/s
Gigabit Ethernet 125 MB/s
IEEE1394B [Firewire] 100 MB/s

Persistor of a Serializer

We had this situation in my last project where we wanted to have some of our objects to get easily serialized into a specific table. Therefor we had to add up to the Serializer an new generic class that uses the Serializer to get the sream to put into a table.
In this example we have several classes like Article, Order, etc. and we wanted to give them a specific addition that would implement the Save and Load for all these classes. So we wanted to have something like this :

public class Article : Persistor

and then later use it as follows:

// Read the last saved Article filter
private Article filter = Article.Load();

// and do something with it and finally save it back to Database



Well, to achive that we implemented the Persistor class as follows:

using System;
using System.Collections.Generic;

/// <summary>
/// Provides the persistance methods for the filter classes.
/// It reads and writes the content in an xml format into the Filter table
/// </summary>
/// <typeparam name="T">The type of the filter. This type should derive from Persistor&lt;T&gt; and have an empty constructor</typeparam>
public class Persistor<T>
where T : Persistor
<T>, new()
/// <summary>
/// Saves this filter as the default filter for the current user.
/// </summary>
public void Save()
// Serialize the current filter instance
Serializer<T> serializer = new Serializer<T>();
string xml = serializer.Serialize(this as T);

// The filter class is a data class that handles the saveing of a record
Data.Tables.Filter filter = Persistor<T>.LoadFilter(true);

// Actual save to database
filter.Value = xml;

/// <summary>
/// Loads the default filter for the current table and user.
/// </summary>
public static T Load()
Tables.Filter filter
= Persistor<T>.LoadFilter(false);

// Deserialize
T currentFilter = null;
if (filter != null && !string.IsNullOrEmpty(filter.Value))
<T> serializer = new Serializer<T>();
= serializer.Deserialize(filter.Value);
= new T();

return currentFilter;

/// <summary>
/// Loads the Filter for the current user and table from the database.
/// </summary>
protected static Tables.Filter LoadFilter(bool createNew)
string tableId = typeof(T).Name;
int userId = UserContext.Current.User.ID;

// Load current filter, if available, otherwise create a new filter instance.
Tables.Filter filter = Tables.Filter.GetForUserTable(userId, tableId);
if (filter == null && createNew)
= new Data.Tables.Filter();
= userId;
= tableId;

return filter;