Archive for the ‘Development’ Category

Following on from my previous post I thought it only fair to dive down into the code that was shown in that article and give a bit more of an explanation on what is going on.

First of all, some of you may have looked at the sample code and asked “What is the ContextSpecification class that the ShoppingCartContext is derived from?” – fair question and one that deserves to be explained.

Allow me to digress momentarily in order to try and set the context (for you seasoned BDD’rs – pun intended!). I was first introduced to BDD (indirectly) at a session on coding Katas at TechEd 2010 in New Orleans and BDD was not exactly why I had attended the session. The Behavior Driven aspect of the interactive presentation was very brief and at the time I was left with the desire to know more, so before the End of TechEd party I spent time scouring numerous technical and not so technical sites – looking for further details. What I found was far more than I had bargained for; it wasn’t that the tests were written in a natural language sort of way, it was the idea that the code was being driven via tests that were in turn driven by use cases – OMG!!!! You mean that the requirements analyst directly affects the way the tests are written? I had already bought in to the TDD mindset and to me it had made perfect sense, but this was far beyond what I had bargained for. So in true engineering fashion – I tried it out myself and low and behold it worked (albeit in a very sanitized and benign sort of way). Before we go any further, I would highly recommend that you read Dan North’s Introduction to BDD (http://behaviour-driven.org/Introduction); there you will see that many of us may be fortunate to get to step 4 of the steps to enlightenment. In my case I was there and thanks to the intro to BDD I would get to 6 and hopefully on to step 7.

So there I am trying to implement my first set of BDD tests (before code implementation) and I hit my first stumbling block. The Context Specification Framework I had been introduced to at TechEd, Machine.Specification by Aaron Jensen (http://github.com/machine/machine.specifications), had wonderful plugin capabilities for ReSharper but nothing that I could use inside of MSTest; yes I know, “big deal”, “so what”, blah, blah… Well as much as I love ReSharper, I still prefer to run MSTest as it is what is run in my build environments. Therefore anything that I have difficulty running with MSTest will be an even bigger hassle on my build machines. So off I went again, looking for more jewels in the proverbial rain-forest of information and lo-and-behold I came across Eric Lee’s implementation of a base class that uses MSpec (http://blogs.msdn.com/b/elee/archive/2009/01/20/bdd-with-mstest.aspx) called ContextSpecification. It is a superb abstract class that allows me to easily write my BDD style test classes and thereby drive my code implementation.

Now then, we have the MSpec assembly reference and now an abstract class (ContextSpecification) to derive from and as I am a big fan of RhinoMocks (for generating mocks or stubs), let’s throw that into the mix. With this base we are ready to go do some BDD.

As I have stated before, the Requirements are what drive our tests in BDD; more specifically the creation of Use Cases will drive the tests. So going back to the example in my previous post, we will start with the following requirement:

    A customer can add items to their shopping cart.

Strictly speaking, in SCRUM terms, this should be written as follows:

    AS A Customer

    I WANT to be able to add items to a shopping cart

    SO THAT I can keep a collection of items that I want to buy.

From this user story we can expand the Use Cases (I also consider them as Conditions of Acceptance for the User Story) to give me detail to the high level statement:

Scenario 1: Adding items to an empty shopping cart

  • GIVEN that the shopping cart is empty
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain 1 item

Scenario 2: Adding items to a full shopping cart

  • GIVEN that the shopping cart contains 2 items
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain the 2 existing items and the 1 new item.

I have purposefully capitalized the GIVEN, WHEN and THEN, simply to draw parallels with the AS A <role> I WANT <functionality> SO THAT <benefit> of SCRUM and hopefully highlight the fact that patterns can be drawn from both and thereby help us to create consistent ways in which to write both User Stories and Use Cases.

Now that we have our Use Cases we can start to create our tests. Taking the first scenario we will need to setup a Shopping cart context; which is where we bring in the ContextSpecification abstract class (remember, we don’t have any implementation code yet):

namespace Bdd.Shopping
{
    public class ShoppingCartContext : ContextSpecification
    {
        /// <summary>
        /// The "Given some initial context" method
        /// </summary>
        protected override void Context()
        {
            // setup your class under test
        }
    }

    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestClass]
    public class UnitTest1 : ShoppingCartContext
    {
        /// <summary>
        /// The "When an event occurs" method
        /// </summary>
        protected override void BecauseOf()
        {
            //
            // TODO: Add behavior setup (Action) here
            //
        }

        /// <summary>
        /// The "then ensure some outcome" method.
        /// </summary>
        [TestMethod]
        public void TestMethod1()
        {
            //
            // TODO: Add test logic here
            //
        }
    }
}

Remember that the use case was written as follows:

  • GIVEN that the shopping cart is empty
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain 1 item

The “GIVEN” aspect of the use case is the Context() method of our base class – where we initialize our member variables.

The “WHEN” of the use case will be the TestClass – this will be the container for the THEN aspect.

The “THEN” will be the TestMethod and perform the appropriate assert(s).

Putting all of this together we arrive at the following:

namespace Bdd.Shopping
{
    public class ShoppingCartContext : ContextSpecification
    {
        protected ShoppingCart _cart;
    }

    /// <summary>
    /// Test Class for "WHEN the customer adds 1 item THEN the shopping cart should contain 1 item"
    /// use case.
    /// </summary>
    [TestClass]
    public class when_1_item_is_added_to_an_empty_shopping_cart : ShoppingCartContext
    {
        /// <summary>
        /// The "Given some initial context" method
        /// </summary>
        protected override void Context()
        {
            _cart = new ShoppingCart();
        }

        /// <summary>
        /// The "When an event occurs" method
        /// </summary>
        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem();
            _cart.Add(item);
        }

        /// <summary>
        /// The "then ensure some outcome" method.
        /// </summary>
        [TestMethod]
        public void then_the_shopping_cart_should_contain_1_item()
        {
            Assert.AreEqual(1, _cart.Items.Count);
        }
    }
}

