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

Team Foundation Service

Illustration

Source control is something that every project needs. I do not care whether it is simple Hello World app or next Office. If you don’t have it under source control, you are doing it wrong.

For a while now I have been advocate of Mercurial. Nice distributed source control with acceptable UI under Windows and with lot of options for online storage (BitBucket being most popular choice). And it integrates nicely in Visual Studio (VisualHg plugin).

If your work completely revolves around Visual Studio, there was always option of using Team Foundation Server. It is good centralized source control system deeply integrated into Visual Studio. As a bonus it also offers quite a good deal of bug ticket management and scrum planning. It tries to be one solution for all project needs, and it is rather successful in that.

Downside is infrastructure. Installing Team Foundation Server is not too difficult but it does require separate server, setting up backup plans and at least though about access. This is not too difficult when dealing with local team but if you have someone outside of your network everything gets painful and expensive pretty soon. Not a problem for organization but usually unscalable obstacle for someone setting it up at home.

Things change a bit with new Team Foundation Service. Sales department boost it as “cloud-powered source code management” but developers can really just look at it as Team Foundation Server on Internet. That means that most difficult part of work is done for us. Server is up, somewhere where everybody can reach it and someone else takes care of backup.

Features include centralized source code management model that is really easy to use and almost anything any scrum team would need for managing project. Yes, that includes tasks, backlogs and all that beautiful stuff. Of course, bug management comes out-of-box too. Really no difference to standalone Team Foundation Server.

Thing that I like the most is fact that it is free for up to 5 users without any additional limit on number of projects. That makes it really viable for hobby project done by single person or even really small teams. Paid plans will be announced in 2013. Before that time even huge teams can get some of a free action.

Yes, BitBucket offers same amount of free users and you can get free scrum and bug management systems also. However, Team Foundation Service really shines in level of integration. I am not aware of any other solution that offers all this and that is so easy to setup.

If your development world is rooted in Visual Studio, life can hardly be better.

ListView Iterations

If there is need to iterate through ListView items, I often see following code:

foreach (var item in listView1.Items) {
    var itemX = (ListViewItem)item;
    //do something with itemX
}

Unfortunately C# compiler is not smart enough to notice that item is actually ListViewItem so it keeps it as Object. And thus we need to cast it to our desired type.

Well, actually there is no need to do this. One just needs to remember live before implicit typing with var came:

foreach (ListViewItem item in listView1.Items) {
    //do something with item
}

This still works and it definitely looks nicer.

SQL Access Denied

Illustration

As I did forced reinstall of my development environment I decided to move all my SQL Server databases to virtual disk. It seemed like a good choice, especially since I formatted virtual disk as exFAT. Since I have dual boot that means that I can use same database from both machines without dealing with all that pesky security.

Well, I was wrong. First message that greeted me was dreadful Access Denied. SQL Server would not attach, create or otherwise do anything with anything on that drive.

I’ll skip some debugging and head smacking and present you only with result: In services find SQL Server instance and change Log on as property to Local System account instead default of Network Service. That will allow it access your attached virtual disk.

Security-wise Network Service is much better account for hosting SQL Server. And in production I would definitely go with either it or separate account only for SQL Server. However, having SQL Server running as Local Service is convenient and good enough for development environment.

P.S. Once you attach database, you can switch back to Network Service account. It seems that error appears only on initial attach.

LDAP Authentication From C#

using (var ldap = new LdapConnection(new LdapDirectoryIdentifier(this.HostName))) {
    ldap.SessionOptions.ProtocolVersion = 3;

    ldap.AuthType = AuthType.Anonymous;
    ldap.Bind();
    var dn = GetDn(ldap, userName);

    ldap.AuthType = AuthType.Basic;
    try {
        ldap.Bind(new NetworkCredential(dn, password));
        return GetUser(ldap, dn);
    } catch (LdapException) {
        return null;
    }
}

First step is just simple anonymous bind to retrieve distinguished name based on user name. If our UID is jdoe, we simply search for uid=jdoe in dc=localdomain (base DN) using sub-tree search. That should give us location of our user wherever he is. Let’s assume that user is now found at uid=jdoe,ou=People,dc=localdomain.

Full DN of user is then used together with password to authenticate ldap connection. If authentication fails our user cannot logon. If it works than another ldap search (uid=jdoe,ou=People,dc=localdomain) retrieves attributes, packs them into class and returns it back.

Sweet and simple.

P.S. Code in this post is just an excerpt. You can download full code here.

Pure Laziness

Illustration

Visual Studio 2012 comes with Blend. Even Visual Studio installation is named “Visual Studio 2012 with Blend”.

Therefore I was surprised when I actually started Blend under Windows 7. I got slapped with “… supports only Windows Store app development on Windows 8 …”.

Under assumption that there is some programming API for retrieving actual version of Windows, I cannot think of an excuse other then pure laziness why this item ended up offered as instalaltion option. If you know that your component does not work under certain OS, do not even show it to user. And do not even think about actually installing it.

