November 2006 - Posts

MSDN Roadshow 2007 [London Olympia] Registration Open Again!

I tried to register for this event last week but I couldn't as the registration page said the event was full. Now it seems it has been a mistake and the registration is open again.

London's roadshow is on the first day of Spring (21 March) and the agenda for the event looks very promising... LINQ, C# 3.0, VB9, ASP.NET AJAX, Entity Framework/Entity Data Model in ADO.NET and WPF(/E). 

Thanks to Ian Cooper and Daniel Moth for posting the link to the London .NET User Group mailing list.

Posted by Mehran Nikoo | with no comments
Filed under:

Instance Constructors

It's construction time! Read this post if you want to refresh your mind on how object construction works. In this post, I will focus on instance constructors in C# and will leave the static constructors (aka type initialisers) to the next post.

Every time you use the new keyword to instantiate an object, the instance constructor of the class is called to initialise the object before it is used.

Each class can have multiple instance constructors with different signatures and access modifiers. If you do not provide an instance constructor for your class, C# compiler will create one for you. The access modifier for the default constructor will be public unless you are defining an abstract class where the access modifier will be set to 'protected' ('family' in IL terminology).

public class Customer
{
}
-----------------------------
.method public hidebysig specialname rtspecialname
       
instance void .ctor() cil managed
{
  // Code size 7 (0x7)
  .maxstack 8
  IL_0000: ldarg.0
  IL_0001: call instance void [mscorlib]System.Object::.ctor()
  IL_0006: ret
} // end of method Customer::.ctor

This means that all classes have at least one constructor defined when compiled to IL, with one exception: if you define your class as static, the compiler will not create a default constructor. In fact, you will get a compile-time error if you explicitly define an instance constructor for a static class, which makes sense.

When compiled to IL, instance constructors are emitted as .ctor methods. The compiler first generates the initialisation code for the instance fields, if there are any. Instance field initialisers are injected into the very beginning of the constructor. Fields are inistialised in the same sequence as they are defined in the class and cannot reference any other instance members (although they can reference the static members of the class).

Now let's see how instance field initialisers look like when compiled to the IL code:

public class Customer
{
  public int EmployeeId = 0;
  public string DepartmentId = "";
}
---------------------
.method public hidebysig specialname rtspecialname 
        in
stance void .ctor() cil managed
{
  // Code size 26 (0x1a)
  .maxstack 8
  IL_0000: ldarg.0
  IL_0001: ldc.i4.0
  IL_0002: stfld int32 ConstructorSamples.Customer::EmployeeId
  IL_0007: ldarg.0
  IL_0008: ldstr ""
  IL_000d: stfld string ConstructorSamples.Customer::DepartmentId
  IL_0012: ldarg.0
  IL_0013: call instance void [mscorlib]System.Object::.ctor()
  IL_0018: nop
  IL_0019: ret
} // end of method Customer::.ctor

You may also notice that Customer's constructor is calling the constructor of System.Object. Before you can create an instance of any object, its base class needs to be constructed first. This goes all the way up to System.Object (in this case System.Object was the immediate parent). So right after emitting the code to initialise the instance fields, the compiler emits an instruction to call the base class's constructor. In order to do so, it looks at the definition of the constructor to see whether it explicitly mentions any specific constructor on the base class (using the base keyword). If it does, it calls the specified constructor on the base class. Otherwise, it calls the parameterless constructor on the base class. This is also the case if the child class doesn't have any constructor. You will get a compile time error if you do not provide a constructor for your class and the base class does not have a parameterless constructor.

Instead of using the base keyword, you can also use this, which allows you to call another constructor on the same class rather than the base class. You can chain the constructors on the same class but eventually, the last constructor in the chain needs to call the base class's constructor.

Something that you need to take into account when overloading the constructor on a type is that inline field initialisers are injected into evey single contructor on the class, unless a constructor is using this keyword to call another constructor on the same class. So the compiled IL code becomes larger in size if you have lots of field initialisers in a class with multiple constuctor overloads. In most cases you don't need to be worried about this but if you are, you can chain the constructors by using this keyword.

So we saw how compiler injects inline field initialisation logic and the call to the base class construcor into the IL code. In the last step, the compiler emits the implementation of the constructor as defined by the developer.

