Monthly Archives: March 2011

My pain when migrating to PHP 5.3 from PHP 5.2 (related to Firebird and MySQL)

I was recently migrating my server to PHP 5.3. To be honest I don’t know why. I’m not using PHP often, only few applications and some simple web pages (really simple logic). And this blog. To make things worse, I’m using as my main database Firebird, not MySQL. And PHP driver for Firebird, say, it’s very average. But to keep myself in touch with “current” world I decided to go to PHP 5.3 (hoping also some bugs (mainly Firebird related ;) ) to be fixed there). I faced two issues.

First was problem with loading php_interbase.dll. After some research I found, the gds32.dll isn’t part of PHP package as it was in 5.2. Using fbclient.dll from Firebird’s installation and renaming it to gds32.dll didn’t solve the issue. Surprisingly (thanks Process Monitor), the extension is looking for fbclient.dll (in PHP’s directory, not in ext). InterBase & Firebird mix. :)

Other problem was MySQL. I don’t like the database and also I’m not expert in PHP+MySQL stuff. I feel more strong around Firebird stuff. The incompatibility is known and it’s about MySQL’s new (longer) password hashes being mandatory to be able to connect from 5.3. And you get error saying it: mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication.. I’m not admin (logically or from privileges) of MySQL server I’m using, so some tips were not working. The final commands that solved my issue were:

set session old_passwords = 0;
set password = password('<password>');

I was kind of jumping around it, with similar commands or commands doing same thing only requiring higher privileges.

Although simple to solve, I spent some time doing wrong steps (and trying). Hope this will save yours.

Type mapper in Entity Framework 4.1

Even if you remove all conventions when using Code First you might get errors from Entity Framework about not being able to properly map some items. The reason is type mapper. In RC (and very probably in RTM as well) it’s not implemented as convention, hence always kicks in.

In this case the Ignore method comes into play. For instance I have in my code property:

public CultureInfo Locale 
{
	get { ... }
	set { ... }
}

and I’m not mapping it at any place. But Entity Framework will still complain about pieces of CultureInfo not being properly mapped. But in EntityTypeConfiguration can make Entity Framework to ignore it. For example:

class FooBarConfiguration : EntityTypeConfiguration<FooBar>
{
	public FooBarConfiguration()
	{
		// ...
		this.Ignore(x => x.Locale);

		this.Map(...);
	}
}

At first I was confused, but after quick email exchange with EF team the “issue” was clear.

Removing all conventions in Entity Framework 4.1 Code First

Convention-over-configuration is great, at least for a quick start, in my opinion. But if you’re like me and you want everything under your control, you may want to remove all (at least those you can remove via code).

Because now there’s no list available (based on RC version, but very probably it’ll be same in RTM) as it was in i.e. CTP5 you need to kind of get all items implementing IConvention interface. And because I want my code work no matter what will be added or removed in next versions, I’m not going to hardcode these. Couple of lines with reflection and we’re done.

MethodInfo method;
method = typeof(ConventionsConfiguration).GetMethod("Remove");
foreach (var convention in Assembly.GetCallingAssembly()
	.GetTypes()
	.Where(t => t.Namespace == "System.Data.Entity.ModelConfiguration.Conventions" || t.Namespace == "System.Data.Entity.Infrastructure")
	.Where(t => t.GetInterface("IConvention", false) != null && !t.IsInterface && !t.IsAbstract))
{
	method.MakeGenericMethod(convention).Invoke(modelBuilder.Conventions, null);
}

I’m simply looking into System.Data.Entity.ModelConfiguration.Conventions namespace, where all the “I-do-the-mapping-for-you” conventions are and also System.Data.Entity.Infrastructure namespace, where the default database creation etc. stuff lives. The code is in overridden OnModelCreating method.

Now you can explore what one must do to create proper mapping by hand. :)

Entity Framework v4.1 Code First and Firebird

I do love Entity Framework. And you probably know it from the amount of weird ways to do some things published on this blog. And so I do love Code First. It’s like having all the power absolutely under control (or at least there’s a possibility to have it). And I also do love Firebird. It’s a great database engine. And I admit, it has strong as well weak points. But every engine does.