I understand that Microsoft wants to sweeten deal for early Windows 8 adopters. I find nothing wrong with that. It is actually really sensible thing to do.

But do not install by default stuff that developer cannot use. It will just make him cranky.

P.S. Uninstalling Blend left it’s item and project templates directories behind…

Uri Escaping

Either I need to download a certain page for further processing or I need to just post some data, code for generating url is quite similar. Just take two strings and merge them together. I usually then convert resulting string into Uri because most methods tend to require it, or even if they accept string, they convert it into Uri internally. For example:

var uriString = string.Format("http://www.example.com/{0}/", "ABC");
var uri = new Uri(uriString);
Debug.WriteLine(uriString + "\t" + uri.ToString());
// http://www.example.com/ABC/    http://www.example.com/ABC/

This, of course, does not deal with having special characters. All you need for those is escaping. Fortunately Uri class already has a method for that:

var uriString = string.Format("http://www.example.com/{0}/", Uri.EscapeDataString("A/BC"));
var uri = new Uri(uriString);
Debug.WriteLine(uriString + "\t" + uri.ToString());
// http://www.example.com/A%2FBC/  http://www.example.com/A/BC/

As you can see peculiar thing happened. While our string is escaped, transforming it to Uri actually loses this. Instead of encoded “A%2FBC” as one segment we get separate “A” and “BC”. Querying server with later will not result in expected content.

Solution here is to use double escaping.

var uriString = string.Format("http://www.example.com/{0}/", Uri.EscapeDataString(Uri.EscapeDataString("A/BC")));
var uri = new Uri(uriString);
Debug.WriteLine(uriString + "\t" + uri.ToString());
// http://www.example.com/A%252FBC/    http://www.example.com/A%252FBC/

End result might look ugly but it will get you that page every time.

P.S. Example.com does not contain said directories/files. To see double encoding example, you can check this link toward DigiKey (http://www.digikey.com/product-detail/en/DS2482S-100%252B/DS2482S-100%252B-ND/1197435) or just roll your own.

Is It Dark Yet?

Themes are quite popular thing under Windows and it is very hard to make an application that would look decent regardless of user-selected colors. It is somewhat easier when you can cover all your needs with predefined theme colors. but sometime you just need a few more in order to emphasize an element.

As an example we can take simple highlighting of an error. Changing offending text to dark red works really nice on white background. If user has dark background, dark red text is probably not as visible.

Easiest solution (and I fear most often used one) is to ignore this issue. If user has such stupid theme, it is his problem. Needless to say, this is very rude. If user wants to have black background, user should have it. Lunatics should not be restricted!

Other solution is to find colors for every combination expected in wild. Given customization possibilities this is probably not a path worth taking. However, we can divide all possible theme choices into subsets and work from there.

I usually just fit everything into two color buckets - light and dark. If I detect that background is light, I use one color, while I use another if background is dark. This simple solution works almost always.

Function looks something like this:

bool IsColorDark(Color color) {
    var y = 0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B;
    return (y <= 160);
}

It just calculates luminance of a given color (0-255). All colors with high luminance are considered light and all those with low luminance are dark. Somewhat arbitrary cutoff point value used here is 160. I found that it works quite well for my needs.

To check whether color belongs on dark end of spectrum we just place it in function call:

if (IsColorDark(myColor)) {
    //do something for dark
} else {
    //do something for light
}

ISO 8601 Week

For a program of mine I needed to get week number. Simple, I though, I’ll just use standard function. I knew from past that C# had one. I also knew that it offered me a choice of how to determine first week. I could start counting weeks starting from first day in year, first full week or first week that has four days in it.

Short trip to Wikipedia has shown that ISO 8601 date standard has part that deals with weeks. One of alternative definitions read that it is “the first week with the majority (four or more) of its days in the starting year”. With that sorted out, code was trivial:

private static int GetWeekNumber(DateTime date) {
    var cal = new GregorianCalendar();
    return cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

Nice, clean and wrong. Week numbers for all years that begin on Thursday were incorrect. For example, January 1 2009 is Thursday. According to ISO 8601 that means that this is first week and Monday, December 29 2008 is it’s first day. Result should have been 1 but .NET returned 53 instead. Probably something to do with United States and week starting on Sunday.

In any case, new algorithm was needed. Simplest thing would be to do all steps that a person would do in order to calculate it:

private static int GetWeekNumber(DateTime date) {
    var currNewYear = new DateTime(date.Year, 1, 1);
    var currFirstThursday = currNewYear.AddDays((14 - (int)currNewYear.DayOfWeek - 3) % 7);
    var currFirstMonday = currFirstThursday.AddDays(-3);

    if (date >= currFirstMonday) {
        var nextNewYear = new DateTime(date.Year + 1, 1, 1);
        var nextFirstThursday = nextNewYear.AddDays((14 - (int)nextNewYear.DayOfWeek - 3) % 7);
        var nextFirstMonday = nextFirstThursday.AddDays(-3);
        if (date >= nextFirstMonday) {
            return 1 + (date.Date - nextFirstMonday).Days / 7;
        } else {
            return 1 + (date.Date - currFirstMonday).Days / 7;
        }
    } else {
        var prevNewYear = new DateTime(date.Year - 1, 1, 1);
        var prevFirstThursday = prevNewYear.AddDays((14 - (int)prevNewYear.DayOfWeek - 3) % 7);
        var prevFirstMonday = prevFirstThursday.AddDays(-3);
        if (date >= prevFirstMonday) {
            return 1 + (date.Date - prevFirstMonday).Days / 7;
        } else {
            return 1 + (date.Date - currFirstMonday).Days / 7;
        }
    }
}

Can this code be written shorter? Of course:

private static int GetWeekNumber(DateTime date) {
    var day = (int)date.DayOfWeek;
    if (day == 0) { day = 7; }
    var nearestThu = date.AddDays(4 - day);
    var year = nearestThu.Year;
    var janFirst = new DateTime(year, 1, 1);
    return 1 + (nearestThu - janFirst).Days / 7;
}

This algorithm is described on Wikipedia so I will not get into it here. It is enough to say that it is gives same results as first method but in smaller volume.

Finally I could sleep at night knowing that my weeks are numbered. :)

P.S. If someone is eager to setup their own algorithm, here is test data that I have used. Most of them were taken from ISO 8601 week date Wikipedia entry but I also added a few:

Sat 01 Jan 2005  2004-W53-6
Sun 02 Jan 2005  2004-W53-7
Mon 03 Jan 2005  2005-W01-1
Mon 10 Jan 2005  2005-W02-1
Sat 31 Dec 2005  2005-W52-6
Mon 01 Jan 2007  2007-W01-1
Sun 30 Dec 2007  2007-W52-7
Tue 01 Jan 2008  2008-W01-2
Fri 26 Sep 2008  2008-W39-5
Sun 28 Dec 2008  2008-W52-7
Mon 29 Dec 2008  2009-W01-1
Tue 30 Dec 2008  2009-W01-2
Wed 31 Dec 2008  2009-W01-3
Thu 01 Jan 2009  2009-W01-4
Mon 05 Jan 2009  2009-W02-1
Thu 31 Dec 2009  2009-W53-4
Sat 02 Jan 2010  2009-W53-6
Sun 03 Jan 2010  2009-W53-7

P.P.S. Getting year and day in week is quite simple and thus left for exercise of reader. :)

Padding Length

Quite a lot of modern protocols have padding requirements. One great example is Diameter. All attribute values there are aligned on 4-byte boundary. Reason behind such complication is in data structure alignment. While only benefit on x86 architecture is (usually minor) speed increase, on RISC processor it makes difference between doing some work or crashing in flames.

Most common alignment is on 4-byte boundaries. If we have something with length of 5, aligned length will be 8. However for length of 4, aligned length is also 4. Code is as simple as it gets:

public int GetPaddedLength(int len) {
    if ((len % 4) == 0) {
        return len;
    } else {
        return len + 4 - (len % 4);
    }
}

Lengths that fall into alignment by their own devices are not touched while all other get small boost. Of course that code can be a bit shorter if one is comfortable with C# ternary operator (present in almost all C-like languages):

public int GetPaddedLength(int len) {
    return ((len % 4) == 0) ? len : len + 4 - (len % 4);
}

And, if other alignment is needed, small generalization is all it takes:

public int GetPaddedLength(int len, int align) {
    return ((len % align) == 0) ? len : len + align - (len % align);
}

Null Object Pattern

One of more dangerous patterns that I have seen is Null object pattern. Premise is simple enough: Instead of your function returning null (e.g. when it cannot find an item) it should return special empty object. This avoids null references exception if such object is accidentally used. With simple change to way how we return object we just got rid of crashes. What could go wrong?

Well, someone might implement new functionality a year down the road. Not knowing about this behavior he will check for null in some border line case. Since change is small, no one will do full testing (of course, in real world, any change triggers full retesting :)). His borderline behavior just went from well defined (check for null and take action) to pray that empty object does not get inserted into main program flow.

Exceptions are your friend. That kind of friend that will kick you in the arse when you do something wrong. Having empty object instead of null will indeed stop the crash. However, there is now empty object floating around. Programs are complex and this object is bound to get into wrong place. Best case scenario is that no data gets corrupted.

Null reference exceptions that you would get traditionally are probably among simplest exceptions that you can find in the wild. From stack trace you can see where object is null and just backtrack from there. And probability of data corruption is quite low since program crashed before actually doing anything with affected object. Even if something wrong got inside, crash is quite a clear signal that something is amiss.

Debugging any errors produced by this pattern is not a trivial task. You will probably only notice that something is wrong on data. And you will not notice that error immediately. No, it will be in database for days, weeks if not years until some TPS report exposes it to public. And then you need to find offending code. Talk about needle in haystack…

I view using this pattern as telling someone to kick you in the balls. Maybe there is good reason to take such action, maybe there are even some benefits. Nevertheless there will be some pain involved and one should better be sure that this is really action that is needed.