In the next example, the Customer class inherits from Person, which has a parameterised constructor. Since we have defined the parameterised constructor for Person, the compiler does not create a default one for us. This means the Customer's constructor has to specify which constructor should be called on the Person class when an instance of Customer is being created.

public class Person
{
  public Person(string knownName)
  {
  }
}

public class Customer: Person
{
  public int EmployeeId = 0;
  public string DepartmentId = "";
  public Customer(string firstName, string lastName): base(firstName + " " + lastName)
  {
    Console.WriteLine("Customer created");
  }
}
---------------------
.method public hidebysig specialname rtspecialname
        instance void .ctor(string firstName, string lastName) cil managed

{
 
// Code size 51 (0x33)
  .maxstack 8
  IL_0000: ldarg.0
  IL_0001: ldc.i4.0
  IL_0002: stfld int32 ConstructorSamples.Customer::EmployeeId
  IL_0007: ldarg.0
  IL_0008: ldstr ""
  IL_000d: stfld string ConstructorSamples.Customer::DepartmentId
  IL_0012: ldarg.0
  IL_0013: ldarg.1
  IL_0014: ldstr " "
  IL_0019: ldarg.2
  IL_001a: call string [mscorlib]System.String::Concat(string,string,
string)
  IL_001f: call instance void ConstructorSamples.Person::.ctor(string)
  IL_0024: nop
  IL_0025: nop
  IL_0026: ldstr "Customer created"
  IL_002b: call void [mscorlib]System.Console::WriteLine(string)
  IL_0030: nop
  IL_0031: nop
  IL_0032: ret
>} // end of method Customer::.ctor 

So to wrap it up: the compiled code initialises the member variables first, then calls the base class's constructor and finally emits the actual constructor code.

Myth: Instance constructor are always run before any other method on that instance.

- Instance constructors are not run when a class is deserialised.
- The overridden methods in the class may be executed before the constructor. This happens if the constructor of the base class calls any virtual methods that are overridden in a child class. Let's see how this can happen...

public class Person
{
  public Person()
  {
    Console.WriteLine("Person created");
    Load();
  }

  protected virtual void Load()
  {
    Console.WriteLine("Person loaded");
  }
}
---------------------
public class Employee: Person
{
  public Employee()
  {
    Console.WriteLine("Employee created");
  }

  protected override void Load()
  {
    Console.WriteLine("Employee loaded");
 
}
}
---------------------
Now, if your create an instance of the Employee class by running the following line of code:

Employee
employee = new Employee();

You will get the following result, which may not be desirable.

Person created
Employee loaded
Employee created

In order to avoid the confusion and potential logical errors, it is a good development practice not to call a virtual method in the instance constructor. This should be considered as an anti-pattern for the Template Method pattern: Using the constructor as the "Template Method" for calling virtual operations on a base class.

Posted by Mehran Nikoo | 1 comment(s)
Filed under: ,

My.Computer.WindowsExperienceIndex = 5.6

I installed Windows Vista on my "very" new PC yesterday. I think I can live with Windows Experience Index of 5.6! (my last experience was a rating of 1.0 on my 3-year old Dell laptop...). The poorest performer is the CPU, which is an Intel Core 2 Duo E6600, running at 2.8GHz (overclocked) so I assume I could achieve a base score of 5.9 if I used a Core 2 Extreme processor (without overclocking).

  
                               Click for a larger view [opens in a new window]


Ordering Experience

Why did I say "my very new PC"? Because it was born yesterday morning. I don't normally mention any vendor names on my blog but I can't resist it this time. As suggested by one of my colleagues, I placed my order on Overclockers UK web site at 12:26pm on Friday 24 Nov and I received an instant (automated) confirmation for my order. At 12:43pm (same day!) I received another email entitled "Your order has shipped". In its body the email was saying that my order was packed and ready for collection by the courier and it included the reference number too. And guess what? On Saturday morning around 9am I was woken up by the courier knocking at the door. I am extremely pleased with the service I received from Overclockers UK, well done! I hope other people have had (and will have) a similar experience with them.

Disclaimer: I am not a sales agent, don't work for Overclockers UK (I live in Surrey and they are based in Staffordshire!) and don't receive any freebies from them either!!!

