User stories and customer

Posted by Chris on January 04, 2007

On the XP mailing list, Adam Sroka posted “this great reply”:http://tech.groups.yahoo.com/group/extremeprogramming/message/124598 to a question regarding how to write a story when there is no user involved. The entire thread is very interesting, but this message contains probably the most well written description that I have seen of the customer in XP (and other agile methodologies.

Plus one on Ayende’s OSS post

Posted by Chris on December 11, 2006

Ayende Rahien recently wrote a very well thought through post discussing The Problem of Open Source in the Microsoft World. This is a must-read for any .NET developer who has reached the stage of looking for tools outside of Microsoft. As Ayende describes, a big part of the problem is that there is one major vendor, Microsoft, who not only gives us the basic framework we use to create applications on but also the tools we use to do so with. This means that we can never expect to see built-in support for creating and running NUnit tests. Microsoft has the strength to respond to a need of .NET developers (unit testing their code in this case) by creating their own framework (MS Test) and promoting that, instead of using (or at least including support for) existing de-facto standards (NUnit and MbUnit in this case) already being used by .NET developers.

While I can hope that this might change (as said by others, some IDE competition would be great) I am afraid that it will not happen anytime soon. So what can we do in the meantime? I think it is important for those of us who are using OSS tools (or simply tools from other vendors) to promote them in the .NET community. I am not saying that there always exists a better alternative to Microsoft products, often there does not, but it is important that we help the rest of the community see and evaluate the alternatives. I think some good work is being done here. At öredev, the largest developer conference in Sweden, the .NET track consisted of ten seminars and two half-day workshops. Half of these (one workshop and five seminars) discussed some new technology from Microsoft (Atlas, .NET 3.0, Linq etc), but half of them where mostly about educating the .NET community about professional development using TDD, domain-driven design and AOP. These are competencies that are much more common and standard knowledge in the Java community than what they are in .NET.

At the latest SNUG meeting I did my presentation on testable user interface code and Joel Fjordén and Richard Houltz discussed tools for developer productivity (CodeRush/Refactor and Resharper was also mentioned), coding guidelines (from outside of Microsoft, sort of) and how to enforce them using Joel’s CodeStyleEnforcer plugin. This is what we need to do, getting the .NET community together at meetings and facilitating discussions about professional development and creating better code, by showing what tools are available. This of course includes Microsoft tools, but we should not be limited to this one major vendor.

Testable UI code presentation at SNUG

Posted by Chris on December 08, 2006

I did a presentation two days ago at “SNUG”:http://www.snug.se/. The topic was *Testable UI Code*. The title of my presentation was actually “_Cleaning up the mess_” with the subtitle “_How to take control over monstrous UI classes_”. You can download the presentation and code (it was mostly code) in a zipped file.

I started out by showing a demo application, built in the all too common way of simply having all code in one form. Naturally, this was only an example so a real application would have multiple forms and maybe even reusable code in the form of some custom user controls. The problems with this application is that it is difficult to test the behaviour of it. Automating some sort of user interface driver to test it creates tests that are much too brittle and difficult to maintain (there are even those that take a screenshot of the UI and then compare the screenshots created by a test to the “correct” ones!).

