Thursday, January 19, 2006

Using database transactions in unit tests

I started using the advice of Roy Osherove regarding how to use transactions in unit tests (see previous blog entry).

To summarize the method:

using System.EnterpriseServices;

ServiceConfig config = new ServiceConfig();
config.Transaction= TransactionOption.RequiresNew;
ServiceDomain.Enter(config);

[database CRUD code]

if(ContextUtil.IsInTransaction)
{
ContextUtil.SetAbort();
}
ServiceDomain.Leave();

This code worked fine after having sorted out some configuration problems. I am accessing the SQL Server 2000 on a Windows 2003 server from a Windows XP on a different domain. First I got "The partner transaction manager has disabled its support for remote/network transactions.", this changed when I allowed for MSDTC on the server. Then I got "The transaction manager has disabled its support for remote/network transactions" which was fixed by allowing MSDTC on the client machine. The final error was because the firewall was blocking the connection.

Therefore in order to make this work (for this scenario) it is necessary to:
  • Allow MSDCT on the client and server: Administration tools -> Component Services -> Computers, right-click on My Computer, click on the "MSDTC" tab, click on "Security Configuration" and allow everything :) In particular: "Allow Outbound" on client, "Allow Inbound" on server (the SQL Server machine), set "No Authentication Required" on both server and client, and enable TIP and XA Transactions on both server and client.
  • In the firewall open up for the msdtc.exe: %root%\WINDOWS\system32\msdtc.exe on both client and server.

Now I am able to control the initial conditions of the database programmatically in a simple manner :)

P.s. The above settings work for me, but further instructions can be had here and here.

No comments: