Rewiring the users and logins in SQL Server

As a developer I find that I’m frequently backing up and restoring SQL Server databases between servers for development and testing purposes. However, each time I do the link between the login (a server concept) and the user (a per database concept) gets broken.

There is a stored procedure in SQL Server to wire it all back up again and I keep forgetting what it is. So here it is (my aide memoir):

sp_change_users_login: It maps an a database user to a SQL Server login.

The quick and easy way is as follows:

sp_change_users_login 'Update_One', 'myUserName', 'myLoginName'

 

Setting the language on a iPad to UK English

Out of the box the iPad is configured to display in English. Sounds reasonable for an iPad bought in an English speaking region. And considering it was bought in the UK I would have assumed that the simple language moniker of “English” meant actual, well, English… as in the language from England, spoken in England, written in England, etc.

It turns out that it doesn’t mean that at all. It means American English. If you want actual English, you have to go through a hierarchy of settings menus to find it hidden way down near the bottom of a list and find the entry called “British English”… No mention of any of the other variants of English, incidentally.

I wouldn’t have minded so much, even although I tend to think of actual English as being “UK English” or “English (UK)” when talking in an international context, but to have “English” mean “American English” seems a bit of an affront…. And I’m not even English!

Anyway, if you want your iPad to display stuff in English (as in British, Commonwealth, or just plain English English) then here’s what to do:

Click the Settings icon, unless you’ve moved it it’s on your home screen. Once in the settings app, select General:

iPad General Settings

Down near the bottom of the General settings you’ll see a button marked International, press it.

iPad International SettingsThen at the top, you’ll see a setting called Language, which is probably displaying “English” as the language at this point. Press the Language button.

iPad Language dialog (English... as in American English)Now you will see the Language pop up and “English” (as in American English) will be ticked. To get to British/Commonwealth/UK English scroll the list all the way to the bottom.

iPad Language (displaying British English)You can now tick “British English”. When you press “Done” the screen will go black and a couple of seconds later it will show your app icons again… This time, your iPad is now displaying actual English.

Interestingly, it looks like Apple have also taken an Amero-centric view of Portugues too. It displays “Português” (which I assume is Brazilian) and “Português (Portugal)”… It’s all a bit like walking up to your parents and giving them a big slap in the face really.

First(OrDefault) Vs. Single(OrDefault)

There are two mechanisms (each with an …OrDefault variant) in LINQ for getting one item out of an enumeration. They are First and Single. There is a difference between the two and you can produce code that functions incorrectly if the wrong one is used.

So, what’s the main difference? They both sound like they’ll return just one item out from the enumeration. And, indeed, they do.

First will return the first item that it encounters that matches the predicate (if supplied). Whereas Single will return the one and only item that it encounters that matches the predicate (if supplied). If Single encounters a second item that matches the predicate then it throws an exception. If no predicate is supplied, it throws an exception simply if the enumeration has more that one item.

Why would there be two things that do almost the same thing that are so subtly different? First exists so that you can get the first item regardless of how many items there may actually be. Single exists to get you the one and only item. Single is useful when your predicate operates on a primary key. For example:

data.Single(d => d.PrimaryKey == idToMatch)

The …OrDefault variants will return the default value for the type (for reference types that will be null) if there are no matches found. Otherwise, both First and Single throw an exception if no items are encountered.

Lets look at some code.

First

string[] data = new[]{"Zero", "One", "Two", "Three",
    "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
var first = data.First();

In this case, first will contain the value of "Zero".

If a predicate is added to the call to First then we can see what happens if there is no match.

string[] data = new[]{"Zero", "One", "Two", "Three",
    "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
var first = data.First(x => x.Length > 10);

In this case, there are no matches, and an InvalidOperationException is thrown with the message “Sequence contains no matching element”

The same thing will happen if the initial set of data is empty

string[] empty = new string[0];
var first = empty.First();

You can happily supply a predicate that may match more than one item in the enumeration

Single

For example

string[] onlyOneItem = new string[]{"Only item"};
var single = onlyOneItem.Single();

This will return the one and only item that matches.

string[] data = new[]{"Zero", "One", "Two", "Three",
    "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
var single = data.Single();

This will thrown an exception. If result set contains more than one item an InvalidOpertationException will be thrown with a message of “Sequence contains more than one element”

string[] empty = new string[0];
var single = empty.Single();

This will throw exactly the same exception as it’s First counterpart; an InvalidOperationException is thrown with the message “Sequence contains no matching element”

…OrDefault

This is where things get a little bit more interesting. This says that if the result set contains zero items null (for reference types) is returned. In the case of First, the result set can contain zero, one or many items and it won’t throw an exception. In the case of Single only result sets containing zero or one item will return while any more will result in an exception.

So… what about this scenario:

string[] data = new[]{null, "Zero", "One", "Two", "Three",
    "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
var first = data.FirstOrDefault();

The first value of the set is genuinely null. How do you tell the difference between that and the result set being simply empty without throwing an exception?

You could just go back to using the First variant and catching the exception. Or you could (if your result set can be enumerated many times without issue, e.g. the underlying object is an Array or List) use Any to test if the set contains any data in advance. Like this:

string[] data = new[]{null, "Zero", "One", "Two", "Three",
    "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
if (data.Any())
{
    var first = data.FirstOrDefault();
    // Do stuff with the value
}

DDD Belfast Parallelisation Talk

Examples

Here are all the examples from Saturday’s introductory talk on Parallelisation at DDD Belfast.

Slide Deck

You can download the slide deck here.

Singular Vs Plural table names

A while ago I blogged about whether to make table names singular or plural. The subject raised itself again recently in the office after Microsoft’s Entity Framework makes some pretty odd decisions when converting from Plural to Singular form. (According to EF the singular of “ranges” is “ranx”… and if you look on places like Stack Overflow you’ll find other examples, such as “changes” to “chanx”)

Here are the updated results

  • Singular: 9
  • Plural: 10
  • Either: 4

Again, there is no overall winner

Those in favour of pluralising the names said:

  • To me, table names should always be plural – they’re a collection of records, and the singular form applies to the record.

Those with no preference:

  • I’ve tended to find that people who are more used to thinking of the model in class terms tend to prefer singular. People who are used to thinking from the DB first tend to prefer plural.
  • For me using an ORM should be removing the need for me to think about database naming because ideally I will never have to go direct to the database tables, I will always be going through objects.

In favour of Singularising names:

  • I’ve always used and prefer singular – better ordering of tables and fewer problems with mappings, but as long as we’re consistent (within a single database)

I suspect this debate will continue on for as long as there are table based databases…

Tip of the day: Expire a cookie, don’t remove it

I recently found a bug in my code that I couldn’t fathom initially until I walked through the HTTP headers in firebug. In short, you cannot simply remove a cookie by calling Remove(cookieName) on the HttpCookieCollection. That will have no effect. You have to expire the cookie in order for it to be removed.

In other words, you need code like this:

HttpCookie cookie = new HttpCookie("MyCookie");
cookie.Expires = DateTime.UtcNow.AddYears(-1);
Response.Cookies.Add(cookie);

When you create a cookie, the response from the server will contain an HTTP Header called Set-Cookie that contains the value of the cookie.

For example, if we create a cookie like this:

HttpCookie cookie = new HttpCookie("MyCookie");
cookie.Value = "The Value of the cookie";
Response.Cookies.Add(cookie);

Then the Response will contain this:

Set-Cookie    MyCookie=The Value of the cookie; path=/

Each subsequent request to the server will contain the cookie, like this:

Cookie        MyCookie=The Value of the cookie

The responses from the server do not contain the cookie unless the server is updating the value of the cookie.

When the cookie is to be removed forcefully, the server must update the cookie with a new expiry, like this:

HttpCookie cookie = new HttpCookie("MyCookie");
cookie.Expires = DateTime.UtcNow.AddYears(-1);
Response.Cookies.Add(cookie);

The response will then have this header:

Set-Cookie    MyCookie=; expires=Mon, 20-Sep-2010 21:32:53 GMT; path=/

And in subsequent requests the cookie won’t be present any more as the browser will have removed it.

Installing a web site on a new server

Here are some blog posts that have been useful to me lately when I got caught out installing a website on a new server (I will eventually get that automated build and deploy process actually performing the deploy step successfully!!)

The configuration section ‘system.web.extensions’ cannot be read because it is missing a section declaration:

While installing a website on a new Windows Server I came across this error. In short, it was because the App Pool was set up as a .NET 2.0 application rather than a 4.0. The blog post explains what was going on and how to fix it.

[Resolved] Could not load file or assembly ‘XXXXX’ or one of its dependencies. An attempt was made to load a program with an incorrect format:

Although this didn’t help me in the end, it does suggest a solution. In my case, because of a third-party dependency that requires an x86 build, it couldn’t be used. In time that dependency will be removed, in the meantime the following was more helpful to me…

Could not load file or assembly ‘PresentationCore’ or one of its dependencies. An attempt was made to load a program with an incorrect format. : A solution:

This post did give me the pointer I needed to the setting that had to be changed to get the web site working.

Browser wars

Every so often I update my chart of the technologies people use to view my blog. The last time was back in October last year, and the chart as it looks now is very interesting. The three major browsers (Internet Explorer, Fire Fox and Chrome) are now converging at around 30% share each. Other browsers such as Opera and Safari don’t get much of a look in. However, it does look like I’ll shortly have to start noting down one or two mobile browsers distinctly. Currently mobile browsers are all lumped into the “Other” category.

Meanwhile, on the operating system front Windows XP continues to slowly ebb away. However, the fact that 30% of the visits to my blog are from a Windows XP machine is still painful to see. Vista users are also dying away and are down to about 6% now. At its current rate of decline there will be more Mac users visiting my blog by the turn of the year.

Google Analytics also has a facility to record page load times, however it is currently only reporting from Internet Explorer and Chrome at the moment. That coupled with only 3 months of data so far doesn’t make for very interesting trend watching. However, in a future update I’m sure I’ll add page load times.

Tip of the day: Getting Visual Studio with TFS to work offline

Earlier to day our TFS server went down. Visual Studio likes to have a constant connection open to it, but obviously that wasn’t going to happen. Luckily, it is possible to work on a solution with no connection to TFS.

If you were just starting some work…

If Visual Studio was open when TFS went off-line then it won’t allow you to check out any files. If all your files are checked in already, then you can just shut down Visual Studio and then start again. When the solution opens it detects that TFS is gone and offers to open the project in Offline mode:

Go Offline
TFS Go Offline

When TFS is available again you can simply reconnect to the server by selecting the Team?Connect to Team Foundation Server… menu. Once you are connected, you can right-click the solution and select “Go Online“.

You’ll get a dialog that asks to to confirm the files that you’ve changed in the meantime:

Go Online
TFS Go Online

It will then take a few moments for TFS to catch up (I have quite a large solution, so it took about a minute for me) then the files appeared in the Pending Changes window ready to be checked in as normal.

If you were in the middle of something

If you already had files checked out when TFS went offline then this post about converting to offline may be more useful to you.

There is also a Visual Studio extension, if you prefer not having to restart Visual Studio called Go Offline. Once installed, just to to File?Source Control?Go Offline. This may be a more useful solution if you are constantly going in and out of connection with TFS (a mobile broadband connection on a train for example).