The class name of the TestClass and the method name of the TestMethod help us associate the test with the first use case; “WHEN the customer adds 1 item THEN the shopping cart should contain 1 item”.

In true TDD fashion we have only implemented enough to compile (i.e. absolute minimum of implementation classes) – so this test will fail:

BDD  - Fail First

The next step, of course is to put in the functionality to get the test to pass (TDD mantra – Red, Green, Refactor, Repeat until all test are done). In the case of the implementation classes, we will go from this:

    public class ShoppingCart
    {
        internal void Add(ShoppingItem item)
        {
            throw new NotImplementedException();
        }

        public List<ShoppingItem> Items { get; set; }
    }

    public class ShoppingItem
    {
        public ShoppingItem() {}
    }

To this:

    public class ShoppingCart
    {
        public ShoppingCart()
        {
            Items = new List<ShoppingItem>();
        }

        internal void Add(ShoppingItem item)
        {
            Items.Add(item);
        }

        public List<ShoppingItem> Items { get; set; }
    }

    public class ShoppingItem
    {
        public ShoppingItem() {}
    }

This will give us green in our first test:

BDD  - Then Pass

Now we move on to the next use case:

  • GIVEN that the shopping cart contains 2 items
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain the 2 existing items and the 1 new item.

Here we see that the Use Case is more specific in that it is requiring us to check that the latest item has been added – we will need to add an identifier to the item be able to check against it in our assertion. This will mean that we will need to run our first test again as we will be changing the implementation classes.

First we write the new Test class and associated Test method and do the minimum implementation to get it to compile.

New Test class and Test method:

    [TestClass]
    public class when_1_item_is_added_to_a_cart_containing_2_items : ShoppingCartContext
    {
        private const string NewItemTitle = "Test Driven Development By Kent Beck";

        /// <summary>
        /// The "Given some initial context" method
        /// </summary>
        protected override void Context()
        {
            _cart = new ShoppingCart();
            ShoppingItem item = new ShoppingItem("Behavior Driven Development By Dan North");
            _cart.Add(item);
            item = new ShoppingItem("Agile Software Development with Scrum By Ken Schwaber and Mike Beedle");
            _cart.Add(item);
        }

        /// <summary>
        /// The "When an event occurs" method
        /// </summary>
        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem(NewItemTitle);
            _cart.Add(item);
        }

        /// <summary>
        /// The "then ensure some outcome" method.
        /// </summary>
        [TestMethod]
        public void then_the_shopping_cart_should_contain_the_2_existing_items_and_the_1_new_item()
        {
            Assert.AreEqual(3, _cart.Items.Count);
            Assert.AreEqual(NewItemTitle, _cart.Items[2].Title);
        }
    }

Minimum implementation classes:

    public class ShoppingCart
    {
        public ShoppingCart()
        {
            Items = new List<ShoppingItem>();
        }

        internal void Add(ShoppingItem item)
        {
            Items.Add(item);
        }

        public List<ShoppingItem> Items { get; set; }
    }

    public class ShoppingItem
    {
        public ShoppingItem(string title) {}

        public string Title { get; set; }
    }

When we run the test, the first one will still pass, but seeing as we have done the minimum to be able to compile the second test will fail:

BDD  - Then Fail Again

So therefore the next stage is to make the red go green and “back fill” the correct functionality – to update the implementation class as follows:

    public class ShoppingItem
    {
        public ShoppingItem(string title)
        {
            Title = title;
        }

        public string Title { get; set; }
    }

Now when we run the tests all should be green:

BDD  - Then Pass Again

As we continue we are always aligning our code with the use cases and therefore ensuring that we are adding the business value as intended. With the TDD aspect we are also ensuring that any changes we do to the implementation can be done so with the peace of mind that as long as all of the tests past before we go on to the next use case, we will be building robust code.

As I have said in this blog post and the previous one, BDD is a natural evolution of TDD in as much that it adds the linkage from the tests to the requirements. At a personal level it is also a natural progression in my continuous evolution as a software professional and it helps to consolidate my understanding of the requirements more than any type of review ever could.

Make no mistake, BDD and (especially) TDD are a definite shift in mindset mostly in the idea that the test is written first and you only write enough of the implementation to be able to get the test to pass. This puts the onus on the test being right in the first instance and places more significance on the testing aspect of software development.

  • Share/Bookmark

