Skip to content

2006

Continuous Integration with traffic lights

Continuous integration is the process that continuously build, analyze and test your sources. In many cases the process is triggered when changes are notified in the version control system, like VSS, CVS, etc. Martin Fowler has a good article about continuous integration.

In the .NET world, the most famous tool is CruiseControl.NET in combination with NAnt & NUnit. Getting an e-mail or popup from CruiseControl.NET is nice when a build is broken, but notifying the build status through traffic lights is much cooler.

Michael Swanson integrated CC.NET with the Ambient Orb. I think that the Ambient Orb is not an option for Europe, but you can integrate by using the X10 home automation technology. A good article about integrating X10 with .NET can be found on Coding4Fun and is called Controlling Lights with .NET.

Here are some (other) implementations:

ccnet

I am going for a walk this evening, and I think that tomorrow a traffic light will be missing :-D

trafficlight

DeckWorkspace extension (CAB) – Prevent drawing controls until all controls are initialized

CAB is an application block for building smart clients in .NET 2.0 and contains proven practices for building complex UI forms with so called SmartParts and Workspaces. The DeckWorkspace enables you to show and hide controls and SmartParts in an overlapped manner with no visible frame.

If you switch between controls, you will notice that the controls are painted while there are initializing. During the loading you will see that there is some overlapping and it doesn't give you a professional user experience.

formloading

Therefore I extended the DeckWorkspace, so that the the controls are only redrawed when they are initialized. This can be done through the WM_SETREDRAW message. Note that this technique can also be used for other workspaces.

public class DeckWorkspaceEx: DeckWorkspace 
{ 
    int freezePainting = 0; 
    const int WM_SETREDRAW = 0xB;

    [DllImport("User32")] 
    static extern bool SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);

    protected void FreezePaintingOn() 
    { 
        if (IsHandleCreated && this.Visible) 
        { 
            if (0 == freezePainting++) 
            { 
              SendMessage(Handle, WM_SETREDRAW, 0, 0); 
            } 
        } 
    }

    protected void FreezePaintingOff() 
    { 
        if (freezePainting != 0) 
        { 
            if (0 == --freezePainting) 
            { 
              SendMessage(Handle, WM_SETREDRAW, 1, 0); 
              Invalidate(true); 
            } 
        } 
    }

    protected override void OnActivate(Control smartPart) 
    { 
        FreezePaintingOn(); 

        try 
        { 
            base.OnActivate(smartPart); 
        } 
        finally 
        { 
            FreezePaintingOff(); 
        } 
    }

    protected override void OnClose(Control smartPart) 
    { 
        FreezePaintingOn(); 

        try 
        { 
            base.OnClose(smartPart); 
        } 
        finally 
        { 
            FreezePaintingOff(); 
        } 
    }

    protected override void OnHide(Control smartPart) 
    { 
        FreezePaintingOn(); 

        try 
        { 
            base.OnHide(smartPart); 
        } 
        finally 
        { 
            FreezePaintingOff(); 
        } 
    }

    protected override void OnShow(Control smartPart, SmartPartInfo smartPartInfo) 
    { 
        FreezePaintingOn(); 

        try 
        { 
            base.OnShow(smartPart, smartPartInfo); 
        } 
        finally 
        { 
            FreezePaintingOff(); 
        } 
    } 
}

The power of a markup language

One of the most popular markup languages is HTML. A markup language contains text and meta data about the text, such as layouts, styles, etc. Now Wiki sites are becoming more and more popular, and most of them use a customized markup language for HTML. One of the popular wiki sites is Wikipedia and is based on MediaWiki which uses WikiText as a markup language.

Here you find the syntax of WikiText. For example an asterix (*) is used for generating lists, the equal sign (=) can be used for sections, and there are many other constructions possible. For example templates are also possible, then contructions such as this can be made:

chesstemplate

There is also an extension called Wikitex for WikiText which is based on LaTeX. Where is the time that I wrote my thesis with pdfLaTeX using the MiKTeX distribution and WinEdt as my editor, very powerfull tool! However, with WikiTex you can even describe your music notes:

wikitextemplate

One of the things I really like and I will certainly incorporate with MediaWiki is UMLGraph. With this library you can also describe your uml and a picture is generated for you. Examples can be found here.

UMLTemplate