I then showed how to take the first step to a better design, by separating the domain logic from the UI class. To my surprise only about half of the audience raised their hands when I asked how many do this in their applications. I guess that it might be that some just did not bother to raise their hands, while others did not really associate with the example I showed (maybe they are using a “Transaction Script”:http://www.martinfowler.com/eaaCatalog/transactionScript.html style rather than the “Domain Model”:http://www.martinfowler.com/eaaCatalog/domainModel.html I showed). This step is what Martin Fowler describes as “Separated Presentation”:http://www.martinfowler.com/eaaDev/SeparatedPresentation.html. My examples are very similar to the ones in Fowler’s texts, so it should be very easy to read his detailed writings and take a look at the examples I created to get a good understanding of the things I discussed in the presentation.

The next step I discussed is to move presentation logic from the UI class to a separate class, often called a presenter. The UI class will simply delegate user input to the presenter class, so I think a simple name for this pattern would be Delegated Input Handling (or similar), although I have never heard it called something like that. The common name for this is of course Model-View-Presenter, but I tried to avoid discussing Model-View-Presenter and Model-View-Controller until later in the talk. The demo (in my code) is called “Passive View”:http://www.martinfowler.com/eaaDev/PassiveScreen.html, since the view (the UI class) contains no logic at all. The view does not do anything else than signalling the presenter when user interaction happens (delegated input handling) and then acts as a getter/setter for the various UI elements that the presenter needs to control.

After this I showed a variation of the step above, where the presenter was simplified by replacing the simple plumbing logic with data binding. To accomplish this the presenter exposes the model (domain objects) to the view so that the view can bind the UI elements to properties of the model. The reasoning for doing this is that data binding is “automatic” and included in the framework, so we can safely use it even though we can no longer test this part of the presentation logic. Martin Fowler calls this pattern “Supervising Controller”:http://www.martinfowler.com/eaaDev/SupervisingPresenter.html (though I would call it Supervising Presenter as he discusses in the article), since the presenter now only supervise things by reacting to user input and letting the view automatically show the current state of the model. However, as a supervisor the presenter will also take control of those situations where automatic handling such as data binding is too difficult or impossible. In those situations it will work with the view in the same way as in Passive View. My demo has an example of this.

Finally, I showed a demo of “Presentation Model”:http://www.martinfowler.com/eaaDev/PresentationModel.html. This pattern is kind of similar in intention to MVP (Passive View and Supervising Controller), but it is differently realized. Here instead of having a presenter we create a separate class, PresentationModel, to hold the current state of the UI. The UI class then does nothing but delegate input handling to the presentation model, and synchronize it’s UI elements with the current state exposed by the presentation model. One of the good things about this is that unit tests become easier to write, since there is no need to fake out the view and test the interaction between the view and the presentation model. With the presentation model completely unaware of the view it is also easy to create the presentation logic (in the presentation model) without any view at all while testing.

Some other relevant links that where in some way mentioned in my talk are listed below.

* “Active Record”:http://castleproject.org/activerecord/index.html is a productive way of setting up a data access layer.
* “MonoRail”:http://castleproject.org/monorail/index.html is an MVC-based web framework for the .NET platform.
* Finally, I mentioned the “Agile öresund”:http://mawi.org/agileoresund/ user group that “Marcus Widerberg”:http://mawi.org/ and I are starting up with some others. If you are interested in meeting quite informally to discuss agile topics, please take a look at the wiki.
* And if you missed it in the text above, you can download the demos and presentation I gave in a zipped file.

On behalf of myself and “SNUG”:http://www.snug.se/, I want to thank those who attended the meeting an hope to see you again at the next meeting which will be in February.

Quick should never imply dirty

Posted by Chris on December 06, 2006

My friend and former colleague “Magnus Mårtensson”:http://blog.noop.se/ recently wrote about “his feelings”:http://blog.noop.se/2006/12/02/When+Quick+And+Dirty+Becomes+Just+Dirty.aspx about “YAGNI”:http://c2.com/xp/YouArentGonnaNeedIt.html and how he instead would like us to follow what he calls “GYCFKSTF” (Give Yourself Credit For Knowing Some Things First). I do not quite agree with what he says (but I guess you knew that already Magnus ;) and started to write a comment, but when it became a bit long I decided to post it here instead.

There is nothing in YAGNI (or other things in XP) that says you cannot “give yourself credit for knowing something”. From the C2 page linked above, here is a relevant quote:

bq. This doesn’t mean you should avoid building flexibility into your code. It means you shouldn’t overengineer something based on what you *think you might need later on*.

I do not interpret YAGNI the same way as Magnus does. I definitely agree that there is a need for some balancing critique of popular things such as agile and terms such as YAGNI. But I think that it will be difficult to come to a conclusion when the different sides have such different interpretations of what they are promoting/critizising. The readers will have to decide for themselves which interpretation they agree with.

What I find that Magnus is doing here is taking something he does not really like (YAGNI), looking at it from some angle and/or interpreting it in one way which makes it look like a bad thing, and then saying that this is the essence of that thing, so naturally it is a bad thing.

To me, YAGNI is just XP’s way of implementing the lean principle of deferring decisions until the latest responsible moment. I do not think that anyone can complain about how this principle works for Toyota and other lean (non-software) companies, but at the same time I realize that what I am doing is just the same thing as Magnus. I am looking at something that I like (YAGNI), from an angle that makes it look like a good thing, and saying that this is the essence of that thing, so naturally it is a good thing. Debates like these will never have any winner, but then again I do not think the meaning of debating is winning. By discussing it everyone is a winner, since hopefully we all learn something in the process. :)

On the smaller scale, YAGNI and TDD says that we should try and solve our problem (get to green) as fast as possible, cutting corners while doing so. This might result in us adding a “public IADAL AAccess” property. However, when we are at green we are encouraged to think, to remove duplication and to improve our design. In this case though we might just be happy with our implementation and add the next test, the one for the IBDAL. Since we need to get to green fast, we would again just add the “public IBDAL BAccess” property. However, now we start to see duplication. At this stage we must refactor to improve our design.

If we do not continuously refactor to improve the code and design, everything will turn into a “BigBallOfMud”:http://www.laputan.org/mud/. Therefore I do not agree that YAGNI will turn into YAGFI (You Ain’t Gonna Fix It!). Agile practices require a lot of disciple, more so than any other method I have encountered, and being professional and always thinking about how the code and design can be improved is part of this.

On the slightly larger scale, YAGNI says that we should “Always implement things when you *actually* need them, never when you just *foresee* that you need them.” It does not say anything about how we should implement things (e.g. “you are not allowed to use a generic version!”). I like to think about it as “do not design for future requirements, but do design for flexibility”. So what would be YAGNI then? Lets say that we “know” that in the future the DALAccess class will need to support feature X (maybe serialization or whatever). We “know” this because there is a story that has been created but not selected for this iteration* which will need this functionality. Lets say that we have done this sort of thing lots of times before, so we “know” that by simply creating an IXable interface and letting our class implement that (or maybe even just returning dummy values for now, the important thing is that the architecture is correct, right?) we will be good for the future. Doing this is violating YAGNI. First of all we do not even know if we need the feature. Implementing it, or at least designing for it now, will take unnecessary time and produce code that might possibly be unnecessary in the end. Next is the question of whether or not this design is the correct one. Based on our experience and what we know now we might be able to say that this design is the correct one. However, if we defer the decision to when we actually need the feature we will know even more and be able to make an even better decision.

So, from my positive point of view, YAGNI is a great guideline that helps me create software that is as simple as possible, but no simpler.

*: ~Again, this is an example of how YAGNI makes more sense for anyone really doing XP, since the fact that there exists a story does not even mean it will ever be selected for implementation.~

One assertion per test should come natural

Posted by Chris on November 17, 2006

In an “earlier post”:/articles/2006/10/22/to-setup-or-not-to-setup I mentioned very briefly the _one-assert-per-test-method_ rule. This is something I think originally came from Dave Astels and definitely a guideline that I try to follow. The reason is of course that it helps make tests simpler and more expressive and therefore make them more helpful in locating problems. “Astels also argue”:http://www.artima.com/weblogs/viewpost.jsp?thread=35578 that “_by adding the specification of the behavior one tiny piece at a time, you drive toward evolving the code in small, controllable, understandable steps_”.

Now there might of course be situations when it makes sense to have more than one assert. However, what is important to note about those situations is that they should not change the Arrange-Act-Assert structure of a test. So if there are multiple asserts in a test, they should all be at the end of the test. Definitely do not let your tests become Arrange-Act-Assert-Act-Assert-Act-Assert or similar.

However, even with nicely structured tests, I have come to think of multiple asserts as a kind of smell that the test (or rather the fixture) might not be really thought through. There is one specific situation that I have seen a couple of times where people say that the test is so simple that there is no reason to write it in multiple test methods. Let me show a typical example:

[TestFixture]
public class FooBuilderTests
{
  [Test]
  public void FooIsBuiltCorrectly()
  {
    string fooThis = "foobar";
    string fooThat = "barfoo";
    FooBuilder fooBuilder = new FooBuilder();
    Foo foo = fooBuilder.Create(fooThis, fooThat);

    Assert.AreEqual(fooThis, foo.This);
    Assert.AreEqual(fooThat, foo.That);
  }
}

What we are testing is a simple builder class (FooBuilder) that is used to create object instances of the class Foo. It takes two strings which we expect to be set correctly on the appropriate properties of the Foo instance returned. Simple enough, right? Why would we ever want to create two separate test methods for these two asserts that are so linked to each other?