Although many people may have commented so. I have been drawn in and fired up by Behavior Driven Development (BDD) and through various discussions I have found a great number of non-believers and nay sayers who, strangely enough, don’t truly “get” Agile development either. Strange that, isn’t it? The brick wall I sometimes encounter when trying to get the idea of SCRUM across to certain people is that it is “academic and won’t really work for us”, “we can use facets of it, but the thing as a whole just doesn’t fit”. And in a similar way the same arguments came up when I mention BDD.

So let’s refresh our knowledge on BDD before we go any further. Behavior Driven Development was the brain child of Dan North and he has an excellent article about its evolution on his blog (http://blog.dannorth.net/introducing-bdd/). BDD brings together the Requirements Analyst with the Testers and Developers to start breaking down the stories into use cases (may be known as Conditions of Acceptance in a User Story). So what’s new you may ask? Well, those Use Cases, written in natural language become the definitions of the Test Cases and Unit Tests that will drive the code.

What? Test before Code? Unheard of! Charlatan!

Oh please! Really? Yes folks, BDD is sometimes seen as an extension of TDD (Test Driven Development). TDD pushes the testing to the fore and is used to drive the implementation, so rather than waiting until the code is written to create the unit tests, we now create the unit test and write the code to make the test pass. In my mind I see BDD as TDD on steroids! So how does it work?

Imagine the following (benign and fictitious) requirement:

  • A customer can add items to their shopping cart.

This could be expanded into the following use cases (or conditions of acceptance):

Scenario 1: Adding items to an empty shopping cart

  • Given that the shopping cart is empty
  • When the customer adds 1 item
  • Then the shopping cart should contain 1 item

Scenario 2: Adding items to a full shopping cart

  • Given that the shopping cart contains 2 items
  • When the customer adds 2 items
  • Then the shopping cart should contain 4 items

From this we can derive our test cases and the definition of our Unit Tests. Consider the following code:

namespace ShoppingCartExample
{
    public class ShoppingCartContext : ContextSpecification
    {
        protected ShoppingCart _cart;
    }

    [TestClass]
    public class when_1_item_is_added_to_an_empty_shopping_cart : ShoppingCartContext
    {
        ///

        /// The "Given some initial context" method
        /// 

        protected override void Context()
        {
            _cart = new ShoppingCart();

        }

        ///

        /// The "When an event occurs" method
        /// 

        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem("Behavior Driven Development By Dan North");
            _cart.Add(item);

        }

        ///

        /// The "then ensure some outcome" method.
        /// 

        [TestMethod]
        public void the_shopping_cart_should_contain_1_item()
        {
            Assert.AreEqual(1, _cart.Items.Count);
        }
    }

    [TestClass]
    public class when_2_items_are_added_to_a_shopping_cart_containing_two_items : ShoppingCartContext
    {
        ///

        /// The "Given some initial context" method
        /// 

        protected override void Context()
        {
            _cart = new ShoppingCart();
            ShoppingItem item = new ShoppingItem("Behavior Driven Development By Dan North");
            _cart.Add(item);
            item = new ShoppingItem("Agile Software Development with Scrum By Ken Schwaber and Mike Beedle");
            _cart.Add(item);
        }

        ///

        /// The "When an event occurs" method
        /// 

        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem("Test Driven Development By Kent Beck");
            _cart.Add(item);
            item = new ShoppingItem("The Art of Unit Testing By Roy Osherove");
            _cart.Add(item);
        }

        ///

        /// The "then ensure some outcome" method.
        /// 

        [TestMethod]
        public void the_shopping_cart_should_contain_4_item()
        {
            Assert.AreEqual(4, _cart.Items.Count);
        }
    }
}

I will go in to more detail about the code in a later blog article. For now we will concentrate on the naming of the classes and Test Methods.

Once we have implemented the code that the tests call, we will see the following results:

BDD Unit Test Results

You can now see how the unit test classes relate to the context of the use case (“Given that the shopping cart is empty” with “When the customer adds 1 item“) and the test methods relate to the result criteria (“Then the shopping cart should contain 1 item“).

The beauty of BDD is that it slams the team into instant interaction; there are no ceremonies, burndowns or roles to allow us to ease into the Agile environment; this is an “in your face”, “get on with it” approach and is an Agile technique that can easily be used within the SCRUM framework. This is also the “ugly” part of BDD, individuals may not be comfortable working in this way and this leads to a bigger question of a right fit for those individuals. The benefits of working introducing BDD to your team are obvious:

  • The clarity of requirements are brought to the fore faster than in any other circumstance – if you can’t write the test, then something is wrong with the requirements and the team will spot that as soon as they sit down to work with the requirements analyst.
  • Unit Tests are written from the beginning and make sense to everyone, even the non-technical members of the group can see how well the design is going, just by looking at the unit tests being run (or not).
  • The design is driven from the requirements – as it should be; why would you write code for anything else? Therefore we see a facet of lean.

The adoption of BDD is by no means easy and it can, as stated before, lead to exposing some deficiencies in the team or environment. This in itself may be a good incentive to adopt; hyper-productive teams are driven to succeed by the very nature of their ease in adopting agile techniques and BDD lends itself to those types of individuals.

  • Share/Bookmark

