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

Flicker-free Paint on Windows Mobile

On our desktop systems answer to flickering in Paint event was to use double buffering. .NET Framework supports it out of box and if you do not like built-in solution, there is quite a few solutions out there. Most of them use SetStyle method in order to inform Form that custom draw will be performed.

If you try that in Windows Mobile, you have a problem. Not only that there is no SetStyle, but you must remember that your application needs to work when rotated (all mobiles with keyboard need rotation too).

Solution is to create your own double-buffered class. Whole idea is rather simple, create bitmap with size of control (client area only) and draw everything to it. Once you have drawn everything you need, paint this bitmap over your control. Since this will be done in single operation, no blinking will occur. Be sure to override PaintBackground method also. If you forget that, you will still have flicker since painting will be done in two passes. First pass will be erasing background - usually in white, and second pass is drawing your buffer. Such sudden changes between white and non white tend to be noticeable.

Here is sample code that I usually use.

Creating Self-signed Certificate

There are lot of providers of code signing certificates out there. But they all share same problem - they are not cheap. Certificate will cost you in range of 400 € (that is per year). Why pay that money when we can make our own free self-signed certificate? Yes, Windows will not recognize it as trusted, but it still can be used for file integrity purposes.

Illustration

In order for this to work, prerequisite is having Microsoft Windows SDK installed (here is Windows Vista and Windows 7 link). All our work will be done in “C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin” (for Windows 7 or something similar for Vista).

First we need to create certificate with private key:

makecert.exe -pe -n "CN=Example;E=example@example.com" -sv example.pvk -a sha1 -r -eku 1.3.6.1.5.5.7.3.3 example.cer
Succeeded

Window will pop-up and ask for password. You can leave it empty - we can delete private key after we finish. Notice that we are creating code signing only certificate here (-eku 1.3.6.1.5.5.7.3.3). If you wish certificate for all purposes, just omit that argument. Notice that CN and E parameters are ones that you would want to change.

