Latest Tweet:
  • Loading...

On the Silverlight.net forums there are several questions about how to configure Silverlight applications. A common question is how to change the URL of a WCF service you are consuming. Another common question is how pass in some user defined configuration settings. There are several interesting solutions, and a couple of days ago Bill Reiss posted an article about “Calling WCF on the server of origin from Silverlight”. Bills solution involves using the HTML Bridge to grab the current URI, and building up the URL of the web service, and then creating the service client using one of the constructors allowing you to manually specify binding and endpoint. This is all cool and really helpful in many cases, but the ServiceReferences.ClientConfig file is there for a reason. I think a lot of developers are a bit confused about how to use this file. And I don’t blame them. In Silverlight 2 Beta 1 this file was generated by Visual Studio, but was not read by the WCF runtime. In Beta 2 this was fixed, and the WCF runtime will now read and use the configuration file.

A lot of developers are afraid they have to rebuild their application to change web service configurations; something Bill also write in his blog post:

This is fine if you're hitting a service like Digg or one of the other public web service APIs out there, but not if you want to be able to test on your own machine and also deploy the same XAP to your server without rebuilding.

You could go ahead and change this to the URI on your server and rebuild, but then it won't work locally for testing unless you have a crossdomain file on your server, and you would be hitting your server's web service, not your local one while testing.

When building a Silverlight 2 application Visual Studio 2008 will spit out a XAP file in the Client Bin directory. The XAP file is just a standard ZIP archive containing some assemblies, the configuration file, a manifest file, and any resources you might have added to your project and market as content. It’s completely safe to rename it to ZIP, unpack it, make changes to the ServiceReference.ClientConfig file and package it all back together to a XAP file. Turns out repacking your XAP file is actually a good idea. Back in May Valeri Hristov discovered that he could chop 1MB of a 3MB large Telerik example application by repackaging it using the 7Zip application. Later David Anson followed up with some more examples showing a 22% average saving by repacking the XAP file… Why Microsoft is using such an inefficient ZIP implementation I don’t know –hopefully this will be fixed before release. Until then creating a post-build event that repackages your XAP will probably be the easiest 22% savings you will get all day.

Content of a XAP file

Anyway, let’s get back to configuration. Now that we can reconfigure our Silverlight application without rebuilding it we might be able to use the configuration file for more useful stuff. Silverlight does not come with a full configuration API like the full .NET framework. You do have the System.Configuration namespace, but it only contains some internal, abstract classes used by the Silverlight WCF stack. If you search for “configuration” in Reflector targeting Silverlight 2.0 you get some hits in the System.ServiceModel.Configuration namespace as well. It got configuration section handlers used by WCF to read information about your web service bindings and end points. All classes are internal and not really helpful for handling general application configuration.

Since the ServiceReference.ClientConfig is a plain XML file there is nothing stopping us from adding our own elements to the file. I decided to use the application setting convention we’re used to from .NET, and added an appSettings element with a bunch of key-value pairs elements. The application continued to run just fine with these additional elements. I also tried adding and removing service references from Visual Studio to see if it would screw up my changes. Thankfully Visual Studio only touched the serviceModel element, and didn’t care about our appSettings element. The ServiceReference.ClientConfig file now looks something like this:

configsample1

This is quite handy, as we can keep all application settings in one file using a format developers know. Next step is writing some code to read the configuration file. I decided to mimic how things work in the full .NET framework by creating a ConfigurationManager class with an AppSettings property. To parse the configuration file I used LINQ to XML which made it really easy to extract the key-value pairs.

configsample2

In the full framework the AppSettings property is of type NameValueCollection. This collection does not exist in Silverlight, so instead of re-implemented it I created a simple class backed by dictionary, exposed as an index property.

configsample3 

You read the application settings the same way you are used to from any .NET application:

configsample4

Hopefully this post gives you a better understanding how Silverlight 2 applications are packaged, and how to configure your application without rebuilding it. If I was consuming WCF services in my project I would add configuration management to my automated build process. It would be fairly simple to write a build script that repackages the XAP with a more efficient ZIP implementation, as well as building different versions for test, staging and deployment.

This is a post I've been looking forward to write for quite some time, but I've just been to busy with work, CodeCampOz and REMIX to get around to do it… At the MVP Summit in Seattle some weeks back I had dinner with a group of friends, including fellow RD and co-worker Sondre Bjellås, and long time IRC-friend Wilco Bauwer (now working at Microsoft). Like when ever a group of programmers get together the talk soon was about Silverlight, C# and programming an general. We started discussing Silverlight and what features we would love to se in future versions. One of the things Sondre felt was missing is support for microphone and webcam. I don't know why Sondre think this is a big deal (but he DO read Love and Sex with robots… btw, Sondre, you should write a book review!). Wilco have worked on the HTML-bridge in Silverlight, so we started talking if it might be possible to "cheat" basic webcam support by bridging Silverlight and Flash. Without knowing the details we all agreed that it was probably possible to do.

When I got back from Seattle I started doing some initial research, like learning how to program against the webcam in Flash, what kind of HTML-bridging  capabilities you got and so on. A video tutorial titled "Webcams, PNG and AIR", combined with a blog post titled "Use JavaScript to Take a Screenshot of a Flash movie", gave me all the pieces to build webcam support for Silverlight (using Flash). So I asked my self: "What would MacGyver do", and decided to glue everything together into a proof-of-concept of webcam support in Silverlight 2.

The video tutorial covers the basics of how to create a camera object, attach it to a video and grab a video frame as a BitmapData object. It also covers how to use the as3core library, a set of open source extensions to ActionScript3, which includes a PNG-encoder class. The PNGEncoder encodes a BitmapData object into a ByteArray. Once I had the ByteArray I needed a way to pass it back to the browser. Since the set of types you can marshal between ActionScript and the browser (at least to my knowledge) is limited, I figured a Base64 encoded string would be the way to go. The blog post about taking screenshots used this technique to pass an image from Flash to JavaScript. It also covered how to expose ActionScript functions to JavaScript using the ExternalInterface APIs.

Once I had the Base64 encoded PNG image in JavaScript I could simply return it back to Silverlight, which then would use the Convert.FromBase64String method to create a byte array. With the image stored in a byte array I could simply load it into a MemoryStream, and then set the MemoryStream as the source of a BitmapImage object.  I'll let MacGyver show you how it all comes together:

MacGyverUML

It literally didn't take more than 20 lines of ActionScript, 5 lines of JavaScript and 5 lines of C# to get a single frame from my webcam onto a Silverlight image control.  This first piece of code is the ActionScript needed to start the webcam, capture a frame, set the mode and expose two functions to the browser:

WebcamActionscript

The next part is the JavaScript needed to grab the object/elem tag containing the Flash player, and calling the ActionScript functions to grab a snapshot from the webcam. The Base64 string is just returned from the function, as this function is being called from C#:

WebcamJavascript

The final part is the C# code using the HTML bridge to invoke the JavaScript function, grab the Base64 string, decode it, and then load the PNG image:

WebcamCSharp

Using the basic webcam integration I created two sample applications. The first one is a "performance test" to see how many frames per second I'm able to transmit to Silverlight. Since I'm not able to pas the raw stream from the camera, and have to PNG encode each frame, it's all CPU bound. The application uses a timer, which will grab a frame and measure the time it takes. Once it got the frame it will adjust the interval of the timer to the amount of time spent on the previous frame + 50 milliseconds (to give the UI thread some room to handle input events etc). I was able to get roughly 12fps 180x140, but on higher resolutions it starts to get sluggish. Also note that when using all the CPU power to capture frames you don't have CPU left to do Silverlight animations etc, so doing "live" video is really something you don't want to do. Click the image to check out the sample:

WebcamLiveVideo

The second sample is a Silverlight "Photo Booth" application, with out any of the cool features of the real Apple Photo Booth app. The interesting part about this sample is how I overlay the Flash container on top of Silverlight. This way my Silverlight application don't need to use CPU power to pre-view the video, and I only grab photos when the user clicks the button. Each image is also added to the thumbnail control, which I re-used from my YouCard demo. Click the image to check out the sample:

WebcamPhotobooth

I've made the code available for everyone to play with, including the Flash webcam wrapper. In order to build the Flash app you need Adobe Flash CS3. If you don't have Adobe Flash CS3 you can still build the app in Visual Studio and use the prebuilt WebcamWrapper.swf file. The code is not optimized in any way, and probably contains some bugs. But, this initial post is meant as a proof-of-concept, and I'll probably revisit this topic later.

And to summarize: THIS is how MacGyver would have built webcam support for Silverlight 2!

One of the activities me and Hege have really gotten into the last year is scuba diving. I'm currently "PADI Advanced Open Water" certified and have 39 logged dives. Hege got me a an awesome Suunto D6 dive computer for Christmas (she has the D9 model). If you buy the (way over priced) computer cable you can sync your Suunto watch with your computer using the "Suunto Dive Manager" application. Once synced to your computer the app gives you all kinds of cool stats, like dive profile, air consumption (if you have the D9 model), temperature, maximum depth, total dive time and lots of other interesting stuff.

suuntodivemanager