So there’s no wonder I’m using Entity Framework’s 4.1 (currently in CTP stage) Code First with Firebird. If you’re a bit lazy and you’re specifying only required minimum on information to run the mapping, you might quickly face one problem.

Long story. If you generated your model from database, the SSDL contained a lot of information about database structure. Especially lengths of (var)char fields. And these information were then used by provider for Firebird to create proper queries. But with Code First it’s bit boring to specify lengths for string fields moreover, when it works without it.

But the Firebird’s API has some limitations (especially around sizes of stuff) and by default (right now – CTP) the (var)char fields are 4000 characters long. The amount of (var)char parameters in code is limited (depends on few variables like charset, hence I’m not putting here exact number) and with UTF8 (multi-byte charset) it’s even more limited. And UTF8 is option #1 in .NET world.

All this together, couple of (var)char fields without length specified and you could start seeing Implementation limit exceeded and block size exceeds implementation restriction etc. The first place where you’ll see it is inserting, because there you have all the fields.

The solution is easy. Specify lengths explicitly and hope for the best. If the table is very wide (aka it doesn’t work), you could always split the table in more (yes, not great, but …).

Are you Lazy<T>?

Yesterday I was chatting with Aleš Roubíček after lunch and he told me he likes the Lazy<T> I put into project we’re working right now and that could be worth to write about it.

Well, here it is. The Lazy<T> class is new in .NET Framework 4. Using this class is easy. If you don’t wnat to create instance of some object until it’s really needed this class will help you. And it can deal with multithreading as well.

So the well known code:

Foo _foo;
public Foo Foo
{
	get
	{
		if (_foo == null)
			_foo = new Foo();
		return _foo;
	}
}

can be replaced with:

Lazy<Foo> _foo = new Lazy<Foo>(() => new Foo());
public Foo Foo
{
	get
	{
		return _foo.Value;
	}
}

Nothing special, but when the multithreading comes into play, it’s more fun. This class has a constructor taking LazyThreadSafetyMode and you can specify what kind of thread safety you want.

  • None is obvious.
  • PublicationOnly means, that the function creating value can be executed by more threads, but only one value will be used.
  • ExecutionAndPublication ensures that the function creating value is executed only once.

By the way if you don’t provide the function, the default constructor will be invoked.

Handy isn’t it.

Let’s play with it:

class Program
{
	static void Main(string[] args)
	{
		Test(LazyThreadSafetyMode.PublicationOnly); // 2x ctor, True
		Console.WriteLine("===");
		Test(LazyThreadSafetyMode.ExecutionAndPublication); // 1x ctor, True
	}

	static void Test(LazyThreadSafetyMode mode)
	{
		Lazy<Foo> _foo1 = new Lazy<Foo>(() => new Foo(), mode);
		Foo f1 = null;
		Foo f2 = null;

		Parallel.Invoke(() => { f1 = _foo1.Value; }, () => { f2 = _foo1.Value; });
		Console.WriteLine("Same: {0}", object.ReferenceEquals(f1, f2));
	}
}

class Foo
{
	public Foo()
	{
		Console.WriteLine("Running Foo's ctor.");
		Thread.Sleep(2000);
		Console.WriteLine("About to finish ctor.");
	}
}

Type safety of SQL commands

I don’t know why, but often I hear that the SQL commands are not type safe. That’s kind of badly said. No it’s wrong, without the proper context.

SQL commands are actually type safe. Did you tried to compare blob and date? Yep, it doesn’t work. And you get the error immediately during the prepare phase (or during compilation of i.e. trigger). Yes, you can compare int and date, because there’s a lot of implicit conversions in every database engine. But basically, if you wrote something wrong, the engine will let you know very quickly.

The problem lies in other detail. Nobody creates and application based only on SQL commands. Your application is probably something like C# or Delphi application, created from C# or Delphi code and compiled. And inside this code you have SQL commands, very probably strings. The C# or Delphi compiler isn’t able to verify the commands, hence to be sure it’s OK, your application needs to execute these commads. And that’s runtime.

Summary? No, SQL commands are type safe but only on server. Written in your applications code it’s still type safe, but not from point of view of type safety of your code and compiler’s rules.

It’s similar to some kind of hypothetical “eval” function in i.e. C#. If you write directly the code, it’s OK. But once you put something into this function (corresponds to database engine), compiler can do nothing with it, until executed.