In my opinion, it becomes more important to have markup languages for the web (generates html, images, javascript, etc.). The big advantage is the flexibility of adding and updating the content very easily, without the need of extra tools and/or uploading images. Certainly when you have a wiki based site, where everybody can change the content.

On every site, whether through MediaWiki, Sharepoint, DotNetNuke or something else, knowledge has to be shared, and each site has its purpose. For example, a developer site has the need for syntax highlighting, uml diagrams, etc, whereas a mathematical site has the need for writing formulas, plots, etc.

Ithink there is a need for a new library (application block) in the .NET community similar to WikiText. A markup language for the web that can be customized, extended and that can be incorporated in each application. Wouldn't it be great that you could write your blog through WikiText.NET? :) I think this can be a good subject for the contest.

Applied Patterns – Part 2

Building an application and/or library usually starts with an OO design. Typically from that design you will define interfaces and implement base classes, which can be used as a starting point for building your application.

Defining the signature of a base class is very important. More specific, the visibility (public, protected & private) and purpose (virtual or not) of the methods are very important. Take for example an order-entry form based application that contains several screens for adding and updating data. Every screen will need to implement a kind of save method for persisting the changes. The very basic structure of your design can be:

public interface IDataView 
{ 
  void Save() 
}

public class DataViewBase: IDataView 
{ 
  public virtual void Save() 
  {     
  } 
} 

Here the intention is that for example every screen of your application need to inherit from DataViewBase and implement the Save method. The problem with this design, is that the interface is marked as virtual (see Virtuality) and is responsible for two jobs, namely that it is part of an interface and for specifying the implementation.

A better way is to apply the Template Method design pattern, also called the  'Hollywood principle', that is, 'Don't call us, we'll call you'. (This pattern is also used a lot throughout the .NET SDK library.)

public class DataViewBase: IDataView 
{ 
  public void Save() 
  { 
    DoSave(); 
  }

  protected virtual void DoSave() 
  { 
  } 
}

This way you have complete control of the interface and you can easily add some logging before and after the save for example, extra checks, etc. If for example you need to implement whether a form-screen is dirty or not, you can easily plug it in as follow:

public class DataViewBase: IDataView 
{ 
  public void Save() 
  { 
      // do some checks 
      // do some logging

      if (IsDirty()) 
        DoSave(); 
  }

  protected virtual void DoSave() 
  {     
  }

  protected virtual bool IsDirty() 
  { 
    return true; } 
  }

If for example you need to extend the application such that when the screen is dirty you get a dialog box asking if you want to save or not. You can simply change the Save method without affecting the derived classes