Since with certificate alone we cannot do anything, we need to go through hoops in order to get pfx (PKCS #12) file:

cert2spc.exe example.cer example.spc
Succeeded
pvk2pfx.exe -pvk example.pvk -spc example.spc -pfx example.pfx

Illustration

PFX file can be imported. Just double-click it to get to Certificate import wizard and continue clicking until it is done.

This whole game caused our certificate to get imported to current user’s personal certification store. We can now safely delete all intermediate files (four of them: .pvk .cer .spc .pfx) since everything we need is in our user account. Smart idea would be to make backup of example.pfx before deleting (e.g. just in case Windows need reinstall) or we can just export it from certificate store at later time.

Code signing itself is lot easier. Just one command is needed:

signtool.exe sign /s "My" /n "Example" /v "test.exe"
The following certificate was selected:
Issued to: Example
Issued by: Example
Expires:   1.1.2040. 0:59:59
SHA1 hash: 740F9468A344BF7BB4DC338C2870BD73BB8797C3
Attempting to sign: test.exe
Successfully signed: test.exe
Number of files successfully Signed: 1
Number of warnings: 0
Number of errors: 0

Take care that this “Example” is same one you used after CN= (a.k.a. common name) in first command.

There it is, you have signed your executable.

Why Should I Sign My Code

I see lot of developers failing to sign their code. Here I want to go through some benefits of that simple procedure.

Integrity check

Once you sign your code, every time you run it you get free integrity check. If you sign code at your end, you can be sure that your customer received same version. Although this will not safeguard you against somebody who wants to change code on purpose (he will just remove signature), it will guard you against accidental errors. Sometimes it will prolong loading time of an assembly, but it is usually worth the effort.

Illustration

Nicer prompts

If you sign your code, it will give much nicer prompts whenever security is involved (e.g. UAC). Notice that for this to work, you cannot use self-signed certificate. You need certificate from one that Windows trusts (e.g. VeriSign). Since those certificates are not cheap (few hundred dollars per year), you can omit it if you are creating small applications or applications that will be used by small number of people. If you distribute your application to large number of people, it would be easier to buy it - that way you will avoid e-mails asking you whether it is safe to install your software.

Easier administration

In one step you can allow (or disallow) all applications from single publisher. I personally used this a lot in order to allow execution of .NET applications over local share. Since .NET Framework 3.5 came out, there is no longer need for this particular case, but some other case may apply to you.

Creating drivers

If you need to write driver, you must sign it. Although it will work without signing on 32-bit Windows, 64-bit version requires trusted signature in order to load it. There are some workarounds, but your customer will not be happy.

Keeping Backlight on

Some applications for mobile phone need to be seen. One example that immediately comes to mind is Google Maps. What is use of maps if your mobile fades away after less than a minute of inactivity. It may prove to be rather distracting to press a button or two every ten seconds while driving.

Fortunately there is a way of changing this behavior. But take great care. Backlight is turned off for a reason. Having it on all the time isn’t kind to battery.

Whole secret lies inside of SetPowerRequirement function. This function, when called, switches selected device to one of D states with D0 being full power and D4 being full sleep. Since this change is made on system level, be sure to call ReleasePowerRequirement as soon as you are done. If you fail to call that function (e.g. your program crashes), there is no way to return it to lower power state other than rebooting your machine. Notice also that if your program specifies that D3 is needed and other program specifies D0, device will go in D0 mode - when conflicting modes are selected, higher power always wins.

In example we will just set backlight, but this function can be used for other devices too (first check their name in registry at HKLM\Drivers\Active with MobiReg).

Here is code sample in C#.

How Big Is Int

When I started programming, I was told that C++ integer (int) is always as wide as processor. On 16-bit processors it was two bytes, on 32-bit processors it was four bytes. Reason was optimization. This was very simplified view since C++ only said short <= int <= long. However, it was true enough.

Currently there is not one but few 64-bit data models in use. You as developer do not have say on which model to use. Choice is made once you decide on which operating system your application is to be executed. If you use Windows you will use LLP64 data model (16-bit short, 32-bit int, 32-bit long, 64-bit pointer). With Linux as platform of your choice LP64 is used (16-bit short, 32-bit int, 64-bit long, 64-bit pointer). Difference is small, but it can make life difficult if you develop for multiple platforms.

Fortunately in most of modern managed environments (e.g. .NET, Java…) data type size is fixed. I find this much better.

Intercepting Backspace on Windows Mobile

Illustration

Plenty of applications inside mobile windows make use of backspace key. Just imagine how difficult and unintuitive would be to create even simplest folder browser if you could not use that key. However, on smartphone you have just that situation.

Smartphone (or Windows Mobile Standard) is specific in sense that backspace is used as system-wide key for application switching. You can think of it as Tab in normal applications. It is not something you usually override but sometimes overriding that key can prove to be useful. In our desktop application we would just override ProcessCmdKey function or in worse scenario (older frameworks), just override WndProc. This would allow us to intercept those special keys and use them for our own evil purpose.

However, if we try to do this for Smart Device project we have a big problem. Neither of those two functions is supported. Reason is simple - compact framework is trimmed as far as they could go. In my opinion they took it too far.

Those who worked in times before .NET framework, may remember SetWindowLong function and that one of parameters enabled developer to set their own window procedure (GWL_WNDPROC). Fortunately, that is supported (as interop call).

In order to simplify development, I tried to keep it as familiar as possible. Whole idea is to create base form with required WndProc function and later just inherit from it. Whole procedure can be seen from sample, so I will only cover base steps.

Each form that needs to intercept backspace will also need to inherit from WndProcForm. Since WndProcForm inherits from Form, you can safely change that in already existing applications and they should retain their functionality (do not forget to recompile application once you do that - otherwise designer may complain until you can do so). Designer will complain that there visual inheritance is no longer supported for that form (P/Interop is reason) but you may safely ignore that if you don’t have visual components on multiple forms.

After that, simple matter of overriding WndProc and waiting first for WM_HOTKEY and then for both MOD_KEYUP (key is depressed) and VK_TBACK (same code as for escape) will do the job.

Notice that while I only give instructions on one usage, you may use this to intercept any window message going to your window. And that is lot of messages. This is also applicable to Windows Mobile Professional (Pocket PC) for those extended cases (although backspace is not used as switch key there).

Resources

How Many Bits Are in AnyCPU

Illustration

There is one decision that every .NET developer needs to face - which target platform should I use?

From my experience most developers leave it on AnyCPU. This usually works just fine (at least on their machine ;)) but understanding option could make all the difference.

x86

This is our 32-bit processor. If we run it on 32-bit OS, it is 32-bit application. If we run it on 64-bit processor, it still runs as 32-bit application (WOW64 takes care of that). It’s whole world fits inside of 32 bits no matter what underlying platform is capable of. I would dare to say that this world may be your wisest choice if you need to play with old technology.

x64

This is what we call 64-bit processor these days. AMD calls it “AMD64”, Intel thinks of it as “Intel 64”, but essentially, it is same architecture. It doesn’t run on 32-bit processor or 32-bit OS. Everything needs to be 64 bits in order to fit. It will not work faster, it will consume more memory, but it is our future. This big boy doesn’t play well with his 32-bit friends.

Itanium

Someone at Intel had a thought: let’s have pure and modern 64-bit design without any compatibility worries. Let’s make it work as fast and effectively as possible. IA64 architecture was born. Unfortunately, it was born in wrong age. 32-bit applications had ruled the world back then and this processor was very slow in x86 compatibility mode. This one is lone wolf - doesn’t play well with neither x86 or x64 programs.

