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

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.

Choose Your Poison

When dealing with programs there are almost always multiple ways to write same thing. Rule of thumb is usually to write it in most readable way. And there people start disagreeing what exactly is readable. Let’s take simple condition:

if (object.equals(obj1, obj2)) {
    ...
}
if (object.equals(obj1, obj2) == true) {
    ...
}

Both these statements do exactly same thing. Heck, they even get compiled to same code. However most programmers I have ever met prefer first one. It just makes intention clear in shorter form.

It’s negative cousin would be:

if (!object.equals(obj1, obj2)) {
    ...
}
if (object.equals(obj1, obj2) == false) {
    ...
}

Again, both statements are same. But I can bet that they will do almost perfect split among programmers. Half of them will prefer concise form with other half preferring longer form. Reasons will vary. For some exclamation mark is too easy to omit when scanning code. For some longer form just sticks out for no good reason.

Personally I passionately hate negative statements and I will avoid them whenever I can. If I really need them I am in group that strongly believes that later form, while longer, is superior as readability goes. For me that is worth seven additional characters. Strangely enough, in positive cases, I omit true.

P.S. One more variation of negative case would be:

if (!(object.equals(obj1, obj2))) {
    ...
}

It might as well be in goldilocks zone. It gives a bit more visibility to exclamation mark by enclosing everything in another set of brackets. Of course, given statement long enough, it can look rather crowded.

WordPress Noindex

As I was checking search for my website I noticed that Google would return essentially same page multiple times in search results. One result pointed to post, second one pointed to same post but within categories and third would be same again but in archives. Not what you can call great search experience.

On WordPress platform (that is used here) solution is really simple. All pages that I don’t want shown I can block from Google via robots meta attribute with content “noindex,follow”. Simplest way to do this is to directly edit header.php file and, below

tag, just write:

<?php
    if (!is_singular()) {
        echo '&lt;meta name=&quot;robots&quot; content=&quot;noindex,follow&quot; /&gt;';
    }
?>

If page is singular in nature (e.g. post, page, attachment…) nothing will happen. If page is collection, one simple html attribute is written.

While this is simplest solution, it is not upgrade-friendly. For each new WordPress version, same change will be needed. Better solution would be to pack this into plugin so each new version can continue using it without any change. Creating plugin in WordPress is as easy as filling some data in comment (e.g. plugin name, author and similar stuff) and then attaching to desired action. In our case full code (excluding plumbing) would be:

add_action('wp_head', 'nonsingular_noindex_wp_head');

function nonsingular_noindex_wp_head() {
    if (!is_singular()) {
        echo '&lt;meta name=&quot;robots&quot; content=&quot;noindex,follow&quot; /&gt;';
    }
}

Whole plugin can be downloaded here. Just unpack it into wp-content/plugins directory and it will become available from WordPress’ administration interface.