public class DataViewBase: IDataView 
{ 
  public void Save() 
  { 
    // do some checks 
    // do some logging

    if (IsDirty()) 
      if (MessageBox.Show("Do you want to save?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 
      DoSave(); 
  }

  protected virtual void DoSave() 
  {     
  }

  protected virtual bool IsDirty() 
  { 
    return true; 
  } 
} 

Due to the fact that the interface and the custom implementation is separated, we can easily extend and have control of the interface. In the other case we would have a lot of code duplication and in most cases we would violate the Liskov Substitution principle.

Syntax highlighting for MediaWiki

Here I describe how you can add syntax highlighting (C#, SQL, Javascript, etc.) in MediaWiki. In MediaWiki you can add syntax highlighting through GeSHiHighlight but I found it interesting for combining the world of PHP and .NET. For syntax highlighting in .NET I used the CodeHighlighter ASP.NET Control from Actipro Software.

The intersection between PHP and .NET for communication are web services. Therefore I created a .NET webservice that provides the method Parse with the parameters code and languagekey (= C#, SQL, XMl, etc.) which returns a HTML string.

using System; 
using System.Web; 
using System.Web.Services; 
using System.Text; 
using System.Web.Services.Protocols; 
using System.Configuration; 
using ActiproSoftware.CodeHighlighter; 
using ActiproSoftware.SyntaxEditor;

[WebService(Namespace = "http://tempuri.org/SyntaxHighlighting")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
public class SyntaxHighlighting : System.Web.Services.WebService { 

  [WebMethod] 
  public string Parse(string code, string languageKey) 
  { 
      if (string.IsNullOrEmpty(code)) 
        return string.Empty;

      SyntaxLanguage language = GetSyntaxLanguage(languageKey); 
      if (language == null) 
        throw new ApplicationException("LANGKEYNOTEXIST");

      CodeHighlighterEngine engine = new CodeHighlighterEngine(); 
      engine.OutliningEnabled = false; 
      return engine.GenerateHtmlInline(string.Empty, code, language); 
  }

  CodeHighlighterConfiguration GetCodeHighlighterConfig() 
  { 
      CodeHighlighterConfiguration config = (CodeHighlighterConfiguration)HttpContext.Current.Cache["CodeHighlighterConfig"];
      if (config == null) 
      { 
          config = (CodeHighlighterConfiguration)ConfigurationManager.GetSection("codeHighlighter"); 
          HttpContext.Current.Cache.Insert("CodeHighlighterConfig", config); 
      }

      return config; 
  }

  SyntaxLanguage GetSyntaxLanguage(string languageKey) 
  { 
      if (string.IsNullOrEmpty(languageKey)) 
        return null;

      CodeHighlighterConfiguration config = GetCodeHighlighterConfig(); 
      foreach (string key in config.LanguageConfigs.Keys) 
        if (key.ToLower() == languageKey.ToLower()) 
          return CodeHighlighter.GetLanguage(config, key);

      return null; 
  } 
} 

In MediaWiki you can extend WikiText so that for example your xml tag is recognized by the parser. This way you can extend the HTML output. In this example you would write in WikiText the following statements:

<code language="C#"> 
  public int x = 5; 
</code> 

In the extensions folder of MediaWiki you add a file called CodeHighlighting.php with the following content:

<?php

$wgExtensionFunctions[] = "wfCodeHighlightingExtension";

function wfCodeHighlightingExtension() 
{ 
  global $wgParser; 
  $wgParser->setHook('code', 'renderCode'); 
}

function renderCode($input="", $argv=array()) 
{ 
  $result = SyntaxHighlighting($input, $argv['language']); 
  return ' <pre>' . trim($result) . '</pre> '; 
}

function SyntaxHighlighting($code, $languageKey) 
{ 
  $location = 'http://localhost/SyntaxHighlightingWS/SyntaxHighlighting.asmx?wsdl'; 
  $result = $code;

  try 
  { 
    $client = new SoapClient($location); 
    $arr = array("code" => $code, "languageKey" => $languageKey); 
    $result = $client->Parse($arr)->ParseResult; 
  } 
  catch(SoapFault $exception) 
  { 
    if (strpos($exception->faultstring, "LANGKEYNOTEXIST") === false) 
    { 
      throw $exception; 
    } 
  } 

  return $result; 
} 
?> 
Through the setHook method you can extend WikiText. Here the method renderCode is called when a XML element named 'code' is inside your WikiText. Calling a web service in PHP 5 is easy with the SoapClient object. If the language we pass does not exist, we simply return the original string.

One more thing must be done, is to add an include in the LocalSettings.php in your MediaWiki folder.

include("extensions/CodeHighlighting.php");

Finally:

mediawikish

IE 7 Beta 2 released

Internet Explorer 7 Beta 2 has been released to the public, and can be downloaded here. I installed IE7 on a clean WinXP SP2 without any problems through VPC. My blog site and IStaySharp.NET rendered correctly with IE7.

IE7Beta2

The coolest feature I found, is the integrated rss reader...

IE7Beta2RSS

Office 12 Ascend Training Paris

I followed the Office 12 Ascend training in Paris that was teached by Patrick. The training was very successful and Patrick showed a lot of interesting stuff and demo's about Office and Sharepoint. So little time, and so much to play with, but thankfully there are the O12 labs which are very useful and detailed.

On Patrick's blog you find a group photo with the team of Paris. Here are some pictures I took during the ascend training.

How to install MediaWiki in 11 Steps

MediaWiki is a Wiki software licensed under GPL and written in PHP. Wiki allows users to easily add and edit content in a collaborative way. Wikipedia for example is one of the most popular Wiki's based on MediaWiki.

Below you find the necessary steps for installing MediaWiki.

  1. Download & install PHP 5.1.2 Installer. The installer creates a folder named c\:php
  2. Download PHP 5.1.2 zip package and extract all files in the folder c\:php
  3. Edit the php.ini file that resides in C:\Windows
    1. Change the extension directory: extension_dir = "c:/php/ext/"
    2. uncomment mysql extension: extension = php_mysql.dll
  4. Download & install MySQL 4.1.16 (Windows (X86)).
  5. Create a virtual directory under IIS called phpmyadmin (e.g. c:/inetpub/wwwroot/phpmyadmin)
    1. Add the entry index.php in the documents tab. iisdocuments
  6. Download the latest phpMyAdmin and extract all files under the virtual directory of phpmyadmin.
  7. Edit the file config.default.php that resides in the phpmyadmin folder.
    1. Change the root password of MySQL.
  8. Browse to http://localhost/phpmyadmin phpmyadmin
  9. Create a virtual directory under IIS called mediawiki (e.g. c:/inetpub/wwwroot/mediawiki)
    1. Add the entry index.php in the documents tab.
  10. Download the latest MediaWiki and extract all files under the virtual directory of mediawiki
  11. Browse to http://localhost/mediawiki & Configure.
    1. Add the line: $wgEnableUploads = true in the LocalSettings.php to enable uploads mediawiki

Warning

After installation you will notice that some pages give a warning, namely: Undefined index: REQUEST_URI in C:InetpubwwwrootmediawikiincludesWebRequest This is a known issue and can be fixed.

Applied Patterns – Part 1

Nowadays, is every kind of enterprise application more complex because there is the need to have much richer UI experience, integration with other systems, security, etc. Therefore it's important to have a good architecture and design of your application, so that you can better maintain and extend your application.

In every enterprise application you have a dependency to data resources. These resources can be to a database, web service, registry, file system, etc. It's a good practice to encapsulate all these dependent resources into services, such that the consumer (caller of the service) doesn't need to know the implementation details and the origin of the data.

That pattern is used a lot and is called a Service Gateway or Service Agent. There is a discussion on the difference between a Service Gateway that can be seen as consumer of a service and a Service Agent as a provider, but in the community both terms are used and mixed. The dependency between the consumer and the service is a contract which is typically a set of interfaces and business entities. In most cases, the service interface acts as a facade pattern, it encapsulates all subsystems underneath.

Des_ServiceInterface_Fig01

A typical example of a service agent is:

public interface ICustomerAgent 
{ 
  Customer GetCustomer(int customerId); 
  Order[] GetOrders(int customerId); 
} 

Note that the interface doesn't expose any details about the underlying system (e.g. database, xml, etc.) and communication protocol (e.g. web service, remoting, etc.).

Programming the UI of an application is typically the most difficult part and a challenge to achieve encapsulation and loose coupling. Thankfully there is for .NET 2.0 the Composite UI and the Smart Client Baseline Architecture Toolkit which guides you to an architecture for developing smart clients. Offcourse there is still the bible that every developer should read/know, it's the GoF book that describes a set of design patterns.

One of the drawbacks of a designer like in Visual Studio.NET, is that it is so easy to drag and drop (in dutch I call it 'drag en drol') components, change some attributes and going through wizards for making your application. For prototyping and demo's this is good enough, but for real enterprise applications it's not. If you want you can write an application that has only one class (= form), named Form1.cs that includes all UI logic, business logic, data access, security, etc but that's not what we want.

Building the UI is basically populating UI controls with data that resides in business entities. This means that for example an array of customers that must be shown in a list, means that every customer entity must be translated to a ListViewItem (if we don't use databinding). In most of the cases this logic resides in the form/usercontrol itself, but in fact it can be seen as a separated responsability for mapping a customer entity to a ListViewItem and vice versa (like in SC-BAT). This means that we can have something like:

public static class CustomerMapper 
{ 
  public static ListViewItem ToListViewItem(Customer customer) { ... } 
  public static Customer FromListViewItem(ListViewItem listViewItem) { ... } 
} 

And in your form/usercontrol you write:

foreach (Customer customer in customers) 
  customerListView.Items.Add(CustomerMapper.ToListViewItem(customer)); 

In every project there are some OO concepts and patterns I always try to achieve maintainability and extensibility. Making good OO designs is in my opinion a matter of experience, creativity and making abstractions. My conclusion...

Abstract

The art of OO programming is to define the set of responsabilities (= objects), to encapsulate and to interact them in a loosely coupled way.