Being a programmer I immediately started poking around in Suunto DM trying to figure ut how to access my dive log from code. Turns out Suunto store all my dives in a Microsoft Access database. When I first discovered this I was pretty happy thinking this was going to be easy as stealing candy from a kid. This was until I discovered Suunto had applied a "one table to rule them all"-database design. The main "Items"-table has 82 (!) numbered columns (custom_1, custom_2 etc.). The only reasonable (?) reason I can think off for this design has to be that Suunto at some point migrated from a proprietary database-like binary format to Access, and that they kept some of the same "data structures" for easy migration. At least that's what I hope... for their sake.

suuntodivemanagerdb

My first idea was to see how well the ADO.NET Entity Framework would play with this database deisign. After all EF is supposed to give you that extra flexibility when mapping objects to data. I did some research only to realise that Access won't be supported by EF v1.0. Danny Simmons, developer on the ADO.NET EF team, gives some background information in a forum post from back in July 2007:

"OLE-DB ado.net provider has not been extended to support the entity framework, and we do not currently have plans to do so in our first release. Further, this would be a fairly difficult effort because OLE-DB doesn't provide enough information in general to translate CQTs (canonical query trees--the entity framework intermediate query representation) to a particular back-end query syntax."

I sent Danny an e-mail to check if this was still the case. Turns out it is. In theory you could use a third party ODBC provider, but according to Danny you probably going to need a custom Access provider in order to use ADO.NET Entity Framework on top of Access databases.

So, since ADO.NET EF was out of the picture I was pretty much left with the default LINQ to SQL support in .NET 3.5 (no way I was going to write the T-SQL by hand). Officially only SQL Server 2000 and 2005 is supported by LINQ to SQL, but it turns out the DataContext object accepts a IDbConnection in its constructor. By passing in a OleDbConnection you can have LINQ talk to an Access database. You will not get design time support in Visual Studio 2008, and have to write all the mapping classes your self. But at least you can execute some basic LINQ queries. The LINQ runtime will not now that it's talking to a Access database, and it will generate SQL code as if it was running against a SQL Server. But for basic SELECT queries I haven't gotten into trouble yet.

This is how happy you get when you discover you can use LINQ against your dive log!

I'll write a follow up post on the actual implementation of my LINQ layer on top of the Suunto Dive Manager database. For now a class diagram might give you a an idea of how the end mapping looks like.

SuuntoLINQ

Do you care about Microsoft Access support in ADO.NET Entity Framework? Or are you perhaps into diving yourself? Let me know in the comments section!

Yesterday Somasegar made some big announcements about the F# programming language. F# is originally a Microsoft Research project coming out of the Cambridge Research lab. Microsoft have decided to take the project forward and "productize" F#. This means that F# is becoming a first class citizen on .NET and in Visual Studio. Soma didn't mention which version F# is going to make it into, but I don't expect them to have anything ready for Visual Studio 2008. Perhaps an intermediate release and a full integration in version 2008+1? One could only speculate...

F# is a functional programming language with roots in ML and draws inspiration from languages like Python, Matlab, C#, Haskell, Scheme and more. I've previously blogged about the importance of learning new programming languages and ideas in my "learn the language, live the lifestyle" post, and one of the most rewarding courses of my bachelors degree from NTNU was a functional programming course in Scheme. The fact that Microsoft is bringing both dynamic (Ruby and Python) and functional (F#) languages  to the .NET is great news for developers. We can use the right language for our problem domain, while still leveraging the .NET framework or any other .NET component we might have written. A typical scenario for F# might be to implement a domain problem described in mathematical notation in F# and compile it into a .NET assembly, and then use other .NET languages to expose this functionality through some UI or service.

You learn more about F# over at the Don Syme's blog or the project site up on MSDN.

One of the new features introduced in .NET 2.0 is the Event-based Asynchronous Pattern.  A class that supports this will have one or more methods named MethodNameAsync. These methods often mirror synchronous versions, which perform the same operation on the current thread. The class may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel method.

The Event-Based Asynchronous Pattern is used several places in the .NET 2.0 Framework , and one example many might find familiar are the auto generated Web Service Proxy classes. For every web service method you get a async version, and an event fired when the async method call finishes. The data is returned as the event argument.  Code like this is really nice to work with, and makes it really simple to make more responsive clients where all web service calls happens on a separate thread. The disadvantage with asynchronous code is that it's harder to write unit tests for.

This is a problem I've faced many times, and I've seen several different solutions. Many of them involves sleeping the thread executing the test, while waiting for the data to come back so that you can do any assertions on the returned data. This has several disadvantages. You don't now exactly how long the asynchronous call is going to take, so you need to sleep "long enough". Having thread sleeps in your tests are going to (big surprise) make your test suite slow. Now matter how fast your service returns it data, you still have to wait for all thread sleeps before the test ends. This is really inefficient, and can really become a problem when you have a large test suite integrated into a build environment. Another problem is that this is an unreliable way to do your testing, as they might pass some times, while fail others (if the thread sleep isn't long enough).

The best solution I've found to unit testing of asynchronous code is the ManualResetEvent class found in the System.Threading namespace. I'm no threading expert, and I'm not going to try to explain how the .NET threading model works, but I've included a little snippet from the MSDN documentation explaining what you can use the ManualResetEvent class for:

"ManualResetEvent allows threads to communicate with each other by signaling. Typically, this communication concerns a task which one thread must complete before other threads can proceed".

This is exactly what we want. When the thread executing the unit test starts an asynchronous call we want to block the thread, and wait for a signal from the callback before we continue. This way we spend the minimal time needed waiting for a result from the async method call, and don't have to depend on thread sleeping for synchronizing the test with the result from the async method. I've included a simple NUnit test for a web service offering basic arithmetic operations. It calls the async versions of the add and subtract methods, performs assertions both on the returned data, and check if the async call actually completed. The details on how to use the ManualResetEvent is included in the code sample beneath (check the comments).

[Test]
public void TestCalculations()
{
    // A simple web service offering basic aritmetich operations
    Service service = new Service();

    // Test data...
    int a = 10;
    int b = 10;

    // Variables to track is a asyn call completed.
    bool addCompleted = false;
    bool substractCompleted = false;

    // Used to signal the waiting test thread that a async operation have completed.
    ManualResetEvent manualEvent = new ManualResetEvent(false);

    // Async callback events are anonomous and are in the same scope as the test code,
    // and therefore have access to the manualEvent variable.
    service.AddCompleted += delegate(object sender, AddCompletedEventArgs args)
    {
        // Some basic assertions on the code.
        Assert.AreEqual(a + b, args.Result);
        addCompleted = true;

        // Signal the waiting NUnit thread that we're ready to move on.
        manualEvent.Set();
    };
    
    service.SubstractCompleted += delegate(object sender, SubstractCompletedEventArgs args)
    {
        Assert.AreEqual(a - b, args.Result);
        substractCompleted = true;
        manualEvent.Set();
    };

    // Call the add method asyncronous.
    service.AddAsync(a, b);

    // Block the current thread untill the callback event signals
    // or the call times out (1500 ms).
    manualEvent.WaitOne(1500, false);

    // Check if we completed the async call, or fail the test if we timed out.
    Assert.IsTrue(addCompleted);

    // Set the event to non-signaled before making next async call.
    manualEvent.Reset();

    service.SubstractAsync(a, b);
    manualEvent.WaitOne(1500, false);
    Assert.IsTrue(substractCompleted);
}

My good friend Håvard sent me an e-mai l today with a link to a Google Tech Talk with Ron Avitzur, an engineer who literally snuck into Apple to work (for free) on a graphical calculator software. The story is truly amazing and inspiring. It's just great to hear about people who share a passion for code and software. Just watch the video (even my non technical friends should watch this). You won't regrets it, trust me!

It's midnight. I've been working sixteen hours a day, seven days a week. I'm ... all not being paid. In fact, my project was canceled six months ago, so I'm evading security, sneaking into Apple Computer's main offices in the heart of Silicon Valley, doing clandestine volunteer work for an eight-billion-dollar corporation. -Ron Avitzur

For more great videos, check out this top 20 list from the Google Research Group.

One of the demos I gave during my Visual Studio 2008 presentation at MSDN Live this Monday was on Visual Studio Tools for Office and how to build an Outlook 2007 Add In. VSTO is now as integrated part of Visual Studio 2008 and not a separate product anymore. Previous versions of VSTO have been a bit limited, but the latest version lets you extend Outlook, Word, Excel, PowerPoint, Visio, InfoPath and Project using managed code. This opens up to some really nice integration scenarios where you can integrate line-of-business applications directly into Office.

In my demo I integrate Virtual Earth maps into the contact form in Outlook 2007. When you open up a contact you get a new button to view a map showing the contacts location on the map. The way I integrate Virtual Earth is by using the Windows Forms Web Browser control. The cool thing about the Web Browser control is that it's really easy to invoke JavaScript functions on the page being displayed directly from C#.  The JavaScript code to find a location on the map and display a pushpin is based on the Virtual Earth Interactive SDK samples.

To create a new Outlook 2007 Add-in start by going File - New Project, and select Visual C# - Office - 2007 - Outlook Add-in. This will create a new Outlook Add-in project. The project template will create a simple ThisAddIn.cs file that contains methods for Add-in startup and exit. For now just ignore this file. The next thing you need to do is add a forms region to your project. Right click the project and select Add - New Item. This will bring up the dialog box with all available items. Select the Outlook Form Region item to design a new form. Adding this item will launch a short "Outlook Form Region" wizard. You get options to design a new form, or import an existing design from an .ofs file. Select new form region. The next question is what type of form region you want to create. You can choose separate, adjoining, replacement and replace-all. Choosing separate will add a new button to the toolbar, which will open your form region as a separate page when you click the button. Select this option. Next step is to give your form a name, before the final step is to select which type of message class you want to display the form region on. You can select multiple options (like mail, RSS, task). For this form we'll simply select contact. This will make the add-in available only on the contact form inside Outlook.