AnyCPU

Illustration

This is chameleon of all targets. If you run it on 32-bit system, it will work as x86. If you run it on x64, you get program that looks like it was compiled for it. Itanium looks native to it also. But (there is always a but), it’s process has same limitations of platform it is pretending to be.

This is done through miracles of IL which emits instructions for whatever underlying architecture really is.

There is also a small price to pay. If you, as a programmer, work on 32-bit system, all your calls to non-.NET world (e.g. Win32 API) are done in 32-bits. However, if you run your program on 64-bit system, all your pointers get 64-bit treatment. For those not watching carefully (e.g. using integer where pointer is needed), world may end up collapsing.

This problem is more visible in VB.NET than C# because of code reuse (and they told you that is a good thing). Lot of VB.NET programmers have background in VB 6 and there is lot of API code written for it. Problem was that there were no pointers there. People used Longs instead of pointer - both of them were 32 bit numbers. Everything worked. Then VB.NET came and long became integer, and everything still worked. At least in 32-bit world. When executed as 64-bit process (either target was x64 or AnyCPU) problem occurred since there was four bytes per pointer missing. Those bugs can be sometimes very hard to catch.

Which one to use

I use AnyCPU unless I need to work with some component that has no 64-bit version. I know that 64-bit processes use more memory (all pointers are double in size) and there is no real speed benefit, but if customer opted to have 64-bit OS, he had some reason for it.

I see no point in overriding his choice and avoiding future. I view it as 16-bit to 32-bit transfer. Not all programs needed it, but it was inevitable. Just do it in 64 bits.

What to Do With Exception

No matter how good your programming is, there will be bugs. Once exception is thrown (hopefully your have centralized exception handling) you need to do something with it. Here is what I found that works best for me.

1. Trace it. In cases where other steps fail, this will at least give you basic information although you will need to use some tool like DebugView in order to see it. Think of it like fail-safe mechanism.

2. Write report to file. I just create file named ErrorReport.something.txt in temporary folder. Here I collect all information that is available to me. Time, message, stack trace, whatever you can think of. This same report will be used in next step so it is not waste of time.

3. Show message to user. Don’t go into details, just be nice and apologetic.

4. Send collected information. Be sure that user knows what you will do. They will not take kindly if their firewall detects data going out and they haven’t authorized it. If sending is successful, you may delete report file from step 2.

5. Exit application. Be sure to use exit code different than zero for this. Console guys can get dangerous if you don’t.

SQL Server Recovery Models

Illustration

There are three recovery models in SQL Server 2008 (and previous ones). Each of them has its purpose. Before we describe models, lets shortly describe how SQL Server deals with incoming data:

When data change is about to occur, data is first written to transaction log. Once transaction is completed, all changes are written to data file (not necessary on a hard drive at this point) and that transaction is marked as committed. At one point in time or another, data is really written to disk and transaction is then marked as “really done”.

Full

Until you perform backup, all that transaction log stuff is kept around. Only once you make a backup, transaction log is overwritten. This gives you possibility of data recovery at any time (in-between any transaction). Cost is size of transaction log (space is only reclaimed after backup) and need to backup transaction log in order to be able to recover from disaster.

Simple

Once data is really written to hard drive, transaction log is freed to be reused. This keeps transaction log quite small (compared to full recovery model). Bad thing is that recovery is possible only at backup times (not at any point in time) and there is no incremental backup. This can bite you in the ass if you have huge database.

Bulk-logged

As always, there is need for compromise. This one gives you small log of simple recovery model and incremental backups of full recovery model. However, you get semi-large transaction log and you will not be able to recovery at any point in time.

Which one?

I tend to use simple recovery model. It “steels” just a small amount of your disk space for transaction log and gives perfectly good solution for humble developer.

But, if you have big database, full recovery will ease burden on your server.

You make the choice.

Detecting 64-Bit Environment

Let start by saying that in .NET there is strict definition of Integer’s size. It is always four bytes. You can run program on 64-bit system and you will still have only 32 bits in Integer. I do like it. No matter which system I run it on, it’s range does not change.

Real way to see whether you have 64-bit environment (64-bit framework on 64-bit OS on 64-bit hardware) is to check type whose size does change. That is IntPtr (a.k.a. integer pointer). Although people usually think of integer pointer as something based on Integer, there is slight difference. IntPtr has size of environment’s pointer. On 32-bit system it will be same length as Integer, but in 64-bit environment IntPtr grows to 64 bits.

Notice that if your program is executing on 64-bit system, but someone set it’s target CPU to x86, this detection will say it is 32-bit (since 32-bit framework is used). Idea behind it is that if you are running in 32-bit, there is no need for you to know whether system is capable of 64-bit. You cannot call that 64-bit code anyhow.

Here is small C# example.