Programming in C#, Java, and god knows what not

SQL Server 2008 R2

A lot of stuff has been released this month from Microsoft. There was Visual Studio 2010, Office 2010, and now, SQL Server 2008 R2.

It is just evolution. Most of changes are directed toward big customers (e.g. support for up-to 256 logical processors) and there is little reason to upgrade if everything is working for you.

Will I upgrade? Of course I will! :)

96 DPI

Illustration

Probably every programmer on this world has his image collection to use in toolbars. It is usually collected over years and gets reused quite a lot. I have collection of my own and it seemed like a natural solution to use it in WPF also.

As I am big fan of high DPI setting and I got used to expect little bit of blurriness in my toolbar as unfortunate result of scaling bitmap from 16x16 (at 96 DPI) to 20x20 (at 120 DPI). However, nothing could prepare me for amount of blur that WPF brought.

Quick search discovered a clue and look on my system confirmed it. Almost all images I had were 72 DPI. That meant WPF did scaling even on systems with “normal” DPI settings.

Scott gave easy fix in form of PNGOUT tool. I tried it out and checked results in Paint.NET. Unfortunately, instead of promised 96 DPI, I got 120 DPI images. Issue here is that PNGOUT uses DPI settings as defined on system. High-DPI setting on my system meant that PNGOUT will not work correctly without configuration change (and required logoff/logon).

Quite annoyed I made quick program in C# that just loads whatever image you give it on command line (e.g. “dpi96.exe *.png”) and changes it’s DPI setting. This finally worked as promised. This small utility is available for your use also.

P.S. Yes, I know that I should prepare separate bitmaps for all common DPI settings. I am lazy and artistically-challenged.

P.P.S. This utility was made in less than 10 minutes. Do not expect extra-quality code (or any exception handling).

The Devil Is In The Details

In quite few programs I see following pattern:

void OnMyEvent(EventArgs e) {
    if (this.MyEvent != null) {
        this.MyEvent(this, e);
    }
}

I must confess that I use same pattern in quite a few pieces of my own code. Nevertheless, this is wrong.

Issue here is that MyEvent can change between check and call statements. If change consists of adding one more delegate everything is fine. If change is removing all existing delegates you are in trouble.

Here is scenario. First line will check whether MyEvent is different than null (which it is at that point in time) and, exactly at that time, control switches to another thread and makes MyEvent null. Once our thread resumes it will use MyEvent which is now null. Exception!

This issue is highly timing sensitive and it is near impossible to reproduce it. You may have that bug for couple of years and never hit it. But it is there.

There are two distinct paths to remove this problem. One is just putting everything into lock statement. This will fix issue but it will also introduce overhead, performance problems and even potential deadlocks. It all depends on what exactly is done in called method. It is not a pattern I would be comfortable with.

Another path is to exploit fact that event delegates are immutable. Every instance has all data needed and if you copy it to local variable there is no need to worry about it changing value. With simple change we now have correct code:

void OnMyEvent(EventArgs e) {
    var ev = this.MyEvent;
    if (ev != null) {
        ev(this, e);
    }
}

10-4

Illustration

Visual Studio 2010 is here!

MSDN subscribers can start download immediately while others will need to wait a little.

As soon as I download it, fate of Visual Studio 2008 is sealed. So long, and thanks for all the fish.