newofficeproject  

newoutlookform

After completing the wizard you get a design surface that should look familiar to any Windows Forms developer. It's the good old Windows User Control designer where you can drag and drop any Windows Forms control onto the surface. Start by adding a web browser control and dock it to the parent. Set the ScrollBarsEnabled property to false. Add an event handler for the DocumentCompleted event. This event is executed when the browser is done loading the web page. Set the URL property of the web browser control to http://jonas.follesoe.no/content/binary/virtualearth.htm, or your own version of the Virtual Earth HTML file. The content of the file is straight forward, and can be viewed below. For security reasons IE (the Web Borwser Control is a simple wrapper around IE) displays a warning when ever a local HTML file is loaded. Even if you accept blocked content I can't get the map to display correctly. That's why I have the map HTML file up on a web server (and not as a local file on disk). The HTML and JavaScript looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Virtual Earth</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        body        
        {
            margin: 0px;
            padding: 0px;
        }
    </style>
    <script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=5" type="text/javascript"></script>
    <script type="text/javascript">      
        var map = null;  
        var pinid = 0; 
        var title = "";
        var description = "";               
        
        function GetMap()      
        {         
           map = new VEMap('myMap');
           map.SetDashboardSize(VEDashboardSize.Small);
           map.LoadMap();      
        }      
                 
        function FindLocation(location, contactName, contactDescription)
        {
           try
           {
               title = contactName;
               description = contactDescription;
               
               if(map == null)
                   GetMap();
              
               map.Find(null, location, null, null, 1, 1, true, true, true, true, LocationFound);
           }
           catch(e)
           {
               alert(e.message);
           }
        }   
        
        function LocationFound(a, b, placeArray, d, e)
        {
           var shape = new VEShape(VEShapeType.Pushpin, placeArray[0].LatLong);          
           shape.SetTitle(title);
           shape.SetDescription(description);
           
           pinid++;          
           map.AddShape(shape);          
        }
    </script>

</head>
<body>
    <div id='myMap' style="position: relative; width: 100%; height: 100%;"></div>
</body>
</html>

In the DocumentCompleted event you need to execute the FindLocation JavaScript function on the loaded HTML page. You do this by calling the webBrowser.Document.InvokeScript method. As parameters to the FindLocation function you need to pass in the contacts name, address and description (used by the pushpin). The code to execute the script and access the currently selected contact is displayed below:

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Outlook.ContactItem currentContact = (Outlook.ContactItem)this.OutlookItem;
            string address = currentContact.BusinessAddress.Replace("\r\n", ",");
            ExecuteScript("FindLocation", address, currentContact.FullName, currentContact.BusinessAddress);
        }

        private void ExecuteScript(string scriptName, params object[] parameters)
        {
           webBrowser.Document.InvokeScript(scriptName, parameters);
        }

The FindLocation function will use VirtualEarth to look up the address, move the map and add a pushpin with the name and address of the contact. Screenshot below:

contactscreenshot

This example is just a quick demo of what some of the new features in Visual Studio Tools For Office 3.0 shipping as part of Visual Studio 2008 has to offer. For another interesting demo check out the TechEd US key note available over at Virtual TechEd. The Office/Outlook demo starts about 58:30 into the video.

For more information about Office Development check out the Visual Studio Tools for Office Developer Portal.

When ever you click on a hyper link like http://jonas.follesoe.no, mailto:me@email.com the Windows component "Url.dll" will do a look up in the register and execute the correct application. For links to regular web pages it will launch your default browser. For mailto links it'll launch your preferred e-mail client. You can use the link concept in a wide range of applications, ranging from linking inside web pages to adding links to e-mail messages, spread sheets, word documents, sidebar gadgets, IM chats and more. The way we can link information together is one of the core fundamentals of the web. Applications that handle a specific type of links is called a protocol handler. In this post I'll discuss how you can create your own protocol handler for a custom application and how this might be a powerful way to achieve light weight  and easy to implement integrations between your applications.

helpdeskclient

To illustrate the concept of protocol handlers I've created a simple Windows Forms Application called HelpDeskClient. The application can be looked at as your typical line of business application you want to "tap into" from other applications. The application contains code to write/delete the registry keys needed to register the protocol handler. To illustrate some simple "integration" the application hosts a HttpListener (a small web server) to display some simple HTML and RSS. The application is implemented as a single instance application, meaning that there will only be one instance of HelpDeskClient.exe running at any time.

To register a new protocol handler all you need to do is add a few lines to the registry:

[HKEY_CLASSES_ROOT]
  [helpdesk]
    (Default) = "URL:HelpDesk Protocol"
    URL Protocol = ""
    [DefaultIcon]
      (Default) = "HelpDeskClient.exe"
    [shell]
      [open]
        [command]
          (Default) = "c:\whatever\HelpDeskClient.exe "%1""

The most important part is the URL Protocol value under the "helpdeks" key. This will register the helpdesk:// protocol with "Url.dll". When ever Windows encounters a helpdesk:// link "Url.dll" will execute your HelpDeskClient.exe file passing the URL as a command argument. So when "Url.dll" executes a link to "helpdesk://open/?id=7" it'll execute "c:\whatever\HelpDeskClient.exe helpdesk://open/?id=7". In your main method you need to parse the arguments and take appropriate action. Fore another example on how to create a Visual Source Safe protocol handler check out this CodeProject article.

To make things easy the application can write/delete the registry keys needed to register the protocol handler. The code to do that looks as follow:

RegistryKey helpDesk = Registry.ClassesRoot.CreateSubKey("HelpDesk");
helpDesk.SetValue("", "URL:HelpDesk Protocol");
helpDesk.SetValue("URL Protocol", "");

RegistryKey defaultIcon = helpDesk.CreateSubKey("DefaultIcon");
defaultIcon.SetValue("", Path.GetFileName(Application.ExecutablePath));

RegistryKey shell = helpDesk.CreateSubKey("shell");
RegistryKey open = shell.CreateSubKey("open");
RegistryKey command = open.CreateSubKey("command");
command.SetValue("", Application.ExecutablePath + " %1");

When you have your protocol handler registered you need to parse the command line arguments. In this example I've created a single instance application, meaning that any attempt to start "HelpDeskClient.exe" while the application is running will not create a new instance. Instead it'll show the all ready running application. Single instance applications are quite common, Outlook 2007 is one example of it. There are several ways to implement single instance applications. If the name of the executable is unique you can simply check the list of running processes. A better way is to use a mutex. If the mutex is used it means the application is all ready running. The easiest way however, if you're writing.NET 2.0 code, is to derive the WindowsFormsApplicationBase class which is part of the "special" VB.NET libraries. The VB guys has always had a few extra classes to help them out, like the "My.*" namespaces introduced in .NET 2.0. The cool thing about .NET is that you can take advantage of these classes your self. All you have to do is to add a reference to "Microsoft.VisualBasic.dll" in your C# application. I guess this will raise a few eyebrows in the C# camp, but trust me, it's safe! Below is my SingleInstanceApplication.cs and Program.cs class. If you want to learn more about how to create single instance applications check out this blog post.

    /// <summary>
    /// The Main class of the application.
    /// </summary>
    static class Program
    {
        // Private members
        private static MainForm mainForm;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //Creates a new SingleInstanceApplication (from the VB Namespace)
            SingleInstanceApplication app = new SingleInstanceApplication();
            app.StartupNextInstance += new StartupNextInstanceEventHandler(app_StartupNextInstance);

            //Creates the MainForm and loads the application.
            mainForm = new MainForm();
            app.Run(mainForm);
        }

        /// <summary>
        /// Method executed if the application is allready running.
        /// </summary>
        static void app_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
        {
            //Tels the loaded main form to parse the command line arguments.
            List<string> list = new List<string>(e.CommandLine);
            mainForm.ParseCommandLine(list.ToArray());
        }
    }

    /// <summary>
    /// A SingleInstanceApplication extending the application base. Part of the VB namespaces.
    /// </summary>
    public class SingleInstanceApplication : WindowsFormsApplicationBase
    {
        public SingleInstanceApplication(AuthenticationMode mode) : base(mode)
        {
            InitializeAppProperties();
        }

        public SingleInstanceApplication()
        {
            InitializeAppProperties();
        }

        protected virtual void InitializeAppProperties()
        {
            this.IsSingleInstance = true;
            this.EnableVisualStyles = true;
        }

        public virtual void Run(MainForm mainForm)
        {
            List<string> list = new List<string>(this.CommandLineArgs);
            mainForm.ParseCommandLine(list.ToArray());
            this.MainForm = mainForm;
            this.Run(list.ToArray());            
        }
    }

As the title of this post suggests the idea of using protocol handlers is that they can be used as a ultra thin layer of integration between your applications. I'll try to elaborate more on this…. Most Windows applications supports some kind of hyper linking. You can type in a link in a mail message, a Word document, an Excel spread sheet and off course on any HTML page. This opens up for some simple "work flows" that just works. I can write an e-mail, paste a link and tell some one to check out this cool YouTube video… Or I can look up and address on Google Earth and copy the location as an hyper link and send it to some one on MSN Messenger. By registering your own protocol handler you can open up to this kind of "integration" your self. By creating some kind of URL scheme to navigate to important parts of your Windows application, open up customers or help desk requests (as in this example) you can open up for some really fluid and easy to implement workflows for your end users. For instance you could send an e-mail to your manager telling them to "help you out with this item", and hyper link directly into your ERP system. Or even more interesting you could start exposing feeds of important items that your users could integrate in any way they want. You could subscribe to "my work items" in any RSS application, and clicking the link would bring up the correct application, pre-loaded with that specific item. You could write a few neat Sidebar Gadgets providing glanceable data from your business applications  saving your users from having to click through several screens just to check if they have any urgent items to take action on.

helpdeskword

To illustrate this (and provide some XML data for further examples) the HelpDeskClient application will start a HttpListener when it loads. You register the HttpListener on any url and port (under local host off course) and can start serving incoming HTTP requests. When a request is received you get access to the HttpRequest object you're used to from ASP.NET and can start creating the HttpResponse. In this example I serve two URLs: http://localhost:8080/taskhtml/ and http://localhost:8080/taskfeed/. The first one servers a simple HTML page with a list of open and closed items. Each item is a helpdesk://open/?id=xx link. When you click the link the HelpDeskClient application will execute and show the selected item. The feed page is a RSS 2.0 feed with all open help desk requests. This feed can be added to any RSS reader, or integrated into a Vista Sidebar Gadget or used where ever you want.

helpdeskweb  

The code to create a HttpListener is shown below:

        /// <summary>
        /// Starts the Http Listener on a background thread.
        /// </summary>
        private void StartHttpListener()
        {
            if (HttpListener.IsSupported)
            {
                try
                {
                    //Creates a HttpListener with two urls for RSS and HTML.
                    HttpListener listener = new HttpListener();
                    listener.Prefixes.Add("http://localhost:8080/taskfeed/");
                    listener.Prefixes.Add("http://localhost:8080/taskhtml/");
                    listener.Start();
                    while (true)
                    {
                        HttpListenerContext context = listener.GetContext();
                        HttpListenerRequest request = context.Request;
                        HttpListenerResponse response = context.Response;

                        //Checks if the user is requesting the HTML page or the RSS feed.
                        if (context.Request.RawUrl.EndsWith("feed"))
                        {
                            //Renders the RSS feed.
                            context.Response.ContentType = "application/xml";

                            XmlTextWriter xmlWriter = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);
                            xmlWriter.WriteStartDocument();
                            xmlWriter.WriteStartElement("rss");
                            xmlWriter.WriteAttributeString("version", "2.0");
                            xmlWriter.WriteStartElement("channel");
                            xmlWriter.WriteElementString("title", "HelpDesk Application - Open Requests");
                            xmlWriter.WriteElementString("description", "An RSS feed of open HelpDesk Requests. Can be used by gadgets, feed readers etc.");
                            xmlWriter.WriteElementString("link", "http://localhost:8080/taskhtml/");
                            foreach (HelpDeskRequest hr in logic.RequestDatabase)
                            {
                                if (!hr.Closed)
                                {
                                    xmlWriter.WriteStartElement("item");
                                    xmlWriter.WriteElementString("guid", hr.ID.ToString());
                                    xmlWriter.WriteElementString("title", hr.Subject);
                                    xmlWriter.WriteElementString("link", "helpdesk://open?id=" + hr.ID.ToString());
                                    xmlWriter.WriteElementString("pubDate", hr.Date.ToString("r"));
                                    xmlWriter.WriteEndElement();
                                }
                            }
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteEndDocument();
                            xmlWriter.Flush();
                            xmlWriter.Close();
                        }
                        else
                        {
                            //Renders the HTML page.
                            context.Response.ContentType = "text/html";
                            StringBuilder sb = new StringBuilder();
                            sb.Append("<html><head><title>HelpDesk Application</title>");
                            sb.Append("<link rel='alternate' type='application/rss+xml' title='HelpDesk Request Feed' href='taskfeed' />");
                            sb.Append("<style>body { font-family: verdana; }</style></head><body>");

                            sb.Append("<h1 style='color: red;'>Open HelpDesk Requests</h1><ul>");
                            foreach (HelpDeskRequest openItem in logic.RequestDatabase.FindAll(delegate(HelpDeskRequest hr) { return !hr.Closed; }))
                            {
                                sb.Append(string.Format("<li><a href='helpdesk://open?id={0}'>{1}</a></li>", openItem.ID, openItem.Subject));
                            }

                            sb.Append("</ul><h1 style='color: green;'>Closed HelpDesk Requests</h1><ul>");
                            foreach (HelpDeskRequest closedItem in logic.RequestDatabase.FindAll(delegate(HelpDeskRequest hr) { return hr.Closed; }))
                            {
                                sb.Append(string.Format("<li><a href='helpdesk://open?id={0}'>{1}</a></li>", closedItem.ID, closedItem.Subject));
                            }
                            sb.Append("</ul></body></html>");

                            StreamWriter streamWriter = new StreamWriter(response.OutputStream);
                            streamWriter.WriteLine(sb.ToString());
                            streamWriter.Flush();
                            streamWriter.Dispose();
                        }
                        response.Close();
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Unable to start HttpHandler. Are you running this application as an administrator?", "Running as administrator?", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

This post fits nicely together with yesterdays post on how gadgets can bring the service oriented architecture all the way to the desktop. By creating a protocol handler for your line of business application you provide a ultra thin layer of integration to hook into from "any" application. This simple concept could make your users more productive, save them lots of clicking, and open up to some nice workflow integrations. I hope you found the posting interesting, and as usual all comments are more than welcome! Before I wrap up, a few of disclaimers. The application has to run as administrator under Vista (because of registry settings and HttpListeners).Using protocol handlers like this isn't expressed best practices from Microsoft and can only be considered an idea I'm throwing out in the open. I haven't implemented it in any real world applications my self yet.

Exception handling is one of those things you have to learn and deal with as a .NET developer (or as a developer using many other languages and frameworks). Exception handling is a built in mechanism for detecting and handling runtime exceptions in your code. There are several things you need to keep in mind when thinking about exceptions in your application. Where do you throw your own custom exceptions? Where to you catch and log exceptions? How do you show exceptions to the end user?

The patterns and practices group have created some guidelines on how to best manage exceptions in your application, and even wrote an Exception Handling Application block. I think this block is now deprecated and have been replaced by the logging application block. Exception handling and logging tend to go hand in hand. And that's what brings me to the topic of this post; re-throwing exceptions.

I don't think I've blogged to much about my work related projects, but currently I'm working as a consultant on a project in the health care sector. The project I'm working on as a external consultant is to write a v2.0 of an internal application to manage research databases and collect electronic forms. The main goal of v2.0 is to decouple it from legacy systems in the health region so that the application can be used at other hospitals in other health regions in Norway.

Anyway, today I discovered that the way we handle exceptions in the application is a bit inconsistent so I decided to look into it. Most of the exception handling is done in the business layer where the exception is logged, before it's re-thrown (or at least that's what the developers who wrote the code thought) so that the UI can catch it and display it in a friendly manner. Most of the code looked something like this:

public static int DoSomething()
{
    try
    {
        return BusinessLayer.DoSomething();
    }
    catch (Exception ex)
    {
        Log.LogException(ex, "Something crashed...", EventLogEntryType.Error);
        throw ex;
    }
}

This is a common way to write code, and I've seen it several places. Developers thinks that this is the way to re-throw an exception. Actually it's not. When you're writing "throw ex", you're actually throwing a new exception, using "ex" as your exception object. When you throw a new exception in .NET the CLR needs to take a snapshot of the call stack and other environment variables to provide you with the information needed to debug the problem. The problem with the above example is that if some one else in a layer above you is catching the exception the stack trace will suggest that the exception occurred in ServiceLayer.DoSomething, and not in the underlying code. In some cases you actually want to hide the stack trace, and exception handling for services needs special considerations. But in most cases you actually want to re-throw the exception, to keep the stack trace correct and to save performance (taking a snapshot of the call stack and other variables are expensive).

I've created a simple example application showing the difference between throwing a new exception (as the example above) and re-throwing an exception within the catch block. The example "simulates" four layered application, with a data access layer, a business layer, a service facade and a user interface. Each layer is a simple class with one method, and the UI is the console application.

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ExceptionTest
{
    class DataLayer
    {
        public static int DoSomething()
        {
            int a = 10;
            int b = 0;
            int c = a / b;
            return c;
        }
    }
    
    class BusinessLayer
    {
        public static int DoSomething()
        {
            return DataLayer.DoSomething();
        }
    }

    class ServiceLayer
    {
        /// <summary>
        /// Creates a new exception by throwing ex in the catch block.
        /// </summary>
        public static int DoSomething1()
        {
            try
            {
                return BusinessLayer.DoSomething();
            }
            catch (Exception ex)
            {
                Log.LogException(ex, "Something crashed...", EventLogEntryType.Error);
                throw ex;
            }
        }

        /// <summary>
        /// Re-throws the exception by calling throw; in the catch block. 
        /// </summary>
        public static int DoSomething2()
        {
            try
            {
                return BusinessLayer.DoSomething();
            }
            catch (Exception ex)
            {
                Log.LogException(ex, "Something crashed...", EventLogEntryType.Error);
                throw;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine();
            try
            {
                ServiceLayer.DoSomething1();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("[New exception thrown]");
                Console.WriteLine(RemoveLongPath(ex.ToString()));
                Console.WriteLine();
            }

            try
            {
                ServiceLayer.DoSomething2();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Exception from data layer re-thrown]");
                Console.WriteLine(RemoveLongPath(ex.ToString()));
                Console.WriteLine();
            }
        }

        static string RemoveLongPath(string text)
        {
            return text.Replace(@"C:\Users\jonasf\Documents\Visual Studio 2005\Projects\ExceptionTest\ExceptionTest\Program.cs", @"C:\Program.cs");
        }
    }
}

The exception occurs in the data layer when dividing by 0, and is first caught in the service layer where it's logged and re-thrown.

There are two versions of the service method, one that throws a new exception by calling "throw ex;", and one re-throwing the exception using "throw;".

The output is shown in the screenshot below. Notice how the stack trace of the first call (yellow) stops in the service layer, while the second call (red) shows the entire stack trace.

Last week I got a call from a colleague who was struggling with a .NET performance issue. He's working a s a developer on a really large .NET project in the finance sector. The project is one of the largest implementations of a service oriented architecture in Norway. My colleague was working on a calculation service exposing some core calculation formulas and models used within the company. The formulas are fairly complex (I didn't understand any of it), but consisted mostly of large sums being accumulated iterative and there was no obvious reason why it took more than 3 minutes to calculate the numbers. Excel crunched the numbers in no time. Where had they had screwed up so badly?

Armed with ANTS profiler I showed up Monday afternoon to have a look at the problem. Following good programming practices the calculation service was well tested using unit tests, and they had a local test environment set up. All we had to do to profile the code was to run ANTS on one of the test suites. And the result from ANTS immediately revealed the problem. More than 99% of the entire running time of the test was spent on the EntityBase.Clone method. By following the "slowest code path" inside ANTS we managed to track down the code responsible for all the cloning. Turns out one libraries exposing "standard" math functions (relevant to the business domain) used and cloned an object derived from EntityBase. The EntityBase object is developed by another team within the business responsible for some of the core functionality across all services in the SOA architecture. The entity library was more or less a "black box" component to my colleague who hadn't thought that this might be the source of the problem.

The EntityBase class exposed some simple base functionality other developers could relay on. One of the major parts of the base class was the implementation of the IClonable interface. The IClonable is the standard way to implement deep copying of .NET objects. To make a shallow copy of an object you use the MemberwiseClone method. The implementation of IClonable in the base class used reflection to make it possible to clone any derived object with out writing any cloning code yourself. Using reflection to make your objects behavior dynamic is a really powerful concept. If you want to learn more about this there is an article and example base class for cloning objects up on The Code Project.

Using reflection is one of the most performance expensive things you can do within .NET. In some cases it's an invaluable feature, but in cases like this one it's the root of the problem. To solve the performance problem in this particular case the solution was to write a custom implementation of the Clone method on the object being cloned all the time by the math library.

By cloning the object field by field, instead of using reflection, we managed to get the time used to clone the object down from 190 to 1.5 seconds!

I've re-created the problem with a really simple example. The example is a tiny console application with one base class (BaseEntity) and one derived class (PersonEntity). The base class implements cloning using reflection, and the derived class implements a separate cloning method called QuickClone. In the Main method I create an instance of the person object and clone it 250 000 times using both Clone and QuickClone. The screenshot shows the results of the ANTS profiler. Cloning the object 250 000 times using Clone and reflection took 13.8 seconds. Cloning the object using QuickClone took 0.5 seconds… 

using System;
using System.Text;
using System.Reflection;
using System.Collections.Generic;

namespace ReflectionTest
{
    public class BaseEntity : ICloneable
    {
        public object Clone()
        {            
            object newObject = Activator.CreateInstance(this.GetType());
            FieldInfo[] newFields = newObject.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            FieldInfo[] oldFields = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

            for (int i = 0; i < oldFields.Length; ++i)
            {
                newFields[i].SetValue(newObject, oldFields[i].GetValue(this));
            }

            return newObject;
        }
    }

    public class PersonEntity : BaseEntity
    {
        private int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public override string ToString()
        {
            return string.Format("{0}, {1} years old", name, age);
        }

        public PersonEntity QuickClone()
        {
            PersonEntity newPerson = new PersonEntity();
            newPerson.age = this.age;
            newPerson.name = this.name;
            return newPerson;
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            PersonEntity person = new PersonEntity();
            person.Age = 20;
            person.Name = "Jonas Follesø";

            Console.WriteLine("Starting to clone...");
            for (int i = 0; i < 250000; ++i)
            {
                person.Clone();
                person.QuickClone();
            }
            Console.WriteLine("Done cloning...");
        }
    }
}

The point of this story is that if you play with reflection you might get burned. You need to know what you are doing. In this case I have no doubt that the framework guys knew what they where doing in the base entity class. I think the problem was that other teams within the company didn't know that the base class used reflection, and that this is something that might hurt performance badly. Another lesson learned is that if you have .NET performance problems, bring in ANTS right away. It's an amazing tool!

The last year there has been a wind of "dynamisms" sweeping the developer community. Developers are getting exited about dynamic languages in general, and perhaps one language in particular; Ruby. The Ruby programming language, and it's supporting frameworks, seams to spread allot of joy and happiness among web developers. Microsoft has recognized this, and has picked up on dynamic languages with IronPython, IronRuby and the Dynamic Language Runtime.

The keynote for day 2 of Developer Summit 2007 was held by Niclas Nilsson and was titled "Dynamic languages for statically typed minds". Niclas talked about talked about three dynamic languages (Ruby, Python, Groovy) and three static languages (C++, C# and Java), but focused mostly on Java and Ruby. Through and interesting talk and several good comparisons and examples Nicolas tried to open up the eyes of the C# and Java developers to this new world of dynamic languages.

Fellow RD Scott Hanselman have talked about dynamic languages several times on this blog. A couple of months back he did an interesting Hanselminutes episode covering dynamic languages (Ruby and PowerShell) from a .NET perspective. Yesterday he wrote a post trying to highlight some of the key aspects that makes Ruby an attractive programming language. I don't think he quite managed to get the message across, but his post caused a really interesting discussion in the comments section. Well worth checking out! Wilco Bauwer followed up on this with an interesting posts on why developers should explore new programming languages. As a developer you should never settle, and always try to improve your self as a professional. By learning new languages you can pick up bits and pieces from the language and its lifestyle that will make you an more efficient programmer. This discussion got me thinking about my programming background, and the different languages I've used over the years.

My dad works for the army, and through his job I got access to computers at an really early stage. When I was 5 or 6 he used to bring home a couple 8086 Apricot computers from work in the holidays so that me and my sister could play with it. I got into programming when I was 11 or 12, and the first language I used was QBASIC. The main reason was that it shipped with Windows/DOS.

Since I couldn't compile my QBASIC 1.0 programs I soon moved on to Borland Turbo Pascal with Borland Delphi as a natural next step. I remember I could do some really cool networking applications in Delphi by dragging and dropping visual components onto a form. You just dragged a TcpSocket component, set a few properties, and you had a simple chat application. Great times! With the web taking off I got into web development using VBScript and classic ASP and did that for quite some while. After high school I co-founded the company GreIT AS, where we built websites in ASP, and later a full blown content management system in C#. I picked up .NET and C# early 2002, and It was love at first sight.

Even though I consider myself a pretty good .NET developer I constantly try to improve as a programmer. This involves looking outside Visual Studio and see what other developers find interesting and cool. Last fall I took a really cool programming course on functional programming at the university. The course taught me about Scheme (LISP) programming and the beauty of functional programming. Writing Scheme and seeing some of the powerful concepts that arise you can do when the distinction between code and data blurs, and you start passing functions as parameters to other functions, or create code dynamically on the fly was an eye opener.

I doubt I'll ever write Scheme or LISP code in my professional career, but I've already found the concepts I learned useful when learning and understanding C# 3.0 and LINQ. Anders Hejlsberg and his team have introduced several concepts from functional programming in C#, including lambdas. An example of one of the cool things you can do is passing functions as predicates to filter method. In C# 2.0 you can do this using delegates and anonymous methods. In C# 3.0 you can even do this even more elegantly using the new lambda construct (taken from LISP).

//Create a list of persons
List<Person> persons = new List<Person>();
persons.Add(new Person("Jonas", "Follesø"));
persons.Add(new Person("Hege", "Røkenes"));
persons.Add(new Person("Håvard", "Sørbø"));
persons.Add(new Person("Gøran", "Hansen"));
//... more persons go here .../            

//C# 2.0 - Using an anonomous method to filter persons that starts with "J"
List<Person> jPersons = persons.FindAll(delegate(Person p) { return p.Name.StartsWith("J"); });

//C# 3.0 - Creating a function using lambda to filter persons that starts with "H"
List<Person> hPersons = persons.FindAll(p => p.Name.StartsWith("H"));    

The way I can leverage my LISP experience in C# is an example of what I mean by learning a new language and it's lifestyle. If you're interesting in learning more on functional programming and how this applies in C# 3.0 I suggest checking out this excellent Channel9 video with Anders.

Enough about functional languages, let's get back to the dynamic languages. All the buzz around dynamic programming might give you an impression that this is a brand new breed of programming languages. But actually it isn't. The first version of Python was released by Guido van Rossum in 1991, Ruby was released by a Yukihiro "Matz" Matsumoto in 1995, and the concept of dynamic typing go all the way back to the beginning of programming and the LISP language created in 1958.

I think there are a couple of reasons why people are starting to pick up dynamic languages, where one of the major driver is test driven development and unit testing. Much of the criticism of dynamic languages is that you get no "spell checking" from the compiler. You can add strings and integers in your code with out getting a compile time error. Most developer agree that a successful compilation isn't enough to ensure that a program work as intended. Therefore we need unit tests to run our code and do assertions to prove that the program works as expected. Great unit testing frameworks like NUnit and Junit, and even out of the box tool support in Visual Studio Team System, has made it an everyday task to write unit tests. Dynamic languages, such as Ruby, facilitates testing in a great way so when developers are picking up a dynamic language they can apply their unit testing habit to the code they write. This will catch your runtime exceptions and actually prove that the code works as intended.

Another important reason why people are exited about dynamic languages, and Ruby in particular, is productivity. Ruby is easy to write, and more importantly, is easy to read. When we write code we don't write it for the computer (the compiler is the one writing code for the computer), we're writing it for other developers. Expressing developer intend in a clear way is one of the most important things when writing software. How many times have you looked back at code you wrote a couple months ago, scratching your head asking "what the hell does this code do"? Languages like Ruby let's you express your intent in a very clear and crisp way, and with fewer lines of code:

# Ruby knows what you mean, even if you
# want to do math on an entire Array
cities  = %w[ London Oslo Paris
              Amsterdam Berlin ]
visited = %w[Berlin Oslo]
 
puts "I still need to visit the following cities:",
     cities - visited

The book "Code Complete" includes a chart on language expressiveness in terms of the statement ratio (lines of code) of a language compared to C.

Language Statements ratio Lines ratio
C 1 1
C++ 2.5 1
Fortran 2.5 .8
Java 2.5 1.5
MS Visual Basic 4.5  ?
Perl 6 6
Smalltalk 6 6.25
Python 6 6.5

Personally I haven't written much Ruby code yet, but I'm currently playing with it and finding it lots of fun and really interesting. With IronRuby and the possibility to run Ruby code on .NET I might even be able to use it for work related projects in a not to distant future. The way I was introduced to Ruby code was actually through an ASP.NET project at work where we used the Watir framework to do functional testing of a web application. Ruby is definitely the next language I'm going to learn.

Which languages have you used, and what is the next language you're learning?

Odd Martin Solheim, a co-worker from ABEO, and Hans Christian Alnæs just got their article titled "Go for the low hanging fruit!" posted on Agile journal. It's an excellent article discussing how you as an professional can improve the way you work. The article talks about how you as an employee can make things change in your company by using certain techniques, and how to focus on your goal (what you want to achieve/change).

The article lists seven steps/points to achieve your goal:

  1. Make a Change Backlog
  2. Find the low hanging fruit
  3. Establish a raiding party
  4. Establish a success story
  5. Go to war
  6. Celebrate!
  7. Start over

The article is well written and easy to read.

Odd Martin have obviously used some of his experiences from ABEO in the article. Odd Martin is an excellent project manager/Scrum Master, and is one of the people pushing Scrum as the default development method in ABEO. He's also the guy who introduced TargetProcess as a project management system, which works well with the Scrum method.

I've had the pleasure of working with Odd Martin on a project before Christmas. During the project I learned a few new tricks, specially on functional web testing and smoke testing. He also introduced me to the book "ShipIt!", which is an excellent book on shipping software (and at the end of the day, that's what we're trying to do).  If you like their article on "the low hanging fruit", you're definitely going to like "ShipIt!".

This blog post is the first one in a series of posts covering how to send free SMS messages using the Ung1881 web site. This first post discuss how to sign into a "Forms Authentication" protected ASP.NET web site, store an authentication cookie, and programmatically post web forms. Even if you're not interested in the free SMS messages you might still find the article interesting. The next part will be on how to use the .NET Class Library in a Windows Vista Gadget.

Unlimited free SMS messages, exposed as a .NET Class Library… Sounds to good to be true? Well, It's not, but as with everything else that's free (except Open Source?) it has a catch.  You can only send messages containing 130 characters. The last 30 characters are reserved for commercials. The good thing is that you can send as many messages as you want, and your own number show up as the sender. The service is offered by "Opplysningen 1881"  (Norwegian Number Enquiry) through their new portal "Ung1881", a page aimed at young people. In order to use their SMS service you need to be a have a Norwegian social security number, and a phone number. They need your social to do a lookup and verify that you're a real person. Even though you might not be able to register for an account at "Ung1881" you might still find the code and article useful since the concepts apply for any web application.

I got interested in the "Ung1881" after Håvard pointed me to it some weeks back. After doing some re-search it turned out someone had written a Mac OSX Widget letting you send SMS messages directly from your Mac desktop. My immediate idea was to port this widget to the Windows Vista Sidebar, but after looking at the JavaScript code of the widget I soon realized this was a bad idea. The Mac OSX Widget is depending on a third party server doing the screen scrapping server side, so all your SMS messages (including your username and password) are sent through a third party using HTTP GET like this: http://www.theretard.net/smss.pl?u=username&p=password&n=number&m=message. I don't know the guys behind theretard.net, but there's no way I'm trusting them with my username, password and every SMS message I ever send. Just imagine the password harvesting possibilities! On top of this they don't even use HTTPS for communication.

I decided I had to write a .NET Assembly wrapping the "Ung1881" service, so that I could re-use the functionality in other applications, like a Windows Vista Sidebar Gadget, a console application, Outlook 2007, PowerShell etc.

The technique of accessing web sites programmatically is commonly refereed to as  screen scrapping. Since the Ung1881 portal doesn't offer any kind of programming interface, you need to tap in to it at the HTTP level, and "pretend" that you're a regular user accessing the page with a browser. Since you're depending on the actual HTML structure page you're application might become unstable, and if the owner of the source you're scrapping change their HTML it might break your application. You also need to be careful that you're not violating copyright regulations, by for instance downloading weather information and displaying it as your own. In the case of "Ung1881" terms don't say anything about "automatic access", and as long as you have a valid account they still get their 30 character commercials included in every SMS message you send. I don't think you'll get into trouble by using this code, but if you do don't blame me!

The "Ung1881" portal is running on the .NET-based Content Management System EPiServer, and uses ASP.NET Forms Authentication to authenticate users on the portal. Forms Authentication normally works by using an authentication cookie. When you logon the server authenticates your username and password. If your credentials are valid, it issues a cookie your browser sends with subsequent requests to the site. So in order to wrap the SMS service in a C# class you basically need to write a "non visual" Web Browser. You need to make a request to their login page, use HTTP POST to post a username and password to the server and store the authentication cookie sent back in the response. On subsequent requests you need to attach the authentication cookie in order to access protected pages (like the send SMS page).

The first thing I did when implementing the "Ung1881" proxy class was to analyze the HTTP traffic going between server and client. There are several tools you can use to monitor network traffic at different levels. My preferred HTTP monitor is Fiddler. Fiddler act as a HTTP Proxy, so all you're HTTP requests are routed through Fiddler. Using Fiddler you can look at the raw requests, the headers, the posted form values etc. New in Fiddler v2.0 is support for HTTPS, which is excellent since the "Ung1881" portal is using HTTPS for secure communication. Another excellent tool for network monitoring is oSpy, written by Ole André Vadla Ravnås - a brilliant programmer, reverse engineer and in general a really nice guy!

The above screenshot shows all the HTTP traffic between Internet Explorer and the "Ung1881" web server. As you can see in the left column the site is quite "chatty" because of all the pictures, advertisements, script, style sheets etc. If you enter your username, password and hit the login button, and look at the request made to the URL https://www.ung1881.no/default____3.aspx you can figure out which form elements that are being posted to the server. The site contains quite a few form elements, but the interesting parts are the following:

Content-Disposition: form-data; name="defaultframework:login:tbxUsername"
myusername

Content-Disposition: form-data; name="defaultframework:login:tbxPassword"
mypassword

Content-Disposition: form-data; name="defaultframework:login:LoginButton.x"
0

Content-Disposition: form-data; name="defaultframework:login:LoginButton.y"
0

Content-Disposition: form-data; name="__VIEWSTATE"
dDw5NDE0MjMxMzc7O2w8ZGVmYXVsdGZyYW1ld29yazpsb2dpbjpMb2dpbk
J1dHRvbjtkZWZhdWx0ZnJhbWV3b3JrOnNlbmRzbXM6YnRuU2VuZDs+Pp5c
kvQYH64y3L+4/9ebcQzi7GmX

I've highlighted the names of the form elements. You could have figured out most of this just by looking at the HTML source, but I find it easier to use Fiddler. The thing that might not be too obvious just by looking at the HTML source, is what form value get posted when you click the login image button. The HTML fragment looks like this:

<input type="image" name="defaultframework:login:LoginButton" id="defaultframework_login_LoginButton" class="..." src="..." alt="" />

If you look at the HTTP POST values above you can see that there are two values posted back to the server when you click the login button, defaultframework:login:LoginButton.x and defaultframework:login:LoginButton.y. Both have the value 0. I took a few seconds before I figured what was happening, but apparently the HTML specifications says that <input type="image"> should post back the x and y values with the coordinates of where the user clicked the image. For accessibility reasons this is deprecated, and if you need x and y values from an image you should use an <imgemap> element instead. In order to confirm with the HTML standard the browser posts an x and y value back to the server.

Another important thing to note is that "Ung1881" is an ASP.NET application, and therefore is depending on the "__VIEWSTATE" form element. This hidden form value holds an encoded string representing the state of the application on the server. If we don't include this value in our scrapper the ASP.NET application can't figure out what state it's in, and how to process the request correctly.

If you look at the response sent back from the server you see that the server issues three cookies:

ASP.NET_SessionId=jnq5hh45zuuu0xyigc1jtm45; path=/

.EPiServerLogin=
6E1DBAC98D4073F956DA2000EBF122056E335441CCC7756F98B2
A229387EC47E446701A29
D36C4497553A5409F40322142C84B140E93C25CFC468C81
5B25CCC35648CE9B03C96XXXXXXXXXXXX; path=/;HttpOnly

ung1881.no=3568924299.20480.0000; expires=Sun, 25-Mar-2007 16:22:15 GMT; path=/

The interesting part is the .EPiServerLogin-cookie which is the authentication cookie. By adding this cookie to my subsequent requests, the server can tell that you're an authenticated user.

Now that we know what's going on when login into the page it's time to send an SMS message. I click the "Send SMS" link on the page, which takes me to the following URL: https://www.ung1881.no/Templates/SMS____24.aspx. I enter a phone number and message, and hit the button to send the message. The requests gets picked up by Fiddler, and by analyzing the request I figure out which form elements I need to post to the server in order to send a message:

Content-Disposition: form-data; name="defaultframework:_ctl2:Smssend:txtPhonenumber"
myNumber

Content-Disposition: form-data; name="defaultframework:_ctl2:Smssend:txtText"
myMessage

Content-Disposition: form-data; name="defaultframework:_ctl2:Smssend:butSend.x"
46

Content-Disposition: form-data; name="defaultframework:_ctl2:Smssend:butSend.y"
9

Content-Disposition: form-data; name="__VIEWSTATE"
*LARGE CHUNK OF STATE*

So after analyzing the application I now know the following about the communication between browser and server:

  • The login URL is: https://www.ung1881.no/default____3.aspx
  • The username form element is named: defaultframework:login:tbxUsername
  • The password form element is named: defaultframework:login:tbxPassword
  • The login button posts two values: defaultframework:login:LoginButton.x and defaultframework:login:LoginButton.y
  • The server issues an authentication cookie named .EPiServerLogin
  • The send SMS URL is: https://www.ung1881.no/Templates/SMS____24.aspx
  • The number form element is named: defaultframework:_ctl2:Smssend:txtPhonenumber
  • The message form element is named: defaultframework:_ctl2:Smssend:txtText
  • The send SMS button posts two values: defaultframework:_ctl2:Smssend:butSend.x and defaultframework:_ctl2:Smssend:butSend.y

Now that I know everything I need to know about the form elements It's time to write a C# class wrapping the site. The code is fairly well commented, so I won't describe it in detail. The key classes involved in the scrapper are the HttpWebRequest, HttpWebResponse, CookieContainer, StreamReader and StreamWriter classes. Another interesting part of the code is the private GetViewState method which extracts the view state of the page so that you can post it back to the server.

 

// Copyright (c) 2007, Jonas Follesø
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Jonas Follesø nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY Jonas Follesø ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Jonas Follesø BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Security.Authentication;

namespace Ung1881
{
    /// <summary>
    /// Proxy class wrapping the Ung1881 site for free SMS messaging.
    /// </summary>
    public class Ung1881Proxy
    {
        /// <summary>
        /// Variable used to store the authentication cookie.
        /// </summary>
        private CookieContainer cookies;

        /// <summary>
        /// Variable used to store the base uri of the page.
        /// </summary>
        private string baseUri = "https://www.ung1881.no/";

        /// <summary>
        /// Default constructor.
        /// </summary>
        public Ung1881Proxy()
        {
            cookies = new CookieContainer();
        }

        /// <summary>
        /// Login on Ung1881 using username and password.
        /// Authenticates against the site and keeps the auth cookie for next request.
        /// </summary>
        /// <param name="username">Username used to logon.</param>
        /// <param name="password">Password used to logon.</param>
        public void Login(string username, string password)
        {
            //Validate arguments.
            if (username == null || username.Length == 0)
                throw new ArgumentException("You must provide a username!", "username");

            if (password == null || password.Length == 0)
                throw new ArgumentException("You must provide a password!", "password");
            
            string loginUri = baseUri + "default____3.aspx";

            // Perform the first http request against the asp.net application login site.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUri);

            // Get the response object, so that we may get the session cookie.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Populate the cookie container.
            request.CookieContainer = cookies;
            response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);            

            // Read the incoming stream containing the login dialog page.
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string loginDlgPage = reader.ReadToEnd();
            reader.Close();            

            // Extract the viewstate value from the login dialog page. 
            // We need to post this back, along with the username and password
            string viewState = GetViewState(loginDlgPage);

            // Build postback string.
            // This string will vary depending on the page. The best way to find out what your postback 
            // should look like is to monitor a normal login using a utility like Fiddler.
            string postback = String.Format("__VIEWSTATE={0}&defaultframework:login:tbxUsername={1}" +
                                            "&defaultframework:login:tbxPassword={2}" + 
                                            "&defaultframework:login:LoginButton.x=0&defaultframework:login:LoginButton.y=0",
                                            viewState, username, password);


            // Our second request is the POST of the username / password data.
            request = (HttpWebRequest)WebRequest.Create(loginUri);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = cookies;            

            // Write our postback data into the request stream
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(postback);
            writer.Close();

            reader = new StreamReader(request.GetResponse().GetResponseStream());
            loginDlgPage = reader.ReadToEnd();
            reader.Close();

            int index = loginDlgPage.IndexOf("Logg ut", StringComparison.OrdinalIgnoreCase);

            if (!CheckAuthenticationCookies() || index == -1)
            {
                throw new AuthenticationException("Unable to authenticate user. Check your username and password.");
            }            
        }

        /// <summary>
        /// Method sending a new SMS message trough Ung1881.
        /// </summary>
        /// <param name="phoneNumber">The phone number of the receiver.</param>
        /// <param name="message">The message to send.</param>
        /// <returns>True if the message was sendt sucsessfully.</returns>
        public void SendSms(string phoneNumber, string message)
        {
            //Validate arguments
            if (phoneNumber == null || phoneNumber.Length == 0)
                throw new ArgumentException("You need to provide a phone number!");

            if (message == null || message.Length == 0)
                throw new ArgumentException("You need to provide a message!");

            //Check that we have an authentication cookie.
            if (!CheckAuthenticationCookies())
                throw new AuthenticationException("User not authenticated. Call Login first!");

            //our third request is for the actual webpage after the login. 
            string smsUrl = baseUri + "/Templates/SMS____24.aspx";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(smsUrl);
            request.CookieContainer = cookies;

            //and read the response
            StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());
            string page = reader.ReadToEnd();
            string viewState = GetViewState(page);

            string postback = String.Format("__VIEWSTATE={0}&defaultframework:_ctl2:Smssend:txtPhonenumber={1}" +
                                            "&defaultframework:_ctl2:Smssend:txtText={2}&defaultframework:_ctl2:Smssend:butSend.x=0" +
                                            "&defaultframework:_ctl2:Smssend:butSend.y=0", viewState, phoneNumber, message);

            reader.Close();

            request = (HttpWebRequest)WebRequest.Create(smsUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = cookies;

            //Write our postback data into the request stream
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(postback);
            writer.Close();

            //Execute the request and read the response.
            reader = new StreamReader(request.GetResponse().GetResponseStream());
            page = reader.ReadToEnd();
            reader.Close();

            //Verify that the message was sent.
            if (!page.Contains("SMS sendt"))
            {
                throw new Ung1881Exception("Unable to send SMS message. Unknown error.");
            }            
        }

        /// <summary>
        /// Check if the user is authenticated.
        /// </summary>
        /// <returns>True if the user is authenticated.</returns>
        private bool CheckAuthenticationCookies()
        {
            bool authenticated = false;

            //Check that we have cookies.
            if (cookies != null)
            {
                //Check all cookies for the EpiServerLogin cookie.
                foreach (Cookie cookie in cookies.GetCookies(new Uri(baseUri)))
                {
                    if (cookie.Name != null && 
                        cookie.Name.Equals(".EPiServerLogin", StringComparison.OrdinalIgnoreCase))
                        authenticated = true;
                }
            }
            return authenticated;
        }

        /// <summary>
        /// Extract the viewstate data from a page.
        /// </summary>
        /// <param name="aspxPage">The raw HTML of the page.</param>
        /// <returns>Thew viewstate data of the page.</returns>
        private string GetViewState(string aspxPage)
        {
            Regex regex = new Regex("(?<=(__viewstate\".value.\")).*(?=\"./>)", RegexOptions.IgnoreCase);
            Match match = regex.Match(aspxPage);
            return System.Web.HttpUtility.UrlEncode(match.Value);
        }
    }
}

To test the class I've created a simple console application accepting a username, password, number and message as it's argument. Using the console application you can send SMS messages by typing the command: "SMS username password number message". If you add the folder containing the .EXE to your environment path you can send SMS messages from any command prompt.

 

// Copyright (c) 2007, Jonas Follesø
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Jonas Follesø nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY Jonas Follesø ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Jonas Follesø BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Ung1881;
namespace ConsoleScraper
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //Check that we have at least four arguments (username, password, number, message)
                if (args.Length < 4)
                {
                    Console.WriteLine("Usage: SMS username password number message");
                }
                else
                {
                    //Extract variables from arguments.
                    string username = args[0];
                    string password = args[1];
                    string number = args[2];
                    string message = string.Empty;

                    //Build up the message.
                    for (int i = 3; i < args.Length; ++i)
                    {
                        message += args[i];

                        //Add space if this isn't the last word of the message.
                        message += (i == args.Length - 1) ? string.Empty : " ";
                    }

                    Console.WriteLine("Sending message \"{0}\" to number {1}", message, number);

                    //Send the message.
                    Ung1881Client client = new Ung1881Client(username, password);
                    client.SendMessage(number, message);                    
                    Console.WriteLine("Message \"{0}\" sent to number {1}", message, number);
                }
            }
            catch (Exception ex)
            {
                //Simple exception handling.
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

So that's about it. A simple C# library allowing you to send unlimited free SMS messages through "Ung1881". You can choose to either download the compiled binaries or the source code. In the next part of this article/post I'll discuss how to use the library in a Windows Vista Sidebar Gadget.

If you have any questions, comments or bugs, or find the library useful, please drop me a comment!

Lead programmer Mats Pedersen workingA common programming technique I've used with great success trough out the years is pair programming.  I assume most of the readers of this blog know what pair programming is, but incase any of my non-programming friends read this blog par programming is exactly what the term says: two programmers working on the same code, on the same computer.

The two programmers have different "roles" when doing pair programming. The programmer controlling the mouse and the keyboard is the "driver", and is doing the actual programming. He's taking all the immediate decisions, like how to structure the code, how to write the if's and else's, what to name the variables etc, just like the driver of a car is making decisions like which lane to use, how to turn etc. The other programmer is the "navigator" looking ahead and planning what to implement next, and overlooking the overall structure of the code. When the programmers reach some kind of "milestone", such as completing a class or implementing some kind of functionality the programmers change role.

Pair programming have several advantages, such as:

  • Higher quality of the code (two people on the same problem)
  • Transfer knowledge from one programmer to the other
  • Higher productivity. When you're coding with some one you don't waste time on Engadget or Gizmodo.

I haven't blogged too much about my work related projects, but currently I'm working on a project at HEMIT (the company in charge of all the IT systems in the health region). The project is about turning an internal application into a full blown product they can sell to other health regions and hospitals as well. The major part of the project is about decoupling the system and eliminating dependencies on systems that are only available in the middle Norway health region, so that we can implement providers for systems used elsewhere.

We're currently three developers working on the project, and we've been using pair programming a lot. This Thursday we took pair programming o the next level by connecting two mice and keyboards and two 19" monitors to the same laptop. This way we can easily switch roles, and we don't need to rub shoulders while programming. The laptop didn't have any problems handling multiple mouse/keyboards, and it worked out really well. There are also some code editors allowing two developers to work on the same source file remotly (remote pair programming). This way you can do pair programming remotely. I don't think there are any Visual Studio plug-ins giving you this functionality, but if you know of one drop me a comment.

gameoflifeGame of Life is one of those simple, yet really fascinating mathematical ideas you sometime learn about. One of the assignments in the course "object oriented software development" is to first model the "Game of Life" and then implement it in Java.

The Game of Life was invented by Dr. John Conway, and is one of the simplest examples of what is sometimes called "emergent complexity" or "self-organizing systems." Life isn't a game in the traditional sense of the word. It's a grid filled with cells, either dead or alive. Some simple rules determines the state of a cell. The rules that rule the universe of "Life" are as follow:

  • A dead cell with exactly three live neighbors becomes a live cell (birth).
  • A live cell with two or three live neighbors stays alive (survival).
  • In all other cases, a cell dies or remains dead (overcrowding or loneliness).

I got really fascinated by this simple "game", and after doing some reading on the subject it turns out you can implement a "turing machine" in Live, which basically means you can implement any computer program as a pattern inside the "Life" game. For instance there are examples where people have implemented programs that finds prime numbers using the simple rules of "Life".

If you're interested in learning more about "The Game of Life" I recommend checking up the site "Wonders of Math". The Wikipedia article on the subject also gives a nice introduction to the game. If you want to get the latest and greatest discoveries of new and interested patterns in "Life" the "Game of Life News" site is the place to be. If you want to learn how to implement a touring machine in "Life" check out this PDF document. If you just want to check out the "code", check out this gif image showing the touring machine pattern.

If you want to play with Game of Life your self you can either run my compiled version directly (JAR) or download a ZIP file containing both the compiled version and the Java code.

ScreenshotWant to congratulate Eric Carr (he need to get something up on his site) as the winner of the Gadget development competition I helped arrange as part of MSDN Live spring 2006. Eric wrote three really cool gadgets for Live.com (and MSN Spaces) that you definitely should check out:

Eric is the lucky winner of a Xbox 360! Looking forward to see you online on Xbox Live.

 

During the MSDN Live events this spring we announced an Gadget development competition. Just wanted to write a quick reminder and encourage everyone to give gadget development a try. There haven't been that many contributions, so if you write a gadget you'll have a fair chance at winning the Xbox 360.

So, the rules are simple: Write a Live.com or Vista Sidebar gadget and send it to me at jonas@follesoe.no, or post it in the http://www.microsoftgadgets.com/ gallery.

The deadline for the competition is august 15. The winners will be announced late august/early september.

You'll find all the information needed to get started over at http://www.microsoftgadgets.com/. You can also check out the example code and slides from the MSDN Live events in this blog post.

God summer, and good luck!

The "Atlas" Control Toolkit is a set of nine great controls and extenders that use "Atlas" technologies and allow developers to easily improve the client experience on their websites.  All of the controls come with full source, and the toolkit also includes Visual Studio 2005 templates to get you started writing your own controls.

You can read more about the Atlas Control Toolkit over at http://atlas.asp.net/default.aspx?tabid=47&subtabid=477 and http://atlas.asp.net/atlastoolkit/.

Just got the word from Microsoft Norway, our team is going to represent Norway in the Nordic finals of Imagine Cup 2006. I don’t want to talk that much about the idea yet… Don’t want to give the Swedes or Danish teams and competitive advantage. The finals is held in Oslo 05.mai, and hopefully we’ll do good enough to reach the world final in India in august. Last years Nordic finals were lots of fun, and the after party was great!
Imagine Cup is an annual competition for students held by Microsoft. The category our team is competing in is software design. You can read more about Imagine Cup over at TheSpoke.

Edward Bakker wrote a blog post yesterday on the Service BAS, a new project from the Microsoft Pattern & Practices team. So what is Service BAS?

Service BAT is a toolkit that provides architectural guidance, tools, patterns, wizards, etc. to help you designing and building services using Windows Communication Foundation and ASMX. The Guidance Automation Toolkit is used to integrate all of this very nicely into Visual Studio.NET 2005

So basically the Service BAT is going to help you build and architect services on the Windows platform. The Visual Studio templates that comes with Service BAT includes items such as “data contract”, “fault contract”, “business entities”, “client” and many more. It looks like Service BAT is going to be a great tool, nicely integrated into Visual Studio 2005, helping you to do stuff like contract first Web Service development.

I definitely need to do some more investigation on the Service BAT as soon as a public version of the toolkit is available. You can read more about the Service BAT over at Edward’s blog, and the code will be made available over at the Service BAT GotDotNet workspace.

Xbox360netThe Game Developers Conference 2006 finished a couple of days ago, so some of you might have heard about this already. Microsoft announced a couple of interesting news at the GDC, among then XNA Studio, XNA Framework and XNA Build.

XNA Studio is a customized version of Visual Studio 2005 Team System aimed at game studios. It helps game studios manage the development process and “content pipeline” (getting all the sound, graphics, models, textures etc into the game).

XNA Build is a tool helping the studios to streamline the software build process, kinda Msbuild on steroids.

How ever, the most interesting announcement was the XNA Framework. This is a custom implementation of the .NET Framework that runs both on the PC and the Xbox 360. The framework contains a set of class libraries to help developers build games faster (and cheaper). By leveraging the XNA Framework cross platform development also become much easier. Basically what this mean is that you can write Xbox 360 games in C#. How cool is that?!  By making Xbox 360 game development accessible for smaller game publisher we’ll hopefully see more innovation and cool games coming out. This combined with the Xbox Live Marketplace distribution model opens up lots of new business opportunities for smaller game developers. Now we just have to hope that the rumors about 100$ Xbox 360 debug units are true… The XNA is available for download as a CTP.

Here are some of the information from the press conference where XNA was announced:

"We've been writing games for the last 15 years as monolithic, single-code bases that are growing unwieldy and complex," says Chris Butcher, lead developer at Bungie Studios. "C# on Xbox 360 lets us think about new modes of programming. It lets us get back to creating a game rather than wresting with code, while maintaining the real-time performance that we need."

Read the whole story over at Xbox.com.

<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910