Agile .NET

Ideas & Gotchas

A simple and tool-free way for database versioning (I)

Posted by Vlad on May 26, 2009

One common problem in projects that involve a database is managing its versions.
Basically, there are two needs to be fulfilled:
- to be able to see a history of changes for a database object in a similar way to seeing the changes for a code file
- to be able to update / revert the database to a specific version without losing the data.

For the first one, a simple solution is to just script all objects in the database to a folder and add it to the source code repository (one file per object – in MS SQL Server can be done with a few clicks from SQL Server Management Studio). When there are changes, all you need to do is to repeat this process and the files will be updated. You can then review changes to database objects in the same way you review them for code files.

The second one is a little trickier. Idealy you want scripts that can be automatically used to:
- update developer database copies
- update the continuous integration database (database used for the continuous integration tests)
- update the test database
- update the production database.

There are tools that give you “diff” scripts that can be used to update a database, but, apart from the price problem, they are difficult to use for several-times-a-day automatic updates like the ones needed to update the developer copies. A second problem is that, because the developers have full freedom in their database copy, some “garbage” or unwanted changes might be picked up and included in the diff script.
The solution below is free, the updates can be run automatically whenever is necessary on any database (developer, test and even production) and ensures that the changes were really meant to be included in the update. All you need is a little discipline from the developers.

Read the rest of this entry »

Posted in Continuous Integration, SQL | Leave a Comment »

ASP.NET – formatting bound fields

Posted by Vlad on October 25, 2007


If you try something like this in a GridView or DetailsView you might end up frustrated:

<asp:BoundField DataField=”Percentage” DataFormatString=”{0:f2}%” HeaderText=” Percentage” ReadOnly=”True” SortExpression=”Percentage” />

That’s because no matter what you put in the DataFormatString property, the text is formatted the same way (although the literal characters from outside the brackets do appear, so DataFormatString it’s not completely ignored).

The solution:

<asp:BoundField DataField=”Percentage” DataFormatString=”{0:f2}%” HeaderText=” Percentage” ReadOnly=”True” SortExpression=”Percentage” HtmlEncode=”false” />

Don’t know why…

Posted in .NET, ASP.NET, WCSF | Leave a Comment »

CenterParent for non-modal forms

Posted by Vlad on October 16, 2007

As it turns out, if you want to show a non-modal form centered in the boundaries of its parent, in .NET 2.0, you’ll have to set its position manually.

Although the System.Windows.Forms.FormStartPosition.CenterParent works fine if you use form.ShowDialog(owner); (modal form), it doesn’t seem to make a difference when using form.Show (owner); for a non-modal form. I suspect a bug, because I didn’t find any mention of this behavior in help.

The solution:

form.StartPosition = FormStartPosition.Manual;

form.Location = new System.Drawing.Point(form.Owner.Location.X + (form.Owner.Width – form.Width) / 2, form.Owner.Location.Y + (form.Owner.Height – form.Height) / 2);

Posted in .NET, C# | 1 Comment »

SQL – Select ranges of records using variables

Posted by Vlad on October 9, 2007

One annoying thing in SQL 2000 was that you couldn’t select TOP @n records using a variable. The options were to construct the SQL query dynamically or (if you wanted to use stored procedures) to use SET ROWCOUNT @n before the select. And of course not to forget to set it back to 0 as soon as you’re done with it.

SQL 2005 solves this problem. You can now use variables in the TOP count:

CREATE PROCEDURE GetLatestAnnouncements
@topCount int

AS
BEGIN

SELECT TOP (@topCount) * FROM Announcements

ORDER BY DateAdded DESC
END

Another handy addition is the Row_Number() function – it basically gives you the sequential number for a row in a result set. You can use it to get “pages” of records just like those you normally need in a paging DataGrid:

Read the rest of this entry »

Posted in SQL | Leave a Comment »

WCSF – Using Session State in Unit Tests

Posted by Vlad on September 28, 2007

The Web Client Software Factory provides a handy class, StateValue<T>, to use for storing values in Session. From the WCSF help:

This class supports code that runs both in a Web server environment (the session is available, and data is stored there) and outside of a Web server environment (no session is available, such as when you run your unit tests, and the data is stored in memory).

To use it, just declare a public field of StateValue<T> type and the Object Builder injects the object:

public StateValue<MyType> MyStoredValue;

To access it, just use the Value property:

MyStoredValue.Value = new MyType();

This works fine when running the application in the web server. When unit testing however, you’ll notice that the field remains null, because the object builder used for the MockCompositionContainer lacks the strategy that deals with the StateValue<T> fields. Unfortunately, the Reference Implementation that comes with WCSF doesn’t make use of these type of fields so there is no quick example on how to deal with them in tests. You can use the tests covering the builder strategies from the CompositeWeb application block tests, or you can use the following quick reference and save yourself the digging ;) .

Read the rest of this entry »

Posted in C#, TDD, WCSF, patterns & practices | 3 Comments »

TDD – MockRepositories for WCF Service Factory

Posted by Vlad on September 21, 2007

MockRepository Class DiagramWhen testing the business logic layer you need to fake the data access layer so you have to worry about the database or the connection speed. The following example focuses on the Repository pattern used in the WCF Service Factory, but it can be adapted to other data access layer architectures.