As you can imagine, I didn't go back to bed and started assembling the PC instead.


What is inside?

Gigabyte GA-965P-DQ6 ICHR8 Mainboard
Intel Core 2 Duo E6600 2.4 GHz
2 x Corsair XMS2 Dominator Twin2X2048 PC2-6400 C4D
Western Digital Raptor X 150GB 10,000RPM
Galaxy GeForce 6950GT 512MB DDR3


Windows Vista Setup Experience

The next "Thank You" goes to Microsoft. The whole setup process took less than 20 minutes (setup files were on the hard disk) and was very smooth. Maybe two or three automatic restarts as I was drinking coffee. By the time Windows was preparing itself for the first use, I was thinking of the next step... going to Gigabyte and Galaxy web sites to get the drivers for Vista (when I installed Windows XP on the same machine in the morning, I had to install drivers for Graphics Adapter, SATA/USB 2.0 and Gigabit LAN before I could use those features). My thinking was interrupted by a nice fading effect on the startup screen displayed at 1600x1200 resolution. I called myself a "fool" as I should have remembered that Windows Vista comes with thousands of drivers so it is unlikely that you need one unless you are using older items. A quick visit to Device Manager confirmed this as all drivers were working fine and Aero Glass kept dazzling my eyes as I navigated through the Control Panel.

Windows operating system has come a long way and although many of us are happy with the current previous version (Windows XP with SP2), I believe Windows Vista is going to rock and will make more happy customers for Microsoft.


Even More Credits

go to hardware manufacturers including Intel for creating faster processors with lower power consumption and Gigabyte for creating a mainboard with excellent layout design and effective cooling technology.

I have to stop now, it's the time for a nice Sunday lunch in the rain...

Posted by Mehran Nikoo | with no comments
Filed under:

Merging Menus in Non-MDI Applications

Although the MenuStrip class in WinForms 2.0 is originally designed to support MDI applications, it is a life saver when it comes to other applications types. Some of the new applications prefer SDI style over MDI. One of our current smart client projects is using the SDI style and we have been missing the automatic menu management features of the MDI world. Most of you know that in MDI applications, the menus from the child menus are automatically merged into the MDI parent window when the child windows are activated.

Our application follows the SDI style so we don't have this luxury.  The application has a main window and allows the users to create multiple instances of child forms that show Customer Details. These Customer Details forms have their own menus and everything is fine as long as they are displayed as floating windows. But as soon as they are docked to the centre of the main window (or shown as tabbed documents, similar to open files in Visual Studio 2005), we do have a requirement to merge their menus to the parent window. Obviously, we need to unmerge these menu items once the child window is closed or reverted back to the floating mode.

The previous version of our application (based on .NET 1.1) had its own menu subsystem, which used a custom and complex mechanism to manage the menus and merge/unmerge them as needed. After the upgrade to .NET 2.0, the ToolStripManager class has come to the rescue. The overloaded Merge method enables you to merge the menus very easily. All you need to do is to pass a reference to the menu you want to merge (source) and the menu you want to merge into (target) to this method and everything will be taken care of. When you want to unmerge the items, you just call the RevertMerge.

protected void OnMenuMerge()
{
    ToolStripManager.Merge(this.childMenuStrip, ApplicationController.View.MenuStrip);
    this.childMenuStrip.Visible = false;
}

protected void OnMenuUnmerge()
{
    ToolStripManager.RevertMerge(ApplicationController.View.MenuStrip, this.childMenuStrip);
    this.childMenuStrip.Visible = true;
}

Just make sure don't underestimate the power of this feature because of its simple interface. It is a rather powerful and robust piece of functionality that allows you to customise the way the menus are merged by allowing you to provide the merge action and merge index for each individual menu item. For example, you can choose the child menu item to replace the parent item or to remove the parent item when a child menu item matches the parent. I don't want to go into the details here as there are some good sources on the net with more details.

Please note that you don't have do call Merge and RevertMerge in MDI applications as automatic merging takes place when you set MainMenuStrip property on an MDI parent form. Also note that Merge and RevertMerge expect parameters of type ToolStrip, so you can merge/unmerge toolbars and status bars too (however, they do not participate in automatic merging in MDI applications so you always need to call Merge and RevertMerge explicitly).

I have created a class diagram that shows the players in the menu merge functionality. All items that can be added to MenuStrip and ToolStrip inherit from ToolStripItem so merge operation can be customised for all of those items by setting the merge action and index.


                             Click for a larger view [opens in a new window]

Have fun!

Posted by Mehran Nikoo | with no comments
Filed under: ,

Productivity Tools for Software Projects: ProjectWiki

Based on Paul Webb's suggestion, we created a Wiki for one of our projects a while back and we have been using it for the last couple of months. This has been a great success as it has become the number one source for knowledge sharing between members of the development team. Effective communication is one of the major challenges for medium to large development teams. We have more than 40 developers working on the same product and people are working on different functional areas without knowing much about the rest of the application (we have around 200 C#/VB.NET projects!). Some of us are working on common components (like Data Access / User Interface framework) whereas other people are focussed on the functional areas.

Prior to the Wiki, SharePoint was our main focal point where we had the high level architecture and detailed design documents (in MS Word format) for various parts of the application. Although SharePoint is a great product for knowledge management, not many people were using it and it was primalily used for publishing the artifacts of the project.

Thanks to the user-friendly nature of the Wiki. We are now visiting the Wiki multiple times a day to know more about the other components within the application. We also provide sample code on the Wiki pages where appropriate to show how to use those components. We are still keeping our published documents on SharePoint as the business users are comfortable with it, but Wiki is the number one source used internally within the development team.

I want to highlight that I am not suggesting not to use SharePoint. SharePoint is a great collaboration tool and it is the home to all published artifacts for every single project we undertake. The point I am trying to make is to adopt an easy-to-use and open collaboration model as opposed to a more formal document management/collaboration system. It is good to know that Windows SharePoint Services 3.0 comes with a Wiki engine so SharePoint can become the one-stop shop for all collaboration tools used within a project, which is perfect from an administration perspective.

In the pre-Wiki era, emails were flying around between developers telling each other how to do certain tasks. But what we do now is to create a related page on the Wiki first (if one doesn't exist already) and send a link to that page instead. This has been a great time saver for the project so we have decided to add the project Wiki to our application development framework.

The great thing about the Wiki is that you can go straight to the point and it is amazing to see how fast you can create a complete knowledge base for the whole application. Here is an example of a simple Wiki page entitled "How to Communicate with Other Applications":

Service Gateway 

In order to communicate with other applications, you need to use a "Service Gateway". The Service Gateway is a class that inhertis from MyCompany.MyApplication.Framework.ServiceGateway.ServiceGatewayBase. The TemplateMethodPattern is used to make sure all calls to other applications follow a pre-defined number of steps like adding the security credentials and logging.

Code Sample

* You need to add a reference to MyCompany.MyApplication.Framework.dll.

namespace MyCompany.MyApplication.Framework.ServiceGateway
{
    public classPaymentServiceGateway: ServiceGatewayBase
    {

        public
overridevoid AddSecurityCredentials()
        {
            // Do stuff
        }

        public override void WriteToEventLog()
        {
            // Do more stuff
        }

        public override void SendRequest()
        {
            // Do even more stuff
        }

    }
}

In a near future, I will write about the "Project Blog", another great productivity tool for the software projects.

Posted by Mehran Nikoo | with no comments
Filed under:

Windows Vista on MSDN Subscriber Downloads

Windows Vista is now available for download on MSDN Subscriber downloads. There is a single .iso image containing the following editions:

Windows Vista Business
Windows Vista Business N
Windows Vista Home Basic
Windows Vista Home Basic N
Windows Vista Home Premium
Windows Vista Starter
Windows Vista Ultimate

but the product keys for Business N, Home Basic N and Starter are not available yet (don't care - who wants Windows Vista without Media Player anyway?!!)

Looking forward to seeing it on the shelves in January!

Posted by Mehran Nikoo | with no comments
Filed under:

Windows Vista RTMs

Windows Vista is released to manufacturing. More here.

According to the MSDN Subscriptions web site, Windows Vista and Office 2007 will be available through MSDN Subscriber downloads within 7 days of RTM.

Posted by Mehran Nikoo | with no comments
Filed under: