Far Away Developer

Sebastien Lachance

Archive for the 'Agile' Category

Agile Software Development

Ohhh, that’s why I should make a TestRepository…

Posted by Sebastien Lachance on May 14, 2008

Listening to the last screencast of Rob Conery (MVC Storefront) made me realize something that I haven’t really understood before.

Suppose you have the interface of a repository, let’s say IEntryRepository. Then you have the actual SqlEntryRepository and TestEntryRepository. When I am doing TDD, I am testing the TestEntryRepository. But it will not be used in production. Why bothering with testing it then?

Because TDD is a design process. Even if I am testing my code, I am also designing it. The SqlEntryRepository will benefits from the actual design of the repository we use for testing.

 

Technorati Tags: ,,

Posted in ASP.NET MVC, Agile, Design, Learning, Tests | 2 Comments »

Alt.NET Podcast

Posted by Sebastien Lachance on May 14, 2008

I have just finished listening to the first episode of a new podcast. It’s a discussion about self-improvement for developer with Chad Myers, David Laribee and Jeremy D. Miller. It’s very inspiring and I recommend that you listen to it if you are serious about software development.

Alt.NET Podcast

Posted in Agile, General, Learning | No Comments »

Mocking the HttpRequest in ASP.NET MVC (April build)

Posted by Sebastien Lachance on May 12, 2008

Like promised, on a previous post, I will show you how to mock HttpRequest. I will use Rhino Mock but you can use the one you want (moq, typemock, etc).

On you controller base class, a property called Request is exposed. Behind the scene you are accessing an HttpContextBase instance (this class is contained in the System.Web.Abstractions library), which is providing you the HttpRequest you want to mock.

So, let’s start by creating a mock of these two object.

var mocks = new MockRepository();
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();

 

The mockedHttpRequest will be provided by the mockedHttpContext. So we will setup the mocked HttpContextBase.Request property to return the mocked HttpRequestBase.

SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);

 

But, what would we do with a mocked HttpRequestBase? When you need to test an action on a controller that will retrieve values for the Request.Form property you could create a NameValueCollection and tell the Form property of the HttpRequestBase instance to return it.

NameValueCollection formParameters = new NameValueCollection();
formParameters.Add("txtUsername", "username");
formParameters.Add("txtPassword", "password1");

SetupResult.For(mockedHttpRequest.Form).Return(formParameters);

 

I really like playing with the ASP.NET MVC framework!!!

Posted in .NET, ASP.NET MVC, Learning, Tests | No Comments »

Mocking the HttpContext in ASP.NET MVC

Posted by Sebastien Lachance on May 8, 2008

I just got a hard time figuring how I could be mocking the HttpContext so that I would be able to mock HttpRequest. But once you understand the principle, it is fairly easy.

First thing we need to know is that the HttpContext is held inside a ControllerContext object. Once we have instantiated one, we can then put it inside our controller.

controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
 
Where mockedHttpContext is your mocked HttpContextBase object.
 
Inside the HttpContextBase object reside a lot of useful stuff that can replace with our mocks. By example, the HttpRequest, HttpServer, HttpApplication, etc, are all contained inside. So, getting familiar with this basic knowledge is a must to do testing usefully.
 
Next post : Mocking HttpRequest.Form to return what we want.

Posted in .NET, ASP.NET MVC, Learning, Tests | 1 Comment »

Testing controllers in ASP.NET MVC aka ActionResult

Posted by Sebastien Lachance on May 6, 2008

I haven’t really done any testing in ASP.NET MVC until now. I started the development of a more serious application and decided to do it TDD. My first test was to make sure the Index action render the Index view. So as an informed developer, I started reading some blog posts to discover that in order to test a controller you need to mock a lot of things. I followed the screencast of Scott Hanselman and implemented his MvcMockHelper. It didn’t worked. The ViewContext on the view engine remained null, resulting in an NullReferenceException. I downloaded the source of the last build to see for myself what was wrong. Surely I don’t understand, because nowhere in the source they are setting the ViewContext on the ViewEngine. They just fill a RenderViewResult object and return it back.

This is how I figured out how we can now test controllers. With the new Interim build of the 04/16, we don’t have to mock the HttpContext, HttpRequest and so on anymore. No need to do a fake view engine and no more mocking needed to test the RenderView method.

[Test]
public void Index_Should_Set_The_Index_View()
{
    EntryController controller = new EntryController();
    var result = (RenderViewResult)controller.Index();

    Assert.That(result.ViewName, Is.EqualTo("Index"));
}

So if you have any other operations (RedirectToAction and Redirect for example), it will return an object of type ActionResult that you can cast to the appropriate inheritor (RenderViewResult, ActionRedirectResult, HttpRedirectResult) to get a lot of information that you would have to retrieve manually with a mock.

I really like the simplicity of it and can’t wait to see more improvement. This is an immense opportunity to learn a great deal of different things.

Posted in .NET, ASP.NET MVC, Learning | 1 Comment »

Quick Start with ASP.NET MVC 0406 MVC Interim Source Code Release

Posted by Sebastien Lachance on May 6, 2008

This is intended to be a quick start for anyone who want to start playing with the latest version of ASP.NET MVC without going through the origin and goals of the MVC pattern. I will use the ASP.NET 0416 MVC Interim Source Code Release for this. Keep in mind, that this will probably all change in a near future.

First step, download and build the source. You will need to have the Moq library (more about this mocking framework in a future post).

Second, download and install the Visual Studio MVC Templates (execute the vsi file).

Third, start an ASP.NET MVC project.

I have two useful resources to share with you. I believe they will give you a head start.

You have the Scott Hanselman’s screencast series on the ASP.NET web site. And you have the MVC Storefront series from Rob Conery.

Posted in .NET, ASP.NET MVC, Agile, Learning | No Comments »

The importance of database versionning

Posted by Sebastien Lachance on March 12, 2008

2-3 months ago, I have deployed the application I was working on the client. Since then a lot of changes have been made and I did not work on this project. The database changed significantly but the sql script have not been updated with the latest changes. Now, I have to get back on the project to make an update to the client. I can generate a new set of scripts to create a new database, but how am I suppose to update the production database …

Before I left, I gave instruction on how to version every changes to the database. I wanted to have scripts with every changes that have been made and then run them on the client on future update.

Let’s see the pros and cons of not doing so :

PROS :

  • Save time when developing

CONS :

  • No way to easily update an existing database
  • Loose time trying to figure out what is changed
  • No confidence that you will update the existing database correctly
  • No way to get back in time if needed

Please, version your sql script! It will be much easier for those doing the futur work.

Posted in Agile, Continuous Integration, Learning | 1 Comment »

WHILSOF : Getting started with NHibernate

Posted by Sebastien Lachance on March 3, 2008

Without digging in too much detail about NHibernate, I will presume you are familiar with what this O/R Mapper can do.

The application configuration file :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="hibernate.dialect">NHibernate.Dialect.MsSql2005Dialect</property>
      <property name="hibernate.connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="hibernate.connection.connection_string">Server=.SQLEXPRESS;Initial Catalog=RecipeHelperTest;User Id=recipeuser;Password=recipeuser;</property>
      <mapping assembly="RecipeHelper.Domain" />
    </session-factory>
  </hibernate-configuration>
</configuration>

This is standard stuff that you can find in the documentation. One interesting point however is the mapping. You can specify where your domain object to be persisted are. This will allow you to not worry about specifying them in code.

Creating a mapping file :

To be able to persist your entities, you’ll need to create a mapping file. In my opinion, this is the hardest thing to learn about NHibernate. But don’t worry, it is well documented.

The strategy I am using is one file per entities, in the same assembly. I also use the same name with the extension “.hbm.xml”. The trickiest part is that you need to set the Build Action to “Embedded Resource“. Once all this is completed you can now start writing your mapping information :

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="RecipeHelper.Domain" namespace="RecipeHelper.Domain" default-lazy="false">
  <class name="Recipe" table="Recipes" >
    <id name="ID" column="ID" type="int" access="field.lowercase-underscore">
      <generator class="native" />
    </id>
    <property name="Name" column="Name" type="string" not-null="false"/>
    <property name="Reference" column="Reference" type="string" not-null="false" />
    <property name="Rating" column="Rating" type="int" not-null="false" />
  </class>
</hibernate-mapping>

Preparation for using NHibernate :

The biggest performance hit is the creation of the ISessionFactory. For this reason, it should only be instantiated once. I created a singleton that will allow me to have access to a single session factory.

using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace RecipeHelper.Domain
{
    public class NHibernateConfig
    {
        private static ISessionFactory _sessionFactory;

        static NHibernateConfig()
        {
            Configuration config = new Configuration();

            _sessionFactory = config.Configure().BuildSessionFactory();
        }

        public static ISessionFactory GetSessionFactory()
        {
            return _sessionFactory;
        }

    }
}

Conclusion :

This isn’t a complete tutorial to get started with NHibernate but should cover the essential steps to prepare your project to use it.

Posted in Agile, Learning, Tools | No Comments »

WHILSOF : ReadOnlyCollection<T>

Posted by Sebastien Lachance on February 26, 2008

Problem :

I have a collection of entities in my repository. Those entities are not supposed to be visible to the outside world. But, In a test I am supposed to see if all objects are still there and I can’t use the GetAll method because it goes to the database and return everything, not just the collection of entities in my repository.

Solution :

I could expose the collection but how can I be sure that nothing will be changed. I could create a copy of the collection but that would not reflect the “Entity” concept. I know that Java has support for returning a read-only collection. A little bit of search and I found the class ReadOnlyCollection<T>. This is thread-safe and any changes to the original collection will be reflected in it since it is only a wrapper.

public static IList<IRecipe> _identityMap = new List<IRecipe>();

  public IList<IRecipe> IdentityMap
  {
      get { return new ReadOnlyCollection<IRecipe>(_identityMap); }
  }

Could not be easier!

Posted in .NET, Learning, Project | No Comments »

WHILSOF : Unit Of Work

Posted by Sebastien Lachance on February 22, 2008

This is an interesting pattern. I was using it without giving it a name. I encountered this pattern while reading the Jimmy Nilsson’s book : Applying Domain-Driven Design and Patterns - With Examples in C# and .NET. The Unit Of Work is a way to create a logical group of object. The most basic example I can think of is the example of an Order. An order contains OrderLines. The Order and the OrderLines are part of the same logical group. We say that this is an Unit Of Work. I tend to think of it at the way I’ll save the Order. Do I call a service to insert the Order and another to save the OrderLines? Or do I call a single service that will persist it all at the same time (maybe using a transaction)? I will use a single service that will save the Order, the OrderLines and all other related information. Everything that must be persisted at the same time is said to be an Unit Of Work.

In the RecipeHelper project (the personnal project I am working on), I have a single Unit Or Work (at the moment). The Recipe is the root and contains a list of steps to follow and a list of ingredients. When I persist a recipe, I persist everything in the object graph.

Here is some resources from experts that can help you more with applying this pattern :

Posted in Agile, Design, Desing Patterns, Learning | 2 Comments »

Setting up a basic continuous integration server with TeamCity

Posted by Sebastien Lachance on February 6, 2008

What is TeamCity? It’s a software that you would use to do continuous integration. Continuous integration is very important and it should never be an option on a serious project (that’s is my opinion and I strongly believe in the values it provide).

If you have followed the Building A New Application Series, you may be wondering why I would want to do that after setting up a complete integration server with CruiseControl.NET. Well, I was skeptical when I first heard about all the fuss surrounding this JetBrains project. After all, CruiseControl.NET was doing everything I wanted and more.

So the reason I made the switch is because of the time it take to set it up : 20 minutes. Everything was fully functional in under 20 minutes. I absolutely got no error at all. I just got through all the step of the wizard and then : done. Unit testing, code coverage, build, reports, etc… And it’s absolutely free for small team.

The big downside for me was the lack of support out of the box for other unit testing framework (other than NUnit and MSTest). My project is using MbUnit so I will need to do some more research to integrate it in my build process. But it is possible if you want to invest time in doing so.

So let’s get started with this little tutorial :

1. Download TeamCity.

2. Start the installation.

Just follow all the steps. I encountered a slight problem due to something already on port 80, so I used the port 8080.

TeamCity_001

TeamCity_002

TeamCity_003

TeamCity_004

TeamCity_005

TeamCity_006

TeamCity_007

I left everything intact in this screen, but this is where you specify some default folder used bu the build agents. The tempDir and workDir will be used to store your application artifacts and even your source file before the compilation if you don’t give it one in the configuration (later).

TeamCity_008

TeamCity_009

TeamCity_010

That’s it, you have installed TeamCity. Now let’s add our project to it.

3. Open TeamCity !!!

TeamCity_011

TeamCity_012

Nothing too complicated here, just enter the username/password you want for the administrator account. The email will be used to sent important information the build server would want you to know..

TeamCity_013

What I like is that you will be taken by the hannd for the rest of the steps. Click on the Create Project link.

TeamCity_014

Name of the project and a description. It will be useful if several projects are on the same build server.

TeamCity_016

Now click the Create build configuration link. You can have multiple build configuration by project.

TeamCity_019

In the build configuration window, you can change the way the build number are generated and the default behavior when the build fail. You can also specify that you want to start with a clean project.

TeamCity_020

There, you can decide how you want the project to be retrieved from the source control repository and where to put him. You can also decide when to label your build. If you do not want a label on a failed build, you can do so. Next, click on Choose build runner.

TeamCity_021

TeamCity is not only for .NET project. Several build runner are included such as MSBuild, NAnt, sln2003, sln2005, sln2008, Ant, Maven2, etc… Because I am using MbUnit as a testing framework I have decided to stick with MSBuild. But if you are using NUnit or MSTest you may want to use sln2003, sln2005, sln2008 as they can run your unit tests and tell the coverage of your assemblies. You need to fill in the Solution File Path field with the name of your .sln, it’s relative to your project structure (if it’s in the root, enter only the name of your solution file. Fill the rest of the field if you are using NUnit or MSTest.

TeamCity_022

Last step! Go to the Version Control Settings tab and click Create and attach new VCS root. Give it a name and choose the version control system (VCS) you want to use. Fill in the required field.

Save, and you’re done!

This is the most basic setup you can have. Of course, there is a lot of other things to configure to your specific needs. You can even have integration inside Visual Studio or Eclipse. As I said before the only downside I found is the lack of support for MbUnit, but I will work something to bypass that.

I may do another post going more in depth if I have time. Or maybe a screencast, that would be a lot of fun. If you’re interested, just leave a comment and I will consider it.

Posted in Agile, Continuous Integration, Learning, Project | 5 Comments »

Screencast and my opinion about TypeMock

Posted by Sebastien Lachance on January 24, 2008

I have always been told that TypeMock was too powerful, not strongly typed and for that, It shouldn’t be used. I believed that. The problem is : I should have given it a try before taking that for granted.

I have watched the Roy Osherove screencast and was impressed! I am currently working on an existing code base that was done before we went Agile and even before we were doing object-oriented development. When I need to refactor certain features I usually start writing tests and then using dependency injection to be able to mock some object. The minimum to be testable with Rhino Mocks. But with TypeMock you can mock object and don’t even need to inject them. You can also make expectation on static methods. Isn’t that just great! I believe so.

However, I will stick with Rhino Mocks for now. I like the way It force me to decouple my code and in some sense, it provide me with guidance to make my work testable.

P.S. : This is just my opinion and not the absolute truth.

Posted in Agile, Design, Tests, Tools | No Comments »

NHibernate - SaveOrUpdate does nothing?

Posted by Sebastien Lachance on January 23, 2008

Of course it does something, just make sure you call the Flush method on your session…

I have just started playing around with NHibernate for a personal project (the one I use for the Building a new application series) and I’m liking it. This make all the data access seems so easy. Maybe I will change my point of view after dealing with some collections and relationships.

Posted in .NET, Design, Learning, Project, Tools | No Comments »

Excellent Foundations of Programming

Posted by Sebastien Lachance on January 14, 2008

Sometimes, you come across real treasure! This is one of them, printed and with me for a long time.

I have just finished reading the “Foundations of Programming” series by Karl Seguin. This is a “Must Read”. It’s a really great series that cover all aspect of building an application. I can’t recommend it enough!

Here is a link to the PDF file which has all seven posts.

Posted in Agile, Continuous Integration, Design, Learning, Tests | 1 Comment »

Mind shift

Posted by Sebastien Lachance on January 14, 2008

I was wondering when this day would come. When I’d start thinking in term of object. This change in paradigm was not easy. I started programming using the data-centric way and was submerged by it. I was struggling to get rid on this kind of thinking. I’ve read multiple book before : Agile Software Development, Object Thinking, Refactoring, etc. But this was hard to me. However, 6 months ago, I finally landed on an Agile team. I got a hard time changing the way I was thinking because I was sure that I was understanding object-oriented development.

For me, the revelation occurred in this team. There I was introduced to my first test-driven project. One of the team members and a consultant for the company was previously working for Object Mentor. I needed to be up to the task, and immerged myself completely into it. I was reading the code of the project regularly and tried to do the same thing. I made mistakes, lots of mistakes, but I learned from them (even if I was not being directed in the right way after making them, but this is another story). Unfortunately the project was put to an halt and I had to get back to the old project, the one that became so complicated that I had abandoned all hope of doing something right with it. I was wrong, this was a wonderful opportunity and this is where the mind shift occurred. I started doing some unit tests and when I was comfortable with the coverage of a certain part, refactor to reflect a more object-oriented and easier to understand ways. I learned about Inversion Of Control (IoC), Dependency Injection, Mocking, Domain-Driven Design and Design Pattern. I also started to read my books back. I re-read Code Complete, Refactor and Object-Design Heuristics, and I am planning to read a lot more. I also adopted many of the Agile practices. This was not hard, since I had worked on project that had big upfront design, and after every release, we were deploying every week a new versions because of the bugs we had found or enhancements the clients wanted. This was just the natural thing to do and I firmly believe this is a good road to follow.

Now, If I could only get a new challenge to push my limits and learn more!

Posted in Agile, General, Learning, Programming | No Comments »