[2010-04-12: Express editions are available for download now.

[2010-04-12: Trial version of full Visual Studio is also available .

[2010-04-12: Unfortunately there is no Ribbon control for managed code. Big disappointment for me.

WPF in Story of Resources.

As I started to play with WPF and XAML one of first things was to get some free vector images. Those images came already formated as XAML resources:

<ResourceDictionary ...>
    <DrawingImage x:Key="Horizon_Image_Up1">
        ...
    </DrawingImage>
</ResourceDictionary>

All one needed to do was to include them as resource. I personally like to do that at application level:

<Application ...>
    <Application.Resources>
        <ResourceDictionary Source="Resources/Left1.xaml" />
        <ResourceDictionary Source="Resources/Down1.xaml" />
        <ResourceDictionary Source="Resources/Up1.xaml" />
    </Application.Resources>
</Application>

Once we do this there will be error message greeting: “Property ‘Resources’ accepts only one object.”

There are two solutions to this problem. First one is obvious - put all resources in same file. I personally tend to avoid it since I like to reuse resources in multiple projects and I hate carrying bunch of unused images.

Second solution is to merge all those dictionaries into one. Fortunately, there is simple way to do it:

<Application ...>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <Application.Resources>
                <ResourceDictionary Source="Resources/Left1.xaml" />
                <ResourceDictionary Source="Resources/Down1.xaml" />
                <ResourceDictionary Source="Resources/Up1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

With that you have single dictionary consisting of all individual images. Do notice that, if there is same key defined in different files, only image that was defined last will be used.

Adventures From SVG to XAML

Illustration

As huge fan of ribbon interface it was just a matter of time before I started playing with WPF flavored version. First thing that became obvious is that my standard toolbar bitmaps are not good anymore.

My default 16x16 icons looked slightly blurry on higher DPI settings when used in Windows Forms applications and I didn’t mind it much. Same icons in WPF looked just plain awful. I spent some time playing with various settings to get better results but even best settings could not hide fact that bitmaps were used. It was quite obvious that vector-based icons were what I needed.

There are some free XAML toolbar icons available but any meaningful project will have problems finding right (free) icon for the job. Since there is quite a selection of free SVG icons, thought came about converting one into another. How hard it can be to convert one vector drawing into another one.

I decided to test this on various media buttons since that was exactly what I needed for one project.

First thoughts went toward InkScape. This is great vector drawing tool with option to save files as XAML. Resulting file used canvas for positioning various elements and thus it was not possible to use it as ribbon image. Simplest solution failed me.

Another solution was exporting file in PDF and then importing that into Expression Design and exporting it as XAML. It worked. However, results were less than satisfactory. All gradients were rendered as image instead of vector. Scaling picture didn’t quite feel right.

I spent better part of night and nothing quite worked.

Best results that I got were with Svg2Xaml library. It is LGPL project in very early phase (version 0.2) of development but I do not see any alternative library that is half as good.

Examples included with that library are quite good but I decided to create another one just for fun. As always, result of that tinkering is available for download.

Alternate Data Streams

NTFS has quite a few features that are hidden from everyday user. One of features that is difficult to access is alternate data streams.

Additionally to normal content, each file can have additional content attached to it. That content is, for all practical purposes, independent of original file content and it can contain anything. Most common stream is “Zone.Identifier”. It gets added by Internet Explorer (and some other browsers) to each executable to mark it as “unsafe”. Before such file gets executed you get security warning with notification that file arrived from big-bad-Internet.

Unfortunately this is as far as using this feature goes in Windows. Although one could think of thousands of more uses for it (e.g. adding thumbnails to file itself instead of separate file) its downfall is support on other file systems. Mere act of copying file to FAT partition will strip additional file streams. Mailing it is out of question and not even HTTP has any provisioning for it. With all that in mind, it is very unlikely that it gets used for anything more than temporary data.

If you are C# programmer and you have purpose for ADS, you will stumble upon another problem - it has no support in .NET framework. This is where this post gets useful.

I decided to implement support for alternate data streams in FileStream-like class that allows for same read/write functions to be used as in any Stream. It just wraps native CreateFile function into some FileStream contructor overloads. For deletion of particular stream within file we can use native DeleteFile and stream-specific functions (FindFirstStream and FindNextStream) will take care of enumeration.

I will let source code speak for itself.

Backing Field Must Be Fully Assigned

Structures are peculiar creatures in C#. One of more interesting peculiarities comes in combination with auto-implemented properties.

Lets begin with following struct:

public struct Test {
    public Test(int a) {
        this.A = 1;
    }

    public int A;
}

It is something that works, but having variable A directly exposed is not something that looks too good. Auto-implemented properties come to rescue:

public struct Test {
    public Test(int a) {
        this.A = 1;
    }

    public int A { get; set; }
}

This looks much better from design point of view. However, it also does not compile. It will greet us with: “Backing field for automatically implemented property ‘Test.A’ must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.”

Solution is quite simple, just call default constructor (as suggested in error message) and everything is fine:

public struct Test {
    public Test(int a)
        this(): {
        this.A = 1;
    }

    public int A { get; set; }
}

Unfortunately, you gain something, you lose something. Our original structure stops us when we forget to initialize field and I think of this as great feature. It ensures that we cannot forget a field.

Solution with auto-implemented properties has no such assurance. Since we need to call default constructor at one point or another, we will end-up with all fields initialized by struct itself. There will be no further checks whether fields are set or not.

While code did get nicer, our refactoring just got harder.

2010 App Cannot Be Found in Local Install Folder

Illustration

Notice: there is quite some ranting going on here, skip to bottom for solution.

I am quite a big fan of Formula 1 racing and, of course, God of Irony decided that I am to be traveling at exact time of race. I was hoping to get some coverage on my mobile phone and I connected to live timing page only to find that my login from last year is not valid.

It figures that I would forget that you need to re-register for this EVERY year. And, of course, neither Internet Explorer or SkyFire would work. They used some strange ordering of elements and submit button was just not visible. After initial frustration, I did find a solution. There is mobile version of site. There I was finally able to register.

I went to download mobile application that would give me access to all race data. My phone was listed among supported and I downloaded application, started install - only to be greeted with “2010 App cannot be found in local install folder”.

Shit, I thought, Internet Explorer is playing games again, I will try SkyFire - same result. In moment of desperation I even installed Opera Mobile only to have same issue. Notice that I was now almost an hour into race and with no data other that first three drivers. I was quite nervous.

In faq they mentioned using JavaFX for running application. In moment of desperation I downloaded it and, what would you know, application started.

There was some initial confusion with entering data because some idiot decided that my mobile must be limited to T9 entry. That meant that, even as phone had physical QWERTY keyboard, I needed to use my keypad to login. As Murphy would have it, after all that trouble, application was unable to connect to my 3G Internet. I fiddled with quite a few settings and gave up…

This morning I checked what exactly was happening and I noticed problem. My install file (Formula1.jad) was only 397 bytes in length. My default Java engine (Esmertec Jbed) didn’t know how to get rest of data. No direct link was present in jad but I figured that jar cannot be too far. Using my laptop, I downloaded jar from same location where jad was. It was enough to copy link and change extension.

I uninstalled JavaFX since I had no use of Java engine without Internet access and proceeded to install Formula 1 application with both jad and jar in same folder. This time it went without hitch.

Named Pipes in WCF

One of new things in .NET 3.5 was support for pipes (both named and anonymous). Since in some of my applications I used P/Interop for that exact purpose, it seemed quite logical to upgrade that code into native solution. As I started changing code I also started to hate that implementation.

Although new classes are quite easy to use, troubles start as soon as you start transferring little bigger amounts of data (more that cca 200 bytes). I spent better part of night troubleshooting problems with messages broken into multiple parts although buffer sizes were more than adequate and Message transmission was used.

Everything was worsened by design decision to kill off two things that make life easier when playing with those streams. First thing that I needed was ability to check whether there is more data before I start to read it (PeekNamedPipe). This comes in quite handy to dimension your buffers and generally detect when data stream is dry. I needed this function quite a lot because they also decided to kill timeouts for Read() function. Once you start reading data, there is no stopping. And since there is no way to know whether there is more data awaiting other than actually reading it I had quite a big problem at my hand.

I was on verge or restoring old P/Inteop code when I had revelation. Old project was based on .NET 2.0 and with this upgrade I will move it to 3.5 anyhow - why wouldn’t I use Windows Communication Foundation. I played with it before with great success but here I wanted to see how simple it can be and main goal was just to integrate it in already existing flow.

Old application used notion of sending actions to other party and just giving responses to user and that simplified what I needed to do drastically.

Main thing to do is specifying how your communication interface will look like:

[ServiceContract(Namespace = "http://example.com/Command")]
interface ICommandService {

    [OperationContract]
    string SendCommand(string action, string data);

}

This code I needed in both server and client part of my code. Beautiful thing is that it is quite enough to have this file in both places and there is no need for separate assembly to hold common definitions.

Only thing left to be done in client was creating proxy to actually call that method. I opted for separate class, but I could be as easy written in any other existing class:

class CommandClient {

    private static readonly Uri ServiceUri = new Uri("net.pipe://localhost/Pipe");
    private static readonly string PipeName = "Command";
    private static readonly EndpointAddress ServiceAddress = new EndpointAddress(string.Format(CultureInfo.InvariantCulture, "{0}/{1}", ServiceUri.OriginalString, PipeName));
    private static readonly ICommandService ServiceProxy = ChannelFactory<ICommandService>.CreateChannel(new NetNamedPipeBinding(), ServiceAddress);

    public static string Send(string action, string data) {
        return ServiceProxy.SendCommand(action, data);
    }
}

Server part was little bit more complicated but not significantly so:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class CommandService : ICommandService {
    public string SendCommand(string action, string data) {
        //handling incoming requests
    }
}
static class CommandServer {

    private static readonly Uri ServiceUri = new Uri("net.pipe://localhost/Pipe");
    private static readonly string PipeName = "Command";

    private static CommandService _service = new CommandService();
    private static ServiceHost _host = null;

    public static void Start() {
        _host = new ServiceHost(_service, ServiceUri);
        _host.AddServiceEndpoint(typeof(ICommandService), new NetNamedPipeBinding(), PipeName);
        _host.Open();
    }

    public static void Stop() {
        if ((_host != null) && (_host.State != CommunicationState.Closed)) {
            _host.Close();
            _host = null;
        }
    }
}

Once server application starts just call CommandServer.Start() and all requests from client side will be auto-magically instantiated in CommandService. Whatever you decide to return from that method arrives directly to client. It cannot be simpler than that.

I created small example but do notice that it is a console application and no multi-threading issues are being addressed here. Since WCF is working on separate thread any conversion into Windows application will most probably require playing with delegates and that is subject for some other story.

P.S. Do not forget to add reference to System.ServiceModel assembly.