With this being my third TechEd and first in the United States, it was by far the best Technical Conference I have been to so far. And from all of the presentations, technical discussions and sessions, there is one definite difference to all other Microsoft events that I have been to in previous years – the enthusiasm and willingness to engage the technical users on how they are using Microsoft Products. Several years ago I would never have imagined that Microsoft Staff (Program Managers and Technical staff alike) would have been so willing to engage the users and be open to frank discussions and feedback on their work (i.e. the development tools that are VS 2010, TFS 2010 and Lab Management).

Some of the highlights for me were a number of sessions that I attended:

ASI203 | Understanding the Microsoft Application Server: AppFabric, WF, WCF, and More

(David Chapell) – as ever David was insightful with his delivery, this time on the Service AppFabric from Microsoft, to the point that he highlighted the difference and somewhat confusing reference to Service AppFabric and Azure AppFabric.  With some of the demonstrations provided by Ron Jacobs, the session was invaluable for those that are on the fringe of Azure and the concept of Cloud Computing as well as those that are seasoned SOA implementers. The presentation took us from an explanation on AppFabric (Services) showing us the magic of AppFabric Caching; through using WF in conjunction with WCF to provide an alternative to traditional WCF Services; to using Hosting and Caching together to provide a seamless experience for the end user.

DPR206 | Visual Studio ALM: Lessons Learned through Dogfooding

(Brian Harry) – Brian took us through a journey of discovery as he pulled back the covers on the pains and successes that the Developer Division went through during their progress from VS 2005, 2008 and 2010. He highlighted the influence that the division had on shaping the tools that came to be as well as the influence that the process adoption had on the tools as well – specifically SCRUM. From the presentation of statistics on various metrics gathered in all three release and the comparison between them; to the explanation on how the teams breakdown the features into pillars then groups and then deliverables. This presentation is high on my list of favorite sessions.

DPR207 Why Software Estimation is so Painful and How It Doesn’t Have To Be

(Gregg Boer) – Gregg’s presentation took us through familiar territory (in fact all too familiar territory) and certainly provided us with the assurance that we (developers / software engineers) are not mad as hatters. His portrayal of circumstances and roles were spot-on to the point that it was uncanny to see – (has he been in the same meetings as I had?). This illustrative presentation re-assured me that the circumstances one finds one’s self is not unique and certainly is repeated across the majority of Software Development Companies throughout the world.

DEV08-INT Using Microsoft Visual Studio 2010 to Understand Your Applications

(Mark Groves and Suhail Dutta) – Mark and Suhail’s demos into how to utilize the features of the Architecture tools were very helpful even to someone who has spent sometime playing around with them in the months leading up to Beta and RC. The demonstrations of Layer Diagrams and UML Diagrams were useful to highlight the very important addition of Architectural tools that have been longed for by many in the development community – I for one am seriously ecstatic for such possibilities that can be incorporated into the build. Just the fact of being able to validate the integrity of the architecture in each build is in itself a major improvement and cannot be understated.

DPR03-INT | Increasing Your Productivity Using Code Katas

(David Starr and Ben Day) – apart from a very interesting topic, the chemistry between the two presenters made for good entertainment (especially their different viewpoints on Bowling – Ten Pin or Candlestick). David and Ben took us on a live ride from the start of a unit test through the cycles of code, test, refactor and showed us a very useful way for developers to stay on top of their game. In fact I was so buzzed I started to use the technique there and then, following David as he walked us through the problem solving exercise. I would highly recommend any serious developer interested in TDD to utilize the technique.

DPR204 | Top 10 Mistakes in Unit Testing

(Ben Day) – Ben covered a topic that was very close to my heart and did not disappoint in the least. In fact not only did he have the 10 mistakes listed, but even provided a further 4 more. Ben’s approach to the topic was very much along the lines of TDD and covered the many pitfalls that people face when embarking on unit testing. Although his ordering was not exactly the same way as I would have perceived it (he did say that they were not in a particular order); he definitely covered the aspects of mistakes made in taking on Unit Testing and showed us some prime examples along with tips on how to avoid the pitfalls.

DEV403 | Building Extensions for the Microsoft Visual Studio Architecture Tools

(Peter Provost) – Peter peeled back the covers on the extensibility of VS 2010 and showed us a glimpse of what is possible with the extensions in the Architecture Tools. Some of the methods by which we can extended the tools varied from the sublime (copying files to a specific folder) to the more subtle and elegant such as writing custom code and deploying them. My only frustration was not to have my MSDN information to hand to be able to download the Feature Pack; however as soon as I am back at the office I shall be trying it out. Combining this session with Mark and Suhails (DEV08-INT) gives a complete picture in to just what we can do with the Architecture tools of VS 2010.

I could go on and on about the sessions that I attended, but the biggest take away from this TechEd is the advancement that Microsoft has made in their Developer tools and how much they have listened to and involved the development community. From the obvious presence of Agile practices in many of the presentations to the technologies and tools available, I was not disappointed by the content and in fact I would go as far as to say – a very grateful thank you from this individual for moving us (in my mind) in the right direction for software development.

  • Share/Bookmark

At long last (On a couple of levels I have to add)!

