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

ClientLogin

Google offers quite rich API for users of their services. Most of it needs some form of authentication. Without much ado here is my C# implementation. Only limitation is lack of captcha support, everything else should be there.

P.S. If you are interested in Google Data API, you might want to check .NET client library. It is open source project and it covers pretty much whole API suite.

NTP Server

Few days ago I stumbled upon problem. I had three Windows 7 computers without Internet access and I needed time synchronization between them. It wasn’t really important that time is correct - it was important that time is same. Solution was simple - just make one of computers NTP server and let others synchronize to it (using standard Windows time synchronization). While Windows 7 synchronizes time perfectly over Internet and/or when you are member of domain, it does not include NTP server.

As I tried to install some other software it became clear that I need to stop and DISABLE “Windows Time” service. NTP servers can only work if they can use UDP port 123. As long as “Windows Time” service is running that port is taken by it. For my scenario this service does nothing so disabling it caused no problems.

As I tried few NTP server solutions I got more and more desperate - either they weren’t free (yes, I am cheap bastard) or they would not work as service under Windows 7. After some time I just decided to make my own program. How hard can it be?

While I consider most of RFCs technical descriptions pure beauty, somebody made a mess of this one. All information was there, how to synchronize, which algorithms to use, probably even genealogy of authors - only thing not there was pure and simple ASCII format of UDP packet. Fortunately authors of SNTP (which is mostly compatible with NTP) did much better work with it. That combined with old pal WireShark made this program possible.

As any program that is written in one afternoon, this one has fair share of things not done. First of all, this program was only tested with Windows XP and Windows 7 as clients. While other versions should work, I spent no time in actually testing it.

This server is also not fully NTP compliant. All fields are there and all clients will consider it valid time source but stratum, precision, root delay and root dispersion numbers are just hard-coded instead of calculated. This should present no trouble in local network and if precision in seconds is satisfactory, but it is definitely not time server you would use if every microsecond is important.

Program requires .NET 2.0 and there is no setup. When you extract it to desired folder first order of day is performing installation from administrator prompt (cmd with Run as Administrator is fine). There we just run program with /install as parameter (“tempora.exe /install”) and service will be installed and started (if you remembered to DISABLE “Windows Time” service first). As long as you don’t uninstall it (“tempora.exe /uninstall”) it will start at each startup and it will return current time to all it’s clients.

Download is here.

P.S. Do not forget to DISABLE “Windows Time” service. ;)

[2015-04-25: Program is available on GitHub]

IsNullOrWhiteSpace

When one deals with user input, it is quite useful to check whether user entered anything. Definition of “anything” is not necessarily same for developer and user.

Quite often user will consider one accidental space to be nothing at all. To implement proper check developer would need something like this:

if (string.IsNullOrEmpty(text) || (text.Trim().Length == 0)) {
    //Text is empty.
} else {
    //Text is not empty.
}

Code is not difficult and it is pretty obvious. Hard part (at least for me) is remembering to add this text.Trim().Length==0 condition. Some time I just forget.

.NET 4.0 brings little bit of syntactic sugar in this area:

if (string.IsNullOrWhiteSpace(text)) {

It is basically same code - just a little bit shorter and, thanks to IntelliSense, much easier to remember.

WebMatrix

Illustration

All those interested in ASP.NET might benefit from newest Microsoft toy. It is called WebMatrix and it is currently available as a beta. It brings to table everything lightweight web development needs: easy syntax (ASP.NET Razor), small database (well known SQL Server Compact Edition) and decent web server (IIS Developer Express). Those interested might as well check video presentation.

For me IIS Developer Express is probably best thing in this package. It is simple web server that does not need ninja to configure it properly. Works with any recent Windows system (yes, even XP is supported) and all that while having almost complete compatibility with full IIS Server. That is quite a feat since all IIS 7 modules are also supported alongside whole IIS 7 extensibility model.

All that and it needs only some space on hard drive and standard user privileges for both running and debugging.

Naming Issues

Illustration

I had to install SQL Server 2008 R2 on Windows Server 2003. As soon as install started, I was greeted with message that Windows Installer 3.1 and .NET Framework 3.5 are missing (yes, it was quite an old installation). Fortunately links were provided and I was ready to continue install.

After checking system requirements, SQL Server had another surprise for me - it needed PowerShell 2.0. Although it was annoying that I haven’t got this error before, I just went to big evil Internet to download it.

To my surprise I could not find direct link to PowerShell 2.0 download. There was a lot of talk about it, quite a few links to PowerShell 1.0 - everything but quick link toward PowerShell 2.0. After restricting search to Microsoft only, problem was found.

For some reason Microsoft decided to pack PowerShell 2.0 with some additional tools and call it a Windows Management Framework update. Following links on that page finally brought me to download containing PowerShell 2.0 (among other things).

We're Off to See the Market

Illustration

In order to put application on Android Market one of most important steps is signing it. There is pretty comprehensive guide available for that in developer documentation. I followed instructions wondering why everything needs to be done in command-line only to discover at the very end that those steps are not needed.

All you need is proper setup of your development environment. Once you have that, creating Market-ready application is just matter of right-clicking on project and selecting “Export Android Application”. From there wizard will guide you through key creation, compilation and all other necessary steps.

Retrieving Application Icon in WPF

As I started doing more and more work in WPF, I had to port my “About” dialog. In attempt to keep everything clean of Windows Forms that also meant that I need to find another way of loading icon (since Bitmap class is not part of WPF).

Code follows same logic as one for Windows Forms. Only important difference is use of ImageSource as our final destination.

var hLibrary = NativeMethods.LoadLibrary(Assembly.GetEntryAssembly().Location);
if (hLibrary != IntPtr.Zero) {
    var hIcon = NativeMethods.LoadIcon(hLibrary, "#32512");
    if (hIcon != IntPtr.Zero) {
        return Imaging.CreateBitmapSourceFromHIcon(hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
    }
}

Without further ado, here is full sample.

The Image Format Is Unrecognized

Illustration

As I started my new WPF application, I got greeted with FileFormatException - “The image format is unrecognized”. I was confused since application was so new that I haven’t added any images to it. After checking and double-checking I found which image exception was referring to - my application icon.

It seemed like normal icon to me. As I compared it to icons that I already used successfully with WPF there was only one difference. This icon had 256x256 size. As soon as I deleted it, my program started working again (ok, it was empty application so making it work was not that big of task).

Side effect of this solution was that I lost my big images. That felt dirty to me so I ended up with two icons in my application. First one was with all images (including 256x256) and I used it as application icon (Properties, Application, Icon). Second one was without 256x256 images and I just set it’s Build Action to “Resource”. Whenever I needed WPF window icon, I just pointed to second one.

I must confess that I am quite annoyed by this. WPF was all about making Windows look and feel better. Using brand new .NET 4 and restricting icons to sizes before Vista just does not seem right. And I better not start about how useful XAML exceptions are…

P.S. If you do not have icon editor available, I would recommend IcoFx. It is good and it is free.

Android Debug Bridge on HTC Desire

Illustration

Debugging Android programs on real device is easy. You just need to follow guide and everything will work. That is theory at least.

All instructions worked just fine up-to point where USB driver had to be installed. Dreadful “Driver not found” was all I was getting. Problem was obvious. My HTC Desire was just too new to be included in driver pack.

However, I had a hunch. “USB Driver for Windows, Revision 3” that was available to me was one that included support for Nexus One. Since Desire seems pretty close to it, I wanted system to use Nexus drivers anyhow.

First thing to do is right-click on My Computer, select Manage and go to Device Management. There you will see ADB device with yellow question mark. Right-click on that device and select properties. Under tab Details there is one combo box with properties. There we need to see “Hardware Ids”.

In case of HTC Desire hardware IDs in question were “USB\VID_0BB4&PID_0C87&REV_0100&MI_01” and “USB\VID_0BB4&PID_0C87&MI_01”. In “android_winusb.inf” file I just copied two entries for Google Nexus (“%SingleAdbInterface%” and “%CompositeAdbInterface%”) and replaced their hardware IDs with hardware IDs for Desire (with slight trimming). Changes are highlighted:

...
;Google NexusOne
%SingleAdbInterface%        = USB_Install, USB\VID_18D1&PID_0D02
%CompositeAdbInterface%     = USB_Install, USB\VID_18D1&PID_0D02&MI_01
%SingleAdbInterface%        = USB_Install, USB\VID_18D1&PID_4E11
%CompositeAdbInterface%     = USB_Install, USB\VID_18D1&PID_4E12&MI_01
;
;HTC Desire
%SingleAdbInterface%        = USB_Install, USB\VID_0BB4&PID_0C87
%CompositeAdbInterface%     = USB_Install, USB\VID_0BB4&PID_0C87&MI_01
[USB_Install]
...

And voilà, we have our driver ready.

P.S. While I talk about HTC Desire here, there is no reason why same method would not work for any other Android phone, providing that it is compatible (on USB communication level) with Nexus.

[2010-06-17: At least in case of Windows 7 and it’s “No driver found” error, it is enough to add only %CompositeAdbInterface%. I haven’t tested on other operating systems but I think that %SingleAdbInterface% is not used at all.]

Get Application's Icon

When I was building “About” dialog for my applications, I wanted it to be as reusable as possible. That meant that all data should be retrieved while program is running. Only thing that I could not discover within .NET code was application’s icon.

Windows API came to rescue. In short we just load our own assembly for purpose of extracting one icon resource. That gives us “good old” pointer which can be used to create bitmap.

IntPtr hLibrary = NativeMethods.LoadLibrary(Assembly.GetEntryAssembly().Location);
if (!hLibrary.Equals(IntPtr.Zero)) {
    IntPtr hIcon = NativeMethods.LoadIcon(hLibrary, "#32512");
    if (!hIcon.Equals(IntPtr.Zero)) {
        Bitmap bitmap = Icon.FromHandle(hIcon).ToBitmap();
        if (bitmap != null) { return bitmap; }
    }
}

Probably most curious thing is “#32512” string. This is resource identifier that goes way back into non-CLR past (also-known-as IDI_APPLICATION constant) and it is not only one that can be used.

Here is full sample.