What do you need from a MockRepository?

· To know if certain methods have been called.

· To know what parameters were passed to those methods.

· To know what (fake) results were returned.

The base Repository class that the Data Access Guidance Package helps you create has 6 types of methods: SearchOne, SearchMany, SearchAll, Insert, Update and Delete. The derived Repository classes use these to accomplish various tasks (SearchById, SearchByIDParent, etc). For the tests, we’ll use the same model: a base MockRepository class that will be inherited by the actual MockRepositories. In order to be able to use them instead of the real ones, we’ll extract the interfaces from the real repositories, have the MockRepositories implement them, and have the business actions work with these interfaces instead.

Read the rest of this entry »

Posted in C#, TDD, WCF, patterns & practices | Leave a Comment »

SCSF – Loading modules into child WorkItems

Posted by Vlad on September 20, 2007

The Composite UI Application Block (CAB) used in the Smart Client Software Factory (SCSF) allows you to specify which modules will be loaded using an XML file or a web service. The problem is that all the modules you specify get loaded into the root WorkItem. If you have a services module, for example, that is used only by one WorkItem, you have to choose between loading it in the root WorkItem and explicitly loading it in the “AddServices” method of your WorkItemController.

The first option can generate EventBroker problems – all events published by the service will be visible to all WorkItems and vice versa, so you might get some “surprise” event calls.

In the second option you get a tight coupling between the module and its services (not always a real problem, but if you have the service in a separate assembly it could be because you are trying to isolate change between them).

The solution we want is to use the same mechanism as the root WorkItem and load the modules defined in an XML file. One way to do this is to create a service that will be available to child WorkItems.

Read the rest of this entry »

Posted in C#, SCSF, Smart Client, patterns & practices | Leave a Comment »

TDD – Test similar objects automatically

Posted by Vlad on September 18, 2007


When testing you get to spend lots of time writing the setup and validation parts of the unit test. I talked in this post about a way to speed up the setup phase – generate objects that have random data in their value-type properties.

Something similar can be applied to the validation part. Let’s take an example of a service implementation with WCF Service Factory. Normally you receive a request containing Data Contract objects, you translate those into Business Entities and pass them to a Business Action. This may return a result also expressed as Business Entities that the service implementation must translate into Data Contract objects and forward them to the client.

Luckily, you have a recipe for creating entity translators. But if you want to test the service implementation thoroughly you have to make sure that every property gets properly translated and forwarded from Data Contracts to Business Entities and back. This means lots of “Assert.AreEqual(source.MyProperty, destination.MyProperty)”. More, if you add or remove properties you have to remember to add them to the asserts list, or they will not be tested.

One way to do this automatically (at least for the value-type properties) is to compare the properties that have the same name and type in both objects – taking advantage of the fact that most of the time they are identical. The following method accomplishes this for non-array value or string properties. It can be extended for arrays and indexer properties or even to drill down into reference types, but i find it difficult to follow what exactly gets tested or not. It can also be used for objects of the same type as a quick property-by-property equality check (or you can use it inside an overridden Equals(), but you have to remove the “obj1.Equals(obj2)” from the first if).

Read the rest of this entry »

Posted in C#, TDD, WCF, patterns & practices | Leave a Comment »

TDD – Create test objects automatically

Posted by Vlad on September 13, 2007


Unit tests normally have three sections: setup, action and validation. In the setup part you often have to create and initialize objects that will be required by the action and that you can use in the validation part to decide whether the code works or not.

The code might look like this:

      [Test]

      public void DoSomethingWorksFine()

      {

            MyObject obj = new MyObject();

            obj.Text = “test text”;

            obj.ID = Guid.NewGuid();

            obj.Date = DateTime.Now;

            // etc.

            testedObject.DoSomething(obj);

            // asserts

      }

Although normally one or two initialized properties are enough, I consider it a good practice to check that all the fields pass well through the test (especially when you’re testing database repositories or web service calls). The problem is that if you use the default values you won’t know if the test passed just because the result has the same initial values.

My solution is a handy utility class that fills the objects properties with random data:
Read the rest of this entry »

Posted in C#, Extreme Programming, TDD | 2 Comments »

Message Contracts in WCF and the Smart Client Software Factory

Posted by Vlad on September 5, 2007

Programming WCF ServicesWe’re developing a new product and we took the chance to change from ASMX web services to WCF. We’re using the Service Software Factory and the Smart Client Software Factory from patterns & practices. I have to admit we’re not experts in WCF yet, but the best way to learn is to practice.

The Service Factory makes it easy to declare Data Contracts (there is even an option to decorate an existing class), Message Contracts and Service Contracts. Basically, a Service Contract defines one or more Operation Contracts that use the Data Contracts as parameters.

So where do the Message Contracts come into play? The Service Software Factory Help says:

“A message contract is a class that represents a request or response message. While data contracts represent types that are reused across services and operations within a service, message contracts are defined for a specific operation on a service and are not reused.”

This and the example that follows on how to define the Message Contracts led us to think about the Message Contracts more as wrappers for the request and response for an operation.

Read the rest of this entry »

Posted in C#, SCSF, Smart Client, WCF, patterns & practices | Leave a Comment »