First and foremost – after a long absence from blogging due to a life-changing event (i.e. recent addition to the family) I have managed to write up an article that has been on my mind since June last year! Secondly, because I finally managed to get the example to work – after months of on and off attempts I had been blocked by a very silly and obvious issue (more later) and this evening I managed to concentrate and see it through.

So what’s the big deal?

My desire was to write a blog explaining the beauty of using POCO from EF 4.0 all the way up through WCF to a client application. I had naively assumed that it would be a straightforward case of building the EFDM, creating my POCO classes, create the appropriate Context Interface (see my earlier blog article on creating an appropriate Context Interface) and then write the WCF service to use the EFDM and expose the same POCO classes to the client – how naïve!

The issue actually came up when I tried to pass the EF “filled” POCO classes back through the WCF service. Bang! I got stumped with the following exception:

System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Although I had the WCF Tracing enabled; I couldn’t for the life of me figure out what it was. Finally after digging through fresh traces I read carefully what the buried exception was:

There was an error while trying to serialize parameter http://tempuri.org/:GetDiverResult. The InnerException message was 'Object graph for type 'DiveLogger.Base.DataContracts.DiveProfile' contains cycles and cannot be serialized if reference tracking is disabled.'.  Please see InnerException for more details.

Of course! How silly of me! It was the fact that the navigation properties of my entities were actually causing cyclic references. Now there was a couple of ways I could do this.

  1. Scrutinize my navigation properties and make sure that the return reference properties were made private (this way the XML Serialization of WCF would overlook it as they would be POCO (i.e. no DataContract attributes here!) – it does work as I tried it out for a laugh.
  2. Utilize the blogged “Cyclic References Aware Contract Behavior” derived from IContractBehavior example. This would allow me to pass my POCO class through un-changed and not cause an exception (that would shutdown my service connection unexpectedly).

In the attached code example I have used the second option as I want to try and demonstrate how we can go from Data Model through EF context to the client via a WCF Service, without decorating our class with any special attributes or referencing any EF or Serialization classes – i.e. real to goodness POCO!

As my regular readers will recognize by now that my reason for being so excited about this (apart from the ability to inject interfaces and have my separation of concerns) is for the all important Unit Tests – after all what fun would it be?

The idea of this exercise was to show that with .NET 4.0 we can now release our bonds to specific assemblies / classes and have truly lightweight classes. Consider how pre-4.0 would have been done:

POCO through technology stack

Each layer would have involved some form of transformation from one type to another simply to avoid issues with the associated technology stack.

Consider the “new” way with .NET 4.0:

POCO through technology stack

Now we don’t have to do any transformation from one type to another because the same type is used all the way up the technology stack without any issues (except for the one described earlier).

So how was it done?

The following steps will guide you through the process:

1. Define our POCO classes according to our Data Model:

[POCO classes]

POCO Definition

[Data Model]

EF Data Model

2. Remove the Custom Tool from the DataMapping properties
(so that we can use POCO):

EFDM Custom Tool

Effect of removing EFDM Custom Tool

3. Define the Context Interface that will become the injection point in future references to the DAL:

    public interface IDiveLoggerContext
    {
        IObjectSet AccessTypes { get; }
        IObjectSet CertificationTypes { get; }
        IObjectSet DiveProfiles { get; }
        IObjectSet Divers { get; }
        IObjectSet DiveSites { get; }
        IObjectSet SurfaceTypes { get; }
        IObjectSet WaterBodyTypes { get; }
    }

And implement it

Implement Context Interface

4. In a WCF project define the Service Interface (we will not decorate the DataContracts as they are POCO):

namespace DiveLogger.Service
{
    [ServiceContract]
    public interface ILoggerService
    {
        [OperationContract]
        Diver GetDiver(int id);
    }
}
5. Create the CyclicReferencesAwareContractBehavior, CyclicReferencesAwareAttribute and ApplyCyclicDataContractSerializerOperationBehavior classes as described in Chabsters blog (WCF Cyclic references support). Obviously if there are no cyclic references in any of our entities, then chances are you will not need to put in this workaround for WCF 4.0.

Cyclic Reference Treatment Classes

And use it on the Service contract

Use CyclicReferencesAware attribute

Now the XmlSerialization can handle those pesky cyclic reference Navigation Properties and our WCF Service will work.

6. Utilize the Context Interface we created earlier to separate the DAL from the Service:

    public class LoggerService : ILoggerService
    {
        private IDiveLoggerContext m_context;

        public LoggerService()
        {
            Initialize(null);
        }

        internal LoggerService(IDiveLoggerContext i_context)
        {
            Initialize(i_context);
        }

        private void Initialize(IDiveLoggerContext i_context)
        {
            m_context = i_context ?? new DiveLoggerContext(UtilityFunctions.BuildAdoConnectionString(null));
        }

        public Diver GetDiver(int id)
        {
            if (id < 1 || id > 999)
                throw new ArgumentOutOfRangeException("Diver ID needs to be between 1 and 999", "id");

            IQueryable query = from diver in m_context.Divers
                                      .Include("CertificationTypes")
                                      .Include("DiveProfiles")
                                      .Include("DiveProfiles.DiveSite")
                                      .Include("DiveProfiles.WaterBodyType")
                                      .Include("DiveProfiles.AccessType")
                                      .Include("DiveProfiles.SurfaceType")
                                      where diver.Id == id
                                      select diver;
            Diver retVal = query.ToList().SingleOrDefault();
            return retVal;
        }
    }
7. In our Unit Test we can mock out the Context Interface instead of generating an actual instance:

    [TestMethod]
    public void TestGetSingleDiver()
    {
        // - ARRANGE -
        // Create the stub instance
        IDiveLoggerContext context = MockRepository.GenerateStub();

        // define/create dummy data
        int id = 500;
        string firstName = "Sherlock";
        string lastName = "Holmes";
        string title = "Mr.";
        IObjectSet divers = TestHelper.CreateDivers(id, firstName, lastName).AsObjectSet();

        // declare instance that we want to "retrieve"
        Diver individual;

        // Explicitly state how the stubs should behave
        context.Stub(stub => stub.Divers).Return(divers);

        // Create a real instance of the Servcie that we want to put under test, injecting the dependency in the constructor
        LoggerService service = new LoggerService(context);

        // - ACT -
        individual = service.GetDiver(id);
        // - ASSERT -
        // Make absoultely sure that the expected excption type was thrown
        Assert.IsNotNull(individual);
        // Make sure that the method was NOT called.
        context.AssertWasCalled(stub => { var temp = stub.Divers; });
    }

This will mean that we can get more realistic code-coverage on our Service:

Code Coverage

The following zip file contains all of the classes and code mentioned in the steps outlined previously:

Divelogger.zip

  • Share/Bookmark

Many times a custom tool that is created to overcome a particular “issue” ends up morphing into something that is greater than the initial idea. Case in point, I had come across many instances where the sheer bulk of Sprint Backlog Items that had to be entered in to TFS almost made me break out in to a cold sweat – it is an arduous task to do it via the Team Explorer Window when you are doing the entries one by one:

TFS Sprint Backlog Item

So, typically for large volumes of Sprint Backlog Items I would prefer to use the Export to Excel capability of a TFS WorkItem Query:

Export To Excel

I could then enter the bulk of Sprint Backlog Items entering the required data in each row (representing each SBI) and then use the Publish feature of the TFS Excel Team Add-In:

TFS Excel Add-In Publish Change

The only issue with this approach is that I’d have to go back and link each SBI in Team Explorer with the correct PBI!

So I created an Add-In to overcome this. At first the Add-In would only pull back the PBI Id and Title and allow the user to type in a new PBI Id and publish the link information, but then I realized it would be great (for planning purposes) to be able to pull back whatever field from a PBI that I wanted. So I created a mapping between the PBI Field name and a Column name that the user would type in to Excel (the red shows the mapping from the Excel Column text; the purple shows the mapping from the TFS Template definition for a Product Backlog Item:

JasPWarE TFS Excel Add-In Mapping

I can then pull back whatever I like and be able to see how it relates to the list of Sprint Backlog Items I have. I also created an informative video to illustrate how to use the add-in.

You can get the latest version from:

http://www.petrellyn.com/jaspware/ExcelTfsAddIn

  • Share/Bookmark

Recently I had been working on creating Sprint Backlog Items in Excel and then using the Team Explorer add-in for Excel to publish the changes back to the TFS server. It was great to be able to view tasks in Excel and update similar tasks through a spreadsheet manner rather than swapping back and fourth in Team Explorer of Visual Studio. The only issue was the linking to Product Backlog Items; there wasn’t any way to link the published SBI with appropriate Product Backlog Items – it meant I would have to go back to Team Explorer and do it through there. I had already worked on an Excel add-in to calculate work remaining for each team member:

Excel Capacity Worksheet

The functionality behind this feature is based on certain fields being defined in the SCRUM template (Estimated Effort (Scrum), Work Remaining (Scrum)). The Excel Add-In exposes Formulas that can be utilized within a cell:

GetTotalHoursRemaining Excel Formula

GetTotalHoursRemaining() provides the calculation of Total hours remaining in a given Sprint for one or more team members:

GetTotalHoursRemaining Excel Formula

Returning to the problem at hand, I realized that it would be simple enough to add functionality into the existing Add-In to be able to “pull” the PBI links down to the sheet and even “push” new links back up to the server; after all each PBI has an ID that can be represented as text, and the process of adding a link to any TFS WorkItem is accomplished through the following call:

workItem.Links.Add(new RelatedLink(linkId));

With a constructor signature for a RelatedLink instance accepts an int:

RelatedLink(int relatedWorkItemId)

This meant that I could scour the ID column of the Sprint Backlog Item in Excel and can pull off the IDs as integers, then scouring the column that had the Product Backlog Item IDs I could update the Sprint Backlog Item internal Links:

Sprint Backlog Item ID Column

By adding a further column (in the Spreadsheet) that can be identified by the Add-In I could pull or push the links to the Product Backlog Items:

Refresh TFS Item Links

I created a simplistic installer (it makes assumptions that you are running Office 2007 and that you are using a suitable template such as the Conchango SCRUM for TeamSystem):

http://www.petrellyn.com/jaspware/ExcelTfsAddIn/index.php?lang=eng

  • Share/Bookmark

On several occasions I have come across instances where people have mistakenly called the interface that a Service implements, the Service itself. The truth of the matter is that the Service can be formed by a number of interfaces (referred to as Service Contracts), each of which contain various methods (referred to as Operation Contracts) returning or receiving simple or complex data (referred to as Data Contracts). Consider the following example:

Example WeatherService

Example WeatherService

From a “traditional sense” it represents a class that implements two interfaces – now hold that thought.

Consider the same example from a Service point of view through the convention used by Thomas Erl:

Thomas Erl style Service Diagram

Thomas Erl style Service Diagram

Two Service Contracts (ITemperature and IRainfall) are defined as follows:

    ///

    /// ServiceContract that provides temperature information.
    /// 

    [ServiceContract]
    public interface ITemperature
    {
        ///

        /// Retrieves the temperature for a specified location given the Latitude and Longitude
        /// 

        /// <param name="location">Location information for retrieving Temperature.</param>
        /// Temperature of location.
        [OperationContract]
        double GetTemperature(Location location);
    }

    ///

    /// ServiceContract that provides rainfall information.
    /// 

    [ServiceContract]
    public interface IRainfall
    {
        ///

        /// Retrieves the rainfall for a specified location given the Latitude and Longitude
        /// 

        /// <param name="location">Location for retrieving Rainfall.</param>
        /// Rainfall of the given location.
        [OperationContract]
        double GetRainfall(Location location);
    }

Where Location is the DataContract defined as:


    ///

    /// DataContract that represents a location specified by its Latitude and Longitude.
    /// 

    [DataContract]
    public class Location
    {
        ///

        /// Gets / sets the Latitude of the location.
        /// 

        [DataMember(IsRequired = true)]
        public double Latitude { get; set; }

        ///

        /// Gets / sets the Longitude of the location.
        /// 

        [DataMember(IsRequired = true)]
        public double Longitude { get; set; }
    }

The class that implements them, WeatherService, is defined as:


    ///

    /// ServiceContract implementation class
    /// 

    public class WeatherService : IRainfall, ITemperature
    {
        ///

        /// Retrieves the rainfall for a specified location given the Latitude and Longitude
        /// 

        /// <param name="location">Location specific information for retrieving Rainfall.</param>
        /// Rainfall of the given location.
        public double GetRainfall(Location location)
        {
            return _GetRainfall(location.Latitude, location.Longitude);
        }

        ///

        /// Retrieves the temperature for a specified location given the Latitude and Longitude
        /// 

        /// <param name="location">Location specific information for retrieving Temperature.</param>
        /// Temperature of location.
        public double GetTemperature(Location location)
        {
            return _GetTemperature(location.Latitude, location.Longitude);
        }

        private double _GetTemperature(double latitude, double longitude)
        {
            return new Random().NextDouble();
        }

        private double _GetRainfall(double latitude, double longitude)
        {
            return new Random().NextDouble();
        }
    }

So now when we refer to a Service we are talking about the implementation of one or more ServiceContracts (as in the case of the Weather Service). One developer may be working on a single ServiceContract that the Service implements (such as ITemperature) but it does not necessarily mean that they are working on the whole of the Service.

  • Share/Bookmark

Visual Studio 2010 - Beta 2

Whilst preparing for my Entity Framework 4.0 and Unit Testing presentation at the recent New England Code Camp, I came across an issue with my code that I couldn’t entirely understand. Picture the scenario:

In Visual Studio 2008 utilizing EF 1.0:

  • Create a repository Assembly that contains the model and entity classes (i.e. no POCO) for a group of tables in my DB
  • Create a Manager class to expose public functions / methods to retrieve data from the DB via the EntityContext
    [store the Manager.cs file in a common area and create a Link to it from the project].
  • Create an extension method that will handle the usage of Lambda expressions inside the context of .Include() [Did I say I hate "magic strings"?]
    [store the ObjectQueryExtension.cs file in a common area and create a Link to it from the project]
  • Create a simple Console app to call the methods on the Manager class
    [store the Program.cs file in a common area and create a Link to it from the project].

Visual Studio 2008

In Visual Studio 2010 Beta 2 utilizing EF 4.0:

  • Create a repository Assembly that contains the model and entity classes (i.e. no POCO) for a group of tables in my DB
  • Create a Manager class to expose public functions / methods to retrieve data from the DB via the EntityContext
    [create a Link to the Manager.cs file from the project in a common area].
  • Create an extension method that will handle the usage of Lambda expressions inside the context of .Include()
    [create a Link to the ObjectQueryExtension.cs file in the common area from the project]
  • Create a simple Console app to call the methods on the Manager class
    [create a Link to the Program.cs file in the common area from the project].

Visual Studio 2010 - Beta 2

As you will see, the only difference between the two solutions is the actual EntityFramework context definition; one utilizes EF 1.0 and the other EF 4.0.

Compile and execute both and it works perfectly, same Program.cs code for both (making the Console Application); same Manager.cs and ObjectQueryExtension.cs code for both (making the RepositoryManager assembly).

Now the fun starts. I then worked my way back to using Dependency Injection and created the unit test methods based on the VS 2010 project described above. When the compiler attempts to compile the following section of code:


IQueryable<Person> query = context.PersonSet
                               .Include(p => p.PersonalDetail)
                               .Include("FavoriteBeers.Beer")
                               .Include(p => p.Customer.Include<Customer, CustomerType>(c => c.CustomerType))
                               .Include(p => p.Addresses);

The following compile error was the result of the attempted compilation against the preceding code:


Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,53): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,58): error CS0311: The type 'EFWorkshop.Poco.Base.Entities.Customer' cannot be used as type parameter 'TSource' in the generic type or method 'EFWorkshop.Ef.Repository.ObjectQueryExtension.Include<TSource,TPropType>(TSource, System.Linq.Expressions.Expression<System.Func<TSource,TPropType>>)'. There is no implicit reference conversion from 'EFWorkshop.Poco.Base.Entities.Customer' to 'System.Data.Objects.DataClasses.IEntityWithRelationships'.
Ef4.0AndEf1.0\Common\ObjectQueryExtension.cs(118,33): (Related location)
Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,60): error CS1061: 'System.Linq.IQueryable<EFWorkshop.Poco.Base.Entities.Person>' does not contain a definition for 'Customer' and no extension method 'Customer' accepting a first argument of type 'System.Linq.IQueryable<EFWorkshop.Poco.Base.Entities.Person>' could be found (are you missing a using directive or an assembly reference?)