As I said, I smell something wrong here. And it is very obvious to me what it is. FooBuilderTests is not a good name for a test fixture, or rather the fixture is not a good one. We should not simply have a single “generic” fixture for every production class. What the fixture is all about is setting up everything in a specific state and then testing things in that state. So what would be a better fixture in this case? Look at the setup that is common for the tests that will be in the fixture. How about we call it AFooCreatedByAFooBuilder. This also makes it quite natural to use the setup method of xUnit frameworks, as I discussed in the “post mentioned earlier”:/articles/2006/10/22/to-setup-or-not-to-setup, although it of course works equally well to do setup in a method called directly from the test methods. Here is what this fixture would look like:

[TestFixture]
public class AFooCreatedByAFooBuilder
{
  private Foo foo;
  private string fooThis = "foobar";
  private string fooThat = "barfoo";

  [SetUp]
  public void InitPerTest()
  {
    FooBuilder fooBuilder = new FooBuilder();
    foo = fooBuilder.Create(fooThis, fooThat);
  }
}

With this fixture it becomes quite natural to create two separate tests for the two asserts. Here is the code that goes for the tests:

  [Test]
  public void ThisIsSetCorrectlyOnFooInstance()
  {
    Assert.AreEqual(fooThis, foo.This);
  }

  [Test]
  public void ThatIsSetCorrectlyOnFooInstance()
  {
    Assert.AreEqual(fooThat, foo.That);
  }

If we strive to organize our tests in a fixture oriented approach instead of a per-production-class oriented approach, I think having one assert per test method comes natural. By the way, with Behavior-Driven Development I do not think this would ever be an issue. With the contexts and specifications of BDD we write this way naturally. Even though BDD is not really a lot more than a different wording from TDD, it makes it so much easier to think correctly about writing your tests/specifications.

To setup or not to setup

Posted by Chris on October 20, 2006

Recently I have been trying the “BDD”:http://behaviour-driven.org/
(Behavior-Driven Development) approach to developing software. Normally, when I am doing TDD there are a couple of “house-rules” that I like to follow. These have developed over time, often following advice from either a colleague or other resource.

One such “rule” that has developed over time is that I tend not to use the SetUp and TearDown methods that the xUnit tools have. These are used to execute some piece of setup and/or teardown code before/after every test method is executed. The reason to use these is of course that you might have some code that is needed to setup the system under test, and this setup code tends to be the same for all test methods in a fixture. To keep things “DRY”:http://en.wikipedia.org/wiki/Don’t_repeat_yourself you will naturally want to put this code in a single place and have it executed along with each test. The xUnit tools have different ways of accomplishing this. NUnit for instance uses reflection to find methods marked with the SetUpAttribute in a class and executes them before each test method is executed.

As I started out doing writing unit tests these methods seemed like a great idea. As soon as I learned about them all test fixtures would have them, in fact the first thing I did when creating a new fixture was to add these methods with a “copy-paste template” (or using snippets or similar when they exist). However, after a while a feeling of something being wrong started showing. Discussing the matter with “others”:http://www.taylor.se/blog and doing some “online reading”:http://www.agileprogrammer.com/dotnetguy/articles/SetupTeardown.aspx led me to the conclusion that SetUp/TearDown was *evil incarnated*.

One of the best things about using TDD is that you almost never need to do any debugging. One of the reasons for this is that when you do some modification to your code and then run the tests, if there is anything wrong you will instantly get feedback about it from a red test. You read the name and location (fixture) of the test and take a look at it, and if you have done things right the test will tell you exactly what it does. With this you will hopefully be able to more or less immediately figure out what you did wrong, and fix it. However, if the test is not well written and does not quickly and easily tell you what it does, then you lose this feedback, or at least a part of it. So what has this got to do with SetUp/TearDown? Well, when the test called Foo in fixture Bar blows up on you and you take a look at it, you want to quickly see what it does. If you are using a SetUp method then you will not get the full picture by simply looking at the test. You also need to take a look at the SetUp, and possibly the TearDown (and then TestFixtureSetUp/TestFixtureTearDown if it is really bad). And, of course we must also know that our xUnit tool works this way, since the test method code shows no evidence of a setup method being called. So, instead of using these tools that xUnit gives us, we should instead be refactoring the common setup code into a separate method and then call that method “explicitly” from each test method. That way it is clear when we look at the test method what it does.

