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

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.

POSIX Time

If you are working with Unix a lot, you get to be aware of weird time-stamps. That markup is usually called Unix time (although POSIX time is more precise term) and it represents number of seconds from January 1st 1970 (in UTC).

I was handling some timing issues in log and I needed to convert between local and Unix time. Since I got quite annoyed during day, at night I created small utility to handle this simple task.

Both application and full code is available.

Toolstrip and Case of Extra Line

Illustration

I needed up/down buttons for one program of mine and I decided to have them on ToolStrip control.

As soon as I figured how to make it vertical, I stumbled upon shade issues. In default RenderMode (ManagerRenderMode) background is just little bit of different background color. Usually this does not matter since ToolStrip is docked on form but in this situation it was quite visible. Solution was simple - switch RenderMode to System and control blends in perfectly.

However, using System render mode has one downfall. There is small light 3D line on bottom of control. Although it is not visible too much, it was enough to bother me.

Since System rendering is done via ToolStripSystemRenderer class, first idea was to extend it. And there it was - OnRenderToolStripBorder. It is enough to override this method and border is never created:

class ToolStripBorderlessSystemRenderer : ToolStripSystemRenderer {

    protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
        //base.OnRenderToolStripBorder(e);
    }

}
[/sourcecode]


Only thing left is to actually telling ToolStrip to use our class for rendering:
```csharp
SettingsForm() {
    InitializeComponent();
    toolstripVhdOrder.Renderer = new ToolStripBorderlessSystemRenderer();
}

Order of Activation

In one of my programs I fixed a bug. I just forgot to restore TopMost state of form. Fix was very simple, just set this.TopMost = true in form’s constructor and everything is solved.

Like every simple fix, this one failed miserably. As soon as I “fixed it” I could not even start program. Even worse thing is that it failed where there was no error before. It didn’t take much to deduce that this change was somehow responsible for triggering error in completely different part of code. It looked like just fact that I have TopMost turned on changes how rest of program is loaded.

I tested program without setting TopMost and order of triggering form’s events was quite expected - first constructor, then Form_Load, then Form_Activated and Form_Shown. However, things do change when you set TopMost property.

It is a subtle change - contructor is still first one to complete, next one is Form_Activated, then Form_Load and Form_Shown is last once more.

If you have code in both Form_Load and Form_Activated you have a minefield in your code. Everything works as expected until you step on mine. In my case mine was TopMost property, but it is not only one that behaves like this.

Solution was dead simple - just move TopMost from constructor to Form_Load and everything works perfectly.

Sample for your testing can be found here.

Case for SysUInt

I was cleaning up one of my old programs and I got interesting warnings from code analysis:

CA1901 : Microsoft.Portability : As it is declared in your code, the return type of P/Invoke 'RichTextBoxEx.NativeMethods.SendMessage(IntPtr, Integer, Integer, Integer)' will be 4 bytes wide on 64-bit platforms. This is not correct, as the actual native declaration of this API indicates it should be 8 bytes wide on 64-bit platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of 'Integer'.
CA1901 : Microsoft.Portability : As it is declared in your code, parameter 'wParam' of P/Invoke 'RichTextBoxEx.NativeMethods.SendMessage(IntPtr, Integer, Integer, Integer)' will be 4 bytes wide on 64-bit platforms. This is not correct, as the actual native declaration of this API indicates it should be 8 bytes wide on 64-bit platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of 'Integer'.

I checked other code where I used that function and I noticed that I used IntPtr there. However, although this was technically correct, it didn’t sound right. SendMessage has many purposes and here I was using it to set tab stops. While I could wrap number in IntPtr and pass it like that, I wanted another solution. Solution that will allow me to use number and still have IntPtr-like behavior.

Of course, as usual in .Net P/Interop, solution seemed quite simple. Use whatever data type you wish and just set correct marshaling. I used signature that P/Invoke Interop Assistant generated:

Of course, as usual in .Net P/Interop, solution seemed quite simple. Use whatever data type you wish and just set correct marshaling. I used signature that P/Invoke Interop Assistant generated:

<DllImport("user32.dll", EntryPoint:="SendMessageW")> _
Public Shared Function SendMessageW(<InAttribute()> ByVal hWnd As IntPtr, ByVal Msg As UInteger, <MarshalAs(UnmanagedType.SysUInt)> ByVal wParam As UInteger, <MarshalAs(UnmanagedType.SysInt)> ByVal lParam As Integer) As <MarshalAs(UnmanagedType.SysInt)> Integer
End Function

On next run program greeted me with “Cannot marshal ‘parameter #3’: Invalid managed/unmanaged type combination (Int32/UInt32 must be paired with I4, U4, or Error).”. No matter what I did, it would not budge. It seems that this tool disappointed me once again.

To keep long story short, this is final function I decided to use:

<DllImport("user32.dll", EntryPoint:="SendMessageW", CharSet:=CharSet.Unicode)> _
Friend Shared Function SendMessageW(ByVal hwnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByRef lParam As IntPtr) As IntPtr
End Function

Since my code still needed to pass integers I made wrapper to sort that out:

Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
    Return SendMessageW(hWnd, Msg, New IntPtr(wParam), New IntPtr(lParam))
End Function

With that my work was done.

P.S. Yes, you are not mistaken, code is in VB.NET. It is program I wrote a while back and I have no intention to rewrite it in C# just to get single bug fixed.

P.P.S. I find it interesting that LRESULT is really IntPtr although name does not suggest so (at least not to me). HRESULT on other hand is not IntPtr although from name I would deduce it is handle (and thus IntPtr).

InternalsVisibleTo

InternalsVisibleTo is interesting attribute. It will make all it’s internal (or friend) fields open to the special one. In this case “special one” is another assembly.

Let’s try to elaborate this with example. Assembly A.exe has reference to B.dll. A.exe can see all public fields and nothing more. However, if designer of B.dll adds InternalsVisibleTo attribute, A.exe will be able to see his fields marked with internal also.

One can argue that this violates “black box” principle and I would agree. This attribute is not to be used regularly. I can think only two reasons why you should use this.

First one is component test. If you “befriend” your test assembly (A.exe) and B.dll this means that testing of target assembly is not limited to public interface. You suddenly have power to test internal workings.

Another usage is for those solutions that have multiple projects in different language. Sometimes you just have components already available in one language (e.g. C#) while main project is in another (e.g. VB.NET). Instead of rewriting everything, simple make new assembly and have all it’s content internal with InternalsVisibleTo exception for main project.

For this case benefits are doubtful since you might as well make those classes public and everything will work as it should. However, I like to make it internal in order to prevent others accessing it. If you just leave public assemblies laying around chances are that someone will use it.

That may be new guy on project that doesn’t know history of that class and he will just see opportunity to hook into already existing interface. He will not know that this was not intended to be public interface and that it wasn’t tested as such and probability is high that something will break.

While public assemblies hopefully get interface testing that they deserve, original idea of this assembly was to be glue between languages. It may be that everything works great while it has benefit of all calls being made from main project but, once you directly access it, you will stumble on quite a lot of problems and border case error that weren’t issue before. And if you ship it, you get to support public interface that was never designed as such.

If you still want to use this attribute after all this warnings, just add it in AssemblyInfo.cs (or your own favorite place):

[assembly: InternalsVisibleTo("A, PublicKey=00240000048000009400000006020000002400005253413100040000010001002de64bdf2fb7ba60913800e843fe50288f7c1467051bb0a70eca140d1e3900530a51931ead28a80d50c7b4bd7a6ec868f601dee366fef644d129a43d6eb8090c1fd097d4e13b80b1069eafab518233e0f21e14e89ee73e47486a7faf4ea2a4ad5dd48a80d1477fdd3c1715c8b46e876bbc2c27595914a0c1437d44e656e4c2d3")]

As you can see, attribute will take one argument consisting of two parts separated by comma (,). First is name of your project (in this case “A”) and other is public key of that strong-signed assembly (yes, this attribute will not work on assemblies that are not strong-signed).

In order to get that last piece of puzzle, one can use Microsoft’s Strong Name utility:

sn -Tp .\A.exe

Microsoft (R) .NET Framework Strong Name Utility  Version 3.5.30729.1
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key is
00240000048000009400000006020000002400005253413100040000010001002de64bdf2fb7ba
60913800e843fe50288f7c1467051bb0a70eca140d1e3900530a51931ead28a80d50c7b4bd7a6e
c868f601dee366fef644d129a43d6eb8090c1fd097d4e13b80b1069eafab518233e0f21e14e89e
e73e47486a7faf4ea2a4ad5dd48a80d1477fdd3c1715c8b46e876bbc2c27595914a0c1437d44e6
56e4c2d3

Public key token is b80ce85f4244428f

Of course, to do this you will need to have “C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin” (or whichever directory holds sn.exe on your system) in path.

How to Create Self-installing Service

Creating Windows Service quite often comes as natural choice when some long-term task needs to be done or, god forbid, you need something running while there is nobody to log on. Although services are useful, there are two things that annoy me and they are just too non-obvious to do. One is debugging services and another one is installing them.

For quite a while I’ve been using installutil.exe in order to install services. Since I am fan of being able to put things on system without actually installing them, that meant that I went through hoops to write C# code which will find installutil.exe in all it’s possible locations, under any combination of service packs and then to parse output once it gets executed.

I am not proud that it took me literally years to get idea to open installutil.exe in Reflector. And there, under whole glory, there was single function that does everything. And to make things even better parameters for this function are same as parameters for installutil.exe itself.

In order to install service, it is enough to pass name of executable (executing assembly in this example) and magic will happen:

ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });

Uninstall is same story. Additional “unistall” (or “u”) flag is all it takes:

ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });

Design of whole thing leaves lot to be desired. It just doesn’t feel like .NET - it feels like whole thing was pushed in after somebody noticed that there is no installer and there are only 2 hours before final version of .NET comes out.

One could get into refactoring whole thing out and making “proper” installer without too much effort. However, personally I will not do it. Although this function annoys me, I am also assured that Microsoft takes care of testing it and that it will work on every supported version of .NET Framework on every supported platform. Services are difficult enough without risking installation issues on some obscure combination.

Things that are not (badly) broken should not be fixed.

P.S. Not to forget, you need reference to System.Configuration.Install.dll in your program.

GetLastWin32Error

static void Main(string[] args) {
    if (!NativeMethods.DeleteFileW(@"X:\NonExisting.txt")) {
        throw new Win32Exception(Marshal.GetLastWin32Error().ToString());
    }
}

private static class NativeMethods {
    [DllImportAttribute("Kernel32.dll", EntryPoint = "DeleteFileW", CharSet = CharSet.Unicode)]
    [return: MarshalAsAttribute(UnmanagedType.Bool)]
    public static extern bool DeleteFileW([InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName);
}

This code looks quite straightforward. Function should delete file and in case of failure exception will be raised. In this particular case one would be expect either 2 (ERROR_FILE_NOT_FOUND) or 3 (ERROR_PATH_NOT_FOUND) as raised exception’s text.

However this example will most probably return 0. You can already guess from highlight that problem is in DllImport line. To make function behave properly, one parameter needs to be added:

[DllImportAttribute("Kernel32.dll", EntryPoint = "DeleteFileW", CharSet = CharSet.Unicode, SetLastError = true)]

When SetLastError is set to true, .NET will make all necessary plumbing in order to catch and store error code. This code will be available to you in GetLastWin32Error() function until some other P/Interop call overwrites it.

Although I knew all of that, I fell as a pray to this annoying bug. Reason lies in great tool - PInvoke Interop Assistant. It will generate all necessary P/Interop signatures and it is just too easy to rely on it’s judgement. At least until you find out that all those API signatures are generated without SetLastError parameter set.

If this little issue goes unnoticed, you have quite a big bug on your hands. Worse still, since GetLastWin32Error() will almost always return 0, bug will probably go unnoticed and it will manifest itself somewhere far away from function. Catching that one can be tricky.