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

Async and Await

On Microsoft’s PDC Anders Hejlsberg gave a talk about two new keywords in C# - async and await.

I will not get into them to much - those interested in more can start with taking a look at actual presentation. In essence, they give you new way of dealing with asynchronous tasks. You just point to system where asynchronous operation might occur and C# (or VB.NET) compiler will build all background code that it needs to handle this gracefully. For me it does same revolutionary thing as yield did for enumeration. Seeing this, I got pissed at Java.

Part of my time I spend as Java developer. And I get pissed at it all the time. Whether it is half-assed implementation of generics, absence of in-language support for yield, and in a year-or-so, I will extend this to absence of async and await.

True Java believer would say that all those things are just syntactic sugar - there is nothing magic in them that could not be written by hand. I consider this irrelevant. It is not point whether something can be written, to me most important is point how easily. If I use e.g. yield, there is almost no chance I will mess it up in three lines it takes to do it. When I write code for it in Java, this expands to few tenths of lines needed for state machine. Error chance and debugging time increases exponentially.

I value Java a lot. It is beautiful language at it’s core and it gave huge boost to development of all managed languages. However, it seems as Latin language to me. Nice and beautiful but there is just no significant development of it’s syntax. It takes more and more effort for me to switch between new modern languages (where I would include C#) and Java. I always find something missing…

P.S. Yes, this post is full of exaggeration, but I do not consider it too much off mark.

Infinity Is Not an Exception

From time to time I find some behavior that I cannot really neither explain as correct nor as incorrect. Best description would be peculiar.

Let’s take simple code:

static void Main() {
    int x = (int)double.PositiveInfinity;
    Debug.WriteLine(x);
}

This will cause compile error “Constant value ‘1.#INF’ cannot be converted to a ‘int’ (use ‘unchecked’ syntax to override)” and personally I view this as correct behavior.

Let’s complicate things a little:

static void Main() {
    double posinf = double.PositiveInfinity;
    double neginf = double.NegativeInfinity;
    int x = (int)posinf;
    int y = (int)neginf;
    Debug.WriteLine(x);
    Debug.WriteLine(y);
}

Here I expected one nice runtime exception. However, I was greeted with -2147483648 as a result for both positive and negative infinity. This I did not expect.

My personal opinion here is that this operation should throw exception. I cannot see any sound reasoning for converting infinity to any finite number. It is called infinity for a reason!

However, I do notice that most of languages choose to have this conversion pass. Unfortunately for C# they (e.g. Java) opted for slightly different behavior.

Java converts negative infinity in same manner C# does but positive infinity gets converted to 2147483647. This may not seem like much, but this at least enables positive infinity to be larger than zero which seems mathematically sound to me (if we ignore all that infinity thing :)).

My personal opinion here is that exception should be thrown. Only thing that this conversion can lead to is data corruption - and this is not a good thing.

P.S. I reported this as an issue to Microsoft. I am really interested how they view this situation.

[2010-12-30: I got answer. It is by design.]

LogCat Does Not Show Log Messages

LogCat is quite good thing to look at when program goes haywire since it usually shows both system and developer’s own log messages.

If you are trying to debug your Android program inside of Eclipse and you cannot see your custom log message, fixing it might be as simple as going to DDMS perspective and selecting your current device (whether real or simulated).

LogCat window displays only messages from device in focus and that might not be device you are currently debugging.

Visual Studio 2010 Patches

I consider Visual Studio 2010 an improvement to Visual Studio 2008. However, it had few annoying issues.

One was making find box wider and wider and that was solved few weeks ago via patch.

Another one was need to scroll context menu although there was enough place on screen. Finally patch for that issue is here. For this patch to work properly you also need another WPF patch.

This is quite a collection of patches - 1, 2 and 3. Once these are installed Visual Studio 2010 suddenly becomes even better environment.

How to Gently Kill a Thread

Creating your own thread is not something that I do lightly. There are so many alternatives these days where framework does “dirty job” for you.

However, sometime making your own thread is way to go. I found that mostly I use same code in order to cancel it.

Idea is creating ManualResetEvent that we can check fairly quick from thread loop. Once that event switches it’s value to true, our thread should terminate.

private ManualResetEvent _cancelEvent;
private Thread _thread;

public void Start() {
    _cancelEvent = new ManualResetEvent(false);
    _thread = new Thread(Run);
    _thread.IsBackground = true;
    _thread.Name = "EntranceBarrier";
    _thread.Priority = ThreadPriority.AboveNormal;
    _thread.Start();
}

public void Stop() {
    _cancelEvent.Set();
    while (_thread.IsAlive) { Thread.Sleep(10); } //wait until it is really stopped
}

bool IsCanceled {
    get { return _cancelEvent.WaitOne(0, false); }
}

void Run() {
    while (!IsCanceled) {
        //some code
        if (this.IsCanceled) { return; }
        //some code
    }
}

P.S. This will terminate thread gently and it only works if event is checked often. If you have code that is waiting for system event, this is not solution for you.

GPS Should Stop

One error that creeps quite often in Android applications is not handling being in background gracefully. It is error that is really easy to make since your application works as it normally would. However, it does use more resources than it is needed and resources usually map to battery life.

One example of bad behavior that comes to mind is updating location non-stop. Most often application needs to update their location only when user is looking at it. Once application is in background GPS should be turned off (although there are some application that have good reason to leave it going).

Easiest way to do it is just handling all GPS “subscriptions” in onResume and onPause methods. Those methods get called each time application comes to foreground (onResume) or leaves it (onPause).

Generic solution would look something like this:

private LocationManager thisLocationManager;

@Override
public void onCreate(Bundle savedInstanceState) {
   ...
   thisLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}

@Override
protected void onResume() {
    thisLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);
    super.onResume();
}

@Override
protected void onPause() {
    thisLocationManager.removeUpdates(gpsLocationListener);
    super.onPause();
}

private LocationListener gpsLocationListener = new LocationListener() {
   ...
};

P.S. Do note that this code is not optimal in any way (e.g. hard-coding “gps” as provider name). Intention is just to illustrate concept.

Getting GUID Value After SQL Insert

Whoever used identity columns in SQL Server probably used SCOPE_IDENTITY in order to retrieve newest identity value after insert.

For example, if we have two columns, one named Id and declared as identity column and other named Test with text inside, we would use something like this in order to insert new row:

INSERT INTO Example(Test) VALUES('test'); SELECT SCOPE_IDENTITY();

Once we use ExecuteScalar, we would get newly inserted identity value (in column Id).

Once we enter world of Guids, we cannot do that. Guid is not considered identity value and same rules do not apply to it. In order to have similar example we shall have also two columns here. However, this time Id column will be of uniqueidentifier type and it will have it’s default set to NEWID(). This way client behavior is same. Once we insert new row (without specifying Id value) we will get Id assigned to us.

In order to retrieve value for Id column, we need to change SQL a little:

INSERT INTO Example(Test) OUTPUT INSERTED.Id VALUES('test');

Visual Basic and Windows Phone 7

One thing that C# could do and Visual Basic could not was development for Windows Phone 7. I will not get too much into whether this is even an issue, but I will notice that it is no longer true.

Visual Basic developers can now download Microsoft Visual Basic CTP for Windows® Phone Developer Tools.

CTP stands for Community Technical Preview and it is closest to something in alpha stage. It will not be usable for production environment and it will take a while for final version to come. However, it is a big step forward.

Extracting Part of Mercurial Repository

As I started to work with Mercurial, I added almost everything in single repository. Time passed and I wanted to move some data to separate one. And this became a problem. There is no obvious way to split repository. However, there is something almost as good - exporting it.

Since I am Windows user, I will give instructions for Windows here. All things should work on Linux also but configuring it to work properly might (and will) differ. I will also assume that you have Mercurial already installed. I tested this with TortoiseHg but other clients should work also.

First step is to enable ConvertExtension on our computer. Just editing “mercurial.ini” under home folder and adding two lines will do:

[extensions]
convert =

If there is “[extensions]” sections inside already, just add “convert =” under it instead of creating new one. Home folder on Windows Vista and 7 is probably located at “C:\Users\YourName”. XP users should look under “C:\Documents and settings\YourName”. If you moved it somewhere else, search for it yourself. :)

Another file that we need to prepare is one used for filtering out things we do not need. Lets store it at “C:\map.txt” and add following text to it:

include "Electronics/Elsidi"
rename "Electronics/Elsidi" "."

Text in quotes is location of directory in original repository. First line includes only files at directory we wish to extract and second one moves those files to root directory (.) of new repository. Do notice that we use paths relative to root of repository and that path IS case sensitive.

I will assume here that “hg.exe” is somewhere in path so you can execute it without problem. In other cases, just write full path to it every time I write “hg”. In my case this is “C:\Program Files (x86)\TortoiseHg\hg”.

Last thing to do is executing conversion itself and update of new repository afterward:

hg convert C:\OriginalRepository C:\NewRepository C:\revmap.txt --filemap C:\map.txt
scanning source...
sorting...
converting...
18 Adding initial Android applications.
17 Initial push.
16 Elsidi rev3.
15 Moving Elsidi directories.
14 Elsidi rev6
13 Elsidi rev G.
12 Power (rev B).
11 Last version of UTF8.
10 Added As.
9 Adding Encoded.
8 Adding World.
7 Adding Unicode.
6 Adding In.
5 Adding Joint.
4 Adding Smokes.
3 Adding Device.
2 Adding Android.
1 Added Test.
0 Adding QText

cd C:\NewRepository

hg update
31 files updated, 0 files merged, 0 files removed, 0 files unresolved

With this you should have your new repository ready. Only files under desired path will be there (moved to root) and all history will be preserved.

Revmap.txt is here just so you can continue interrupted process. If you want to start whole process from start just delete both it (revmap.txt) and new repository’s directory (C:\NewRepository).

Hope this works for you.

P.S. If you see “C:\NewRepository” with just “.hg” folder inside and nothing else, you probably forgot to execute “hg update” command.

P.P.S. This procedure will leave exported data in original repository. You might remove it yourself but do notice that you will not recover any disk space - nothing is really deleted with Mercurial.

NEWID Vs NEWSEQUENTIALID

When GUIDs got introduced, people started using them as primary keys (which is ok) and, because of default, most of those GUIDs ended up as clustered index.

Clustered index itself tries to keep values that are close to each other in binary form also close in physical order. This is fine for data that is usually just increasing (like integer identity column) but it is not as good when you have random data. Unfortunately GUIDs (as created with NewId function) are closer to random than to any other order.

NewSequentialId function was introduced to solve this exact problem. It will return values in increasing order but with small catch - it is guarantied only until you restart Windows. Once you reboot Windows starting value might be lower than last one inserted.

Shit really hits the fan if you need to combine date from more than one server. Each one will generate completely different set of increasing GUIDs. This will wreak havoc for your clustered index. Fragmentation, here we come.

And what is result of this “fight”? Should one use NewId or NewSequentialId function?

It simply does not matter. Once you remove clustered index issue from decision process, either function works fine. And I cannot say that I see any scenario where clustered index on GUID is appropriate.

Am I missing something?

P.S. Personally, I would go for NewId - it is shorter to write and it is more user-friendly.