Here is an example of a test fixture written this way (in C# using NUnit):

using System;
using NUnit.Framework;
using SystemUnderTest;

namespace SystemUnderTest.Tests
{
	[TestFixture]
	public class AccountWithBalance100_WithoutSetup {
		private Account account;

		private void Init() {
			account = new Account(100);
		}

		[Test]
		public void Depositing50LeavesBalanceOf150() {
			Init();
			account.Deposit(50);
			Assert.AreEqual(150, account.Balance);
		}

		[Test]
		public void Withdrawing50LeavesBalanceOf50() {
			Init();
			account.Withdraw(50);
			Assert.AreEqual(50, account.Balance);
		}

		[Test]
		public void Withdrawing100LeavesBalanceOf0() {
			Init();
			account.Withdraw(100);
			Assert.AreEqual(0, account.Balance);
		}

		[Test]
		[ExpectedException(typeof(ArgumentException))]
		public void Withdrawing101ThrowsException() {
			Init();
			account.Withdraw(101);
		}
	}
}

So, that is the end of that story the, right? Well, I started out this blog entry writing about BDD, not about SetUp/TearDown. So I guess I need to tie this together now. As I said I have been trying BDD instead for a while now. Apart from calling tests specifications and fixtures contexts, there is not a whole lot different between TDD and BDD. At least on the surface, that is. The whole reason to change the terminology is to “force” people in doing TDD the right way. This means using the tests (specifications) to specify behavior, not testing bugs. This means that you will think a bit differently, depending on how you are used to thinking with TDD. It might not be a huge step for all, but for me it has made me reflect a bit.

I did not notice it until after a while, but one interesting reflection I make now is that I do not follow some of my old house-rules when specifying in BDD. Take this example, in “Boo”:http://boo.codehaus.org/ using “Specter”:http://specter.sourceforge.net/:

import System
import Specter
import SystemUnderTest

context "An account with a balance of 100":
	account as Account

	setup:
		account = Account(100)

	specify "Depositing 50 should leave a balance of 150":
		account.Deposit(50)
		account.Balance.Must.Equal(150)

	specify "Withdrawing 50 should leave a balance of 50":
		account.Withdraw(50)
		account.Balance.Must.Equal(50)

	specify "Withdrawing 100 should leave a balance of 0":
		account.Withdraw(100)
		account.Balance.Must.Equal(0)

	specify "Withdrawing 101 should throw an exception":
		{ account.Withdraw(101) }.Must.Throw(typeof(ArgumentException))

This code example shows a typical BDD context and specifications the way I have been writing them. Note the setup part. Specter, the “xUnit tool” I am using here, sees this and executes the setup code before each specification is executed. I used it without even thinking about it. The way the specs are qritten, following the *Given* _an account with a balance of 100_, *when* _a withdrawal of 50 is made_ *then* _there should be 50 left_ style, it seems so natural to setup the context in this way. I suppose it is also largely due to the way specifications is so often written using only a single row, or at least very short.

So, when I made this reflection, I thought that if you write unit tests following the one-assert-per-test-method rule, and of course write short test methods, and (maybe most important of all) create a test fixture per “situation” (or context…), then why should it not feel as natural to use setup here? Here is an example of the same tests as above but this time with the init code moved into a SetUp method.

using System;
using NUnit.Framework;
using SystemUnderTest;

namespace SystemUnderTest.Tests
{
	[TestFixture]
	public class AccountWithBalance100_WithSetup {
		private Account account;

		[SetUp]
		public void Init() {
			account = new Account(100);
		}

		[Test]
		public void Depositing50LeavesBalanceOf150() {
			account.Deposit(50);
			Assert.AreEqual(150, account.Balance);
		}

		[Test]
		public void Withdrawing50LeavesBalanceOf50() {
			account.Withdraw(50);
			Assert.AreEqual(50, account.Balance);
		}

		[Test]
		public void Withdrawing100LeavesBalanceOf0() {
			account.Withdraw(100);
			Assert.AreEqual(0, account.Balance);
		}

		[Test]
		[ExpectedException(typeof(ArgumentException))]
		public void Withdrawing101ThrowsException() {
			account.Withdraw(101);
		}
	}
}

I am not quite finished with my thinking about this, so I am not sure if I think this is better. But I do not think that one of these tests, when blowing up in the test runner, would give me less information than the ones in the example without using the SetUp method. Since I know that the failing test is in the “AccountWithBalance100″ fixture I can easily guess what the variable account holds. But I guess if the setup is more complex then it might not be as easy to name the fixture and/or understand the code.

Comments? Anyone else using BDD that find themselves using setup differently from when doing TDD?

FOR XML EXPLICIT

Posted by Chris on October 09, 2006

A couple of weeks ago I was engaged as trainer for the course “2779: Implementing a Microsoft SQL Server 2005 Database”:http://www.microsoft.com/learning/syllabi/en-us/2779afinal.mspx. The module that was by far the most difficult according to the attendees was the one on xml, with none of them having any practical experience with xml. One of the things that was specifically difficult to understand was the @FOR XML EXPLICIT@ clause to the @SELECT@ statement.

The EXPLICIT mode of the FOR XML clause is to be used when you need to create XML of a specific format that cannot be done with AUTO or RAW modes. You can use EXPLICIT to generate xml of more or less any format you wish. It is also the most complex mode to use. The AUTO and RAW modes are normally used to transform the result of an existing query from a tabular resultset into an xml stream. The key word in that sentence is existing, by which I mean that whether or not you want the results in xml or not you still use the same query. Just add the FOR XML clause and you’re good.

With the EXPLICIT mode it is not that easy. The transformation engine that creates the xml stream from the result of a query requires that the resultset is designed specifically for this task. The concept you must understand is what is called a universal table. This table will have all the information that is needed for the transformation engine to generate xml of the format you require. So what is a universal table then? I think it is easiest to start with an example:

Tag | Parent | Employee!1!Id
 1  | null   | 280

So what does the above mean? First thing to note is the column names. This metadata is used by the transformation engine to create the nodes in the resulting xml output. We must make sure that the query we run (the one we use the FOR XML EXPLICIT clause with) returns a resultset like the one above.

The first two columns must always exist with those names. They are used to describe the hierarchy of elements in the xml output. Every element that should exist in the needs to be represented by a row in the universal table. Every unique “type” of element (ie an element name at a specific level in the hierarchy of the xml fragment) needs to be uniquely idientified by an arbitrary tag number, which is specified in the first column. If the element is nested inside a parent element then the tag number of the parent element should be included in the column for that.

The rest of the column names (in this case only one) specify the names of the nodes in the resulting xml fragment. In our example we have Employee!1!Id. This cryptic combination says that the element tagged with number 1 should be called Employee, and it should have an attribute called Id. Then, for all the rows in the table the value in this column will end up in the Id attribute of element Employee. So the very simple xml fragment we get from the universal table above would look like this:


This is about as much as the course documentation says about FOR XML EXPLICIT and universal tables. Well, it contains a little more but it is quite difficult to see how to use it for more complex examples than what you can easily create with the other modes. So I decided to create an example that does a little more, but still should be quite simple to understand.

Lets say that we have a requirement to produce an xml fragment like the one below.


        
                
                
                ...
        

What we want is an xml fragment describing a specific employee (id=280 in this case) and her customers. The data we need for this can be returned by the following query (run in the AdventureWorks database):

SELECT Employee.EmployeeId Id
	, Employee.LoginID [Login]
	, SalesPerson.SalesLastYear
	, Store.CustomerID CustomerId
	, Store.Name
	, Customer.AccountNumber Account
FROM HumanResources.Employee Employee
INNER JOIN Sales.SalesPerson SalesPerson
	ON Employee.EmployeeId = SalesPerson.SalesPersonId
INNER JOIN Sales.Store Store
	ON SalesPerson.SalesPersonId = Store.SalesPersonId
INNER JOIN Sales.Customer Customer
	ON Store.CustomerId = Customer.CustomerId
WHERE Employee.EmployeeId = 280
ORDER BY EmployeeId, CustomerID

This result includes all the data that should go in the resulting xml fragment. However it does not tell transformation engine how to create it. If we would simply add FOR XML AUTO or RAW we would not at all get the result we want. What we need to do is to create a query that will return a universal table consisting of the data above but in a resultset that includes the metadata needed to create the xml. The following query will do the trick:

SELECT 1 AS Tag
	, NULL AS Parent
	, Employee.EmployeeId AS [Employee!1!Id]
	, Employee.LoginID AS [Employee!1!Login]
	, SalesPerson.SalesLastYear AS [Employee!1!SalesLastYear]
	, NULL AS [Customers!2]
	, NULL AS [Store!3!CustomerId]
	, NULL [Store!3!Name]
	, NULL [Store!3!Account]
FROM HumanResources.Employee Employee
INNER JOIN Sales.SalesPerson SalesPerson
	ON Employee.EmployeeId = SalesPerson.SalesPersonId
WHERE Employee.EmployeeId = 280
UNION ALL
SELECT 2
	, 1
	, NULL
	, NULL
	, NULL
	, NULL
	, NULL
	, NULL
	, NULL
UNION ALL
SELECT 3
	, 2
	, NULL
	, NULL
	, NULL
	, NULL
	, Store.CustomerID
	, Store.Name
	, Customer.AccountNumber
FROM Sales.Store Store
INNER JOIN Sales.Customer Customer
	ON Store.CustomerId = Customer.CustomerId
WHERE Store.SalesPersonID = 280
FOR XML EXPLICIT

As you can see, what we have is a query that is really built up of several queries (three in our case) unioned together. Each query must include all the columns that it needs itself as well as the ones necessary for the other queries. The queries assign arbitrary tag numbers to the three different kinds of elements in our expected output (remember we had Employee, Customers and Store) and also hierarchically arrange them under their direct parent element.

Each of the queries returns the data that is necessary for the elements at a specific depth in the xml tree. For the columns that specify other elements at other depths they just specify null. Note that all the column names are aliased in the first query, since the union operator will use those names for the unioned resultset. Also note specifically how the second query will always return one row and is only used to add the Customers element (that’s why the column name is only two parts and does not include an attribute name) to use as parent for the Store elements.

Unit testing internals

Posted by Chris on October 04, 2006

One of the cool things about Dotway is that we have these “competence weekends” three or four times a year, where we go away to some hotel and geek out about something more or less of technical nature. As “Andrés”:http://www.taylor.se/blog/ mentions recently we spent a weekend “learning about TDD”:http://www.taylor.se/blog/2005/11/24/talking-about-agile/. One of the things that we discussed was how to test code that is not public. Normally you place your tests in a separate assembly and reference the production code. However, that means you need to make types and members public to be able to test them. So if you want to keep the implementation details hidden (with internal access level) you will need to have the tests in the same assembly as the production code. That brings further challenges in setting up the build environment to create different builds, since you naturally do not want to include the tests in the released code.

Today I stumbled upon a .NET 2.0 feature that helps solve this. I was setting up an assembly with attributes and noted one I had not seen before:

@InternalsVisibleToAttribute (string assemblyName)@

That sounded like something interesting, so I decided to try it. I created a new solution and added a class library project called Code to it. I then added a second class library that I named Tests, which referenced Code (and NUnit.Framework). In the AssemblyInfo.cs for Code I added the following:

@[assembly: InternalsVisibleTo("Tests")]@

Now I was ready to start testing. In Code I created two classes, publicclass.cs and internalclass.cs as shown below.

// publicclass.cs
namespace Code {
  public class publicclass {
    internal bool internalmethod() {
      return true;
    }
    public bool publicmethod() {
      return true;
    }
  }
}

// internalclass.cs
namespace Code {
  internal class internalclass {
    public bool publicmethod() {
      return true;
    }

    internal bool internalmethod() {
      return true;
    }
  }
}

In the Tests project I then added InternalsVisibleToTests.cs, shown below:

// InternalsVisibleToTests.cs
using NUnit.Framework;
namespace Tests {
  [TestFixture]
  public class InteralsVisibleToTests {
    [Test]
    public void AccessPublicClassMembers() {
      Code.publicclass foo = new Code.publicclass();
      bool condition1 = foo.publicmethod();
      bool condition2 = foo.internalmethod();

      Assert.IsTrue(condition1);
      Assert.IsTrue(condition2);
    }

    [Test]
    public void AccessInternalClassMembers() {
      Code.internalclass foo = new Code.internalclass();
      bool condition1 = foo.publicmethod();
      bool condition2 = foo.internalmethod();

      Assert.IsTrue(condition1);
      Assert.IsTrue(condition2);
    }
  }
}

As you can see these tests refer to both internal types and members in the Code assembly. The solution compiles and the tests are green!

Even though my libraries often do not need this (most of the stuff is public anyway), it is a very useful technique to have access to. It should be noted of course that this means that anyone can create an assembly named Tests and access the internals in my Code assembly, but there are of course ways around that.

Coming user group meetings

Posted by Chris on October 04, 2006

This Thursday I will be in Stockholm for the “Swedish SQL Server User Group’s (SQLUG)”:http://www.sqlug.se/ final meeting of 2005. The two presentations will be given by none other than Dr. Michael Rys of Microsoft (and member of the ISO standard SQL committee as well as the XQuery committee on W3c)! I saw him at -PDC- PASS and know he is a good speaker so this will be a great meeting.

Then on Monday 12/12 the local .NET user group that I am co-founder of, “Skånsk .NET User Group (SNUG)”:http://www.snug.se/ will have our last meeting for 2005. We have some maybe not as famous speakers but still very interesting presentations to offer; Marcus Widerberg from Dotway will talk about Developing with Generics in .NET 2.0 and then Kim Gräsman from TAC (and C++ MVP) will talk about Continuous Integration and CruiseControl.NET. If you are in the Malmö/Lund/Helsingborg/Köbenhavn area and interested then “take a look at the forums”:http://cs.snug.se/forums/86/ShowPost.aspx#86.

To aggregate or not to aggregera

Posted by Chris on October 04, 2006

I do not think I have yet posted a message that is only meant for Swedish (speaking) readers. Anyway, this post is probably mostly interesting to Swedish-speaking people, but I will keep it in English anyway (except where not possible, as is natural from the following discussion).

A couple of months ago (well about half a year ago actually, don’t know why I haven’t thought about this again until now) I was preparing a presentation on SQL Server 2005 that I was to present at a breakfast seminar at Dotway. Since I was going to speak Swedish I wanted to try and include as little Swenglish as possible (very common in the Swedish IT community otherwise, though usually called ‘Svengelska’ which would be the Swedish ‘translation’ of the ‘English’ word Swenglish). So I was looking to translate as much of the terms I could. But one term where I completely stumbled was _aggregate functions_.

*What do you call Aggregate Functions in Swedish?*

Or more specifically, I was going to describe user-defined aggregate functions in SQL Server 2005, and wanted to avoid Swenglish. To make sure we have the same English definition here, what I mean by an aggregate function is a function that calculates a single value based on a set of values as input. I guess more or less as it is defined in “Princeton Wordnet”:http://wordnet.princeton.edu/perl/webwn?s=aggregate, but with a little more database context to it.

The first one that came to mind was the probably very Swenglish ‘*Aggregatfunktioner*’. To someone familiar with SQL Server it sounds very correct, but I guess that is precisely because they (and I) recognise the English word that is actually in there. And the only definition of the word ‘aggregat’ I have found in Swedish does not provide a lot of help here:

*aggregat* [agreg'a:t Uttal] aggregatet aggregat aggregaten subst.
grupp av sammanbyggda maskiner

A typical use of this is a word like ‘värmeaggregat’ (something like a heater). And that is nowhere near what I am looking for..

Next try was ‘*Aggregeringsfunktioner*’ and immediately after that came ‘*Aggregerande funktioner*’. These feel more Swedish, and the first one is actually used in the “IT word dictionary of PC World”:http://pcforalla.idg.se/tjanster/dataordboken/ (look up ‘aggregera’), as much as you want to use that as a source.. But they still do not sound quite correct (and fully Swedish), and they definitively do not feel right to say. So I actually went ahead and used the Swenglish ‘*aggregatfunktioner*’ in my presentation, which I think worked very well and everyone understood what I meant (in a typically Swenglish fashion).

Today when I somehow came to think about this again I contacted “Jesper Holmberg”:http://blogs.msdn.com/jesperh/ at Microsoft and asked him what he thought about it. Jesper works with the Swedish localization of Windows and other Microsoft products (and possibly more, sorry if I missed something) and has a very interesting blog as well. He was really quick at answering and his suggestion was ‘*mängdfunktioner*’, apparantly the recommended translation at Microsoft (remember other products, such as Excel, have aggregates as well). This is a great translation that really conveys the meaning like I wanted, but unfortunately it feels like noone ever use that word in Swedish. So I fear half of the audience (if I were to give the presentation again) would not realize what I was talking about, at least not immediately. But I do think that I will actually use ‘*mängdfunktioner*’ next time unless I get a better suggestion.

So, anyone with other ideas, please post a comment…