Monthly Archives: April 2012

Server unplugged

One of my first servers I used for real world applications is now unplugged. Weird feeling. It was Linux box running Slackware 10.2.0 (yeah, old). For a while it was my main mail (Postfix, Dovecot) and antispam (SpamAssassin) server. I had Firebird there as well as Apache/httpd, PHP, Subversion and Mono. And all the standard services (SSH, cron, FTP, gcc, …). The Firebird handled quite some applications thorough years. Apache handled till very last time, among other things, download mirror for PSPad (and I learned a lot about performance tuning with limited resources available when new (non-beta) version of PSPad was released). Few scripts were written in Perl, a lot of in bash directly. And that’s just what I remember.

Upgrading, configuring, compiling all these services… What a great memories.

You served well all these years (8?).

root@<removed>:~# shutdown now

Broadcast message from root (pts/0) (Mon Apr 30 08:29:38 2012):

The system is going down to maintenance mode NOW!

Compare NULLs in database as in C# in Entity Framework

Roughly two years ago I blogged about differences in NULLs handling in databases and in (some) programming languages (C# in particular). But Entity Framework 5 (in .NET 4.5) (lost?) comes with handy switch. It’s UseCSharpNullComparisonBehavior. What this basically does is ensure when you compare nullable fields to be handled like in C#, aka null == null and not like in SQL where NULL compared to anything is NULL or false when boolean value is needed.

Let’s have a look at the diffences. Simple code:

int? i = default(int);
using (testEntities c = new testEntities())
{
	c.ContextOptions.UseCSharpNullComparisonBehavior = true;
	Console.WriteLine((c.Details.Where(x => x.MasterID != i) as ObjectQuery).ToTraceString());
}
using (testovaciEntities c = new testovaciEntities())
{
	c.ContextOptions.UseCSharpNullComparisonBehavior = false;
	Console.WriteLine((c.Details.Where(x => x.MasterID != i) as ObjectQuery).ToTraceString());
}

The first query creates “magic” SQL:

SELECT
[Extent1].[ID] AS [ID],
[Extent1].[ID_MASTER] AS [ID_MASTER],
[Extent1].[BAR] AS [BAR]
FROM [dbo].[DETAIL] AS [Extent1]
WHERE  NOT ((([Extent1].[ID_MASTER] = @p__linq__0) AND ( NOT ([Extent1].[ID_MASTER] IS NULL OR @p__linq__0 IS NULL))) OR (([Extent1].[ID_MASTER] IS NULL) AND (@p__linq__0 IS NULL)))

While the other expected one:

SELECT
[Extent1].[ID] AS [ID],
[Extent1].[ID_MASTER] AS [ID_MASTER],
[Extent1].[BAR] AS [BAR]
FROM [dbo].[DETAIL] AS [Extent1]
WHERE [Extent1].[ID_MASTER] <> @p__linq__0

What the first one is doing is handling the case where C# null (in parameter) can be compared to database NULL to fix-up the logic.

If you’re not familiar with NULLs in database this can be tricky to handle correctly, especially if you have negations, Alls and Anys nested inside query. Hence setting this property to true can save you hours of debugging and wondering what’s going on.

ID or Id?

Looks like there are two groups of developers. One writing ID and one writing Id. I'm in the first one, and I'm even not 100% sure why (except because my feelings are saying me, it's "more" correct). But it looks like there's no conclusion.

More and more I see the other option being used often (DbContext or HttpApplication to name a few), especially if you take into account properties like URL and so on. It even looks this is more common inside .NET Framework, but still, i.e. DBNull or System.Web.UI is an exception. Who knows...

Anyway, I'd like to ask you. What are your habits? Have you find some good pros (or cons) for one or the other? Or articles/papers/... about this naming? Share your thoughts in comments.

Update:
In "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition)" I've found (link):

Two other terms that are in common usage are in a category by themselves, because they are common slang abbreviations. The two words Ok and Id (and they should be cased as shown) are the exceptions to the guideline that no abbreviations should be used in names.

Solved. On the other hand the DbContext and DBNull is still weird inconsistency.

Count for System.Collections.Concurrent.ConcurrentStack<T>

Collections in System.Collections.Concurrent namespace are optimized for access from more (basically) threads. That means no stupid “one-lock-for-everything” approach. Actually these are lock free.

It’s good for performance, but also, if used foolhardily, the performance penalty can be too big. One example can be the ConcurrentStack<T> class. As with a lot of collections, this stack also has a Count property. But because it’s a lock free implementation using linked list the Count isn’t that easy. Actually it’s O(n) and this can be especially bad for big stacks. So use with care. As the remarks for this property recommends, if you need to know just whether it’s empty of not, the IsEmpty is better (though realize, that in time you check it it might be empty, but not on next line where you’re about to perform some action and vice versa).

Use the tools, but also know your tools.

Generating POCO and Code First mapping from database

I like POCOs and Code First. Simply because that way I have everything under my control. I don’t mean just the code itself, but also the formatting, ordering of static/public/private/… properties etc. Same with mapping. Everything is described by me. No magic conventions. But there was one problem. If you already had a database (even with new database the initial amount of tables is big) writing all this stuff was tedious and boring.

Apart from the option to write the tool to do it yourself, there was an “hack” to create a EDMX model and generate classes (easy) and mapping (little harder) from it. In fact there are some templates ready, so you don’t have to start from scratch. But still, too much “problems”.

Luckily now there’s a tool for that, that does all in one step. EF Power Tools (currently Beta 2). When you right-click on project, you’ll get Entity Framework menu with Reverse Engineer Code First.

This will query the database similar as when using EDMX and spit out entity classes and (complete) mapping (using Fluent API). You can even customize the template being used for generating code. It’s just T4. Only difference is, that you can’t select subset of tables. It will always create code from whole database (which can be problem for huge legacy databases). And you don’t have any progress while process is running. But it’s still beta. :) On the other hand, you can run it multiple times, it will overwrite the original files, so you’ll get fresh mapping, which can be quite handy, and entities (sure you’re using VCS to merge your changes back).

I tried it even with Firebird and worked as expected, probably any EF enabled provider will work.

If you’d like to read more about features, check the blog post on ADO.NET team blog. Other are interesting too (like View Entity Data Model (Read-only)).

Problem “Could not load file or assembly ‘<assembly>’ or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0×80131047)” when using Entity Framework’s migrate.exe

When you use migrate.exe from Entity Framework‘s Migrations (in time of writing 4.3.1) you might get the error saying:

Could not load file or assembly ‘<assembly>’ or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0×80131047)

That’s nice, but nothing special, right? The reason is simple and as lot of magic execution errors it is current/working directory related. To fix it, simply explicitly specify path (relative works) to your assembly using StartUpDirectory parameter. And there’s another one gotcha. This parameter works only with :. Let me explain.

migrate.exe /StartUpDirectory C:\Foo\Bar\Baz

Doesn’t work (and no error). But this one.

migrate.exe /StartUpDirectory:C:\Foo\Bar\Baz

Does.

Hope it saves you some time hunting what’s wrong.