However, the following “magic string” laden Includes compile and execute fine:


IQueryable<Person> query = _context.People
    .Include("FavoriteBeers.Beer")
    .Include("PersonalDetail")
    .Include("Customer.CustomerType")
    .Include("Addresses");

Therefore it would seem that the non POCO based classes permit us having the Lambda expression based includes as described earlier; however the moment that POCO is introduced that style of Include is no longer viable – or is it?

  • Share/Bookmark

Wow – June 24th was the last entry! First of all I need to apologize for my bad blogging; I have no other excuse except for the volume of work AT work. Sure I could have re-prioritized and it may have made a difference, but I don’t think my employer would have been very pleased.

So, New England Code Camp, Microsoft Offices, Waltham, MA – full information can be found at http://www.thedevcommunity.org/Events/PresentationList.aspx?id=13. Today I am giving two presentations:

Using Entity Framework’s New POCO Features: Part 2 (Unit Testing)

Level: Intermediate

Starts: Oct 17 2009 2:50 PM

Ends: Sep 17 2009 4:05 PM

Room: MPR A

Speaker: James Phillips

In many cases Unit Testing is considered a chore rather than another development task and often ends up being the last task in a development cycle. More often than not, the sheer work involved in preparing unit tests for existing code can lead to the production of Integration Tests rather than true Unit Tests. Where a unit of code that is under test relies on an external resource, such as a Database or Configuration file, the dependency can lead to testing of the underlying mechanism as well as the unit being tested. This was especially true with Entity Framework 1.0 shipped with .NET Framework 3.5 Service Pack 1. With the advent of .NET Framework 4.0, the Entity Framework has advanced in favor of better Unit Testing with the use of POCO and the ability to create interfaces based on IObjectSet. This presentation will cover the examples that can lead to true Unit Testing as opposed to Integration Testing and provide valuable feedback metrics such as code coverage and automated build time reporting of results.

SCRUM and TFS

Level: Introductory

Starts: Oct 17 2009 4:10 PM

Ends: Sep 17 2009 5:25 PM

Room: Rhode Island

Speaker: James Phillips

SCRUM has grown in popularity and acceptance by many companies over the world with numbers of registered SCRUM Masters reaching 51,955 (11 March 2009 – Jeff Sutherland). Although SCRUM does not stipulate what tools to use to produce the necessary artifacts, Microsoft Team Foundation System provides a number of features via TFS Explorer that facilitate capturing the artifacts of SCRUM and is a useful tool for any SCRUM Master, Team and Product Owner. This presentation will highlight the SCRUM framework and show you practical use of TFS and other tools that facilitate the ceremonies and artifacts of SCRUM.

The slides and code are available for download here:

SCRUM_And_TFS.zip

EF_POCO_And_UnitTesting_slides.zip”

EF_POCO_And_UnitTesting_code.zip

EF_POCO_And_UnitTesting.zip

  • Share/Bookmark

After publishing the blog article on Mocking in EF 2.0, Diego Vega (Microsoft Program Manager Entity Framework and LINQ to SQL Product Teams in Redmond) pointed out that the following code snippet is quite inefficient:


    var customers = (from cus in _context.Customers
                    where cus.CustomerID == i_customerId
                    select cus);
    if (customers.Count() == 1)
    {
        o_customer = customers.Single<Customer>();
    }
    else
    {
        o_customer = null;
    }

It turns out that even though the expression does not change between the call to customers.Count() and customers.Single<Customer>(), they will actually cause two calls to the Database. I had mistakenly assumed that the result would be cached as there was no change to the “query”.

By using the SingleOrDefault<T>() function that is now available in EF 2.0 (through IQueryable<T>) we actually save on the round trip.


    o_customer = (from cus in _context.Customers
                    where cus.CustomerID == i_customerId
                    select cus).SingleOrDefault<Customer>();

Something to bear in mind when working with IQueryable<T>.

a2dbm5vn79

  • Share/Bookmark