Far Away Developer

Sebastien Lachance

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 | 1 Comment »

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 »

New code drop to the ASP.NET project on Codeplex

Posted by Sebastien Lachance on May 13, 2008

  • 05/12 Source code release of the ASP.NET AJAX Script Profiler helper control: To support the ASP.NET AJAX script combining feature which shipped in the .NET Framework 3.5 SP1 Beta release, we’ve added the ASP.NET AJAX Script Profiler helper control source and binaries to this project. This control helps you to identify the scriptreferences used in your ASP.NET AJAX page to use with ASP.NET AJAX script combining. You can find this release here: ScriptReferenceProfiler Source and Binary Release. In addition this control is used in a Screencast for ASP.NET AJAX script combining on the ASP.NET site.
  • 05/12 Release of the ADO Data Service AJAX Client : The ADO Data Service AJAX Client Library enables you to consume an ADO.NET Data Service from client script in an ASP.NET AJAX Web page.

Read more here.

I am really wondering how I can keep up with all these new things to try. Well, I guess we will really need a pill to stop sleeping one day.

Posted in .NET, ASP.NET | No Comments »

My solution node does not appear in Visual Studio 2005 or Visual Studio 2008

Posted by Sebastien Lachance on May 13, 2008

A reader asked me how we can display the solution node in Visual Studio when you have only one project. This feature is turned off by default. What you need to do is to go in your Tools/Options menu and click on Projects and Solutions. Then you need to check the Always Show Solution checkbox.

AlwaysShowSolution

Feel free to ask me any questions.

Posted in .NET, Visual Studio | 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 »

100th Post

Posted by Sebastien Lachance on May 9, 2008

100th post. I want to thanks everyone who came visiting me regularly. Over the last year, the amount of visits grew each weeks. I remember when I got the 100 visits mark. Now I am at an average of 120 visits per day with a day of 199 visits. As you can see below, it’s pretty clear where the weekend is.

BlogStats

BlogsStatsWeek

Here is a gift for you all !!! (I think he had a lot of spare time …) Enjoy!

Posted in Blogging, Fun, General | 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 | No Comments »

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 »

Top 5 most influential peoples on my career

Posted by Sebastien Lachance on April 30, 2008

I was thinking about this for a while. If I have to choose five peoples who have influenced me the most concerning my career, who would that be?

1. My first supervisor when I was a wielder.

This guy once said to me that I would never do anything more than wielding in my life and if it wasn’t for my father, he would have fired me for nothing. I promised him that It will not happen. Four years later, I was the leader of a small team in the company. Take that…

2. Bernard Voyer.

A famous explorator that I met when I was in school. He believed in his dream and have conquered the Everest, South Pole, North Pole and a lot of hard to reach places. He his just a normal person who gave everything he had to make his dream true.

3. The ASP.NET guy.

I don’t remember his name , but it’s shortly after I finished school. He had just completed a Microsoft Certification in ASP.NET. This is where I first heard the term MCSD and I promised myself I would be one (even though I had no idea what it was at that time). 2 years later, February 7 2006 at almost 9:00 PM, I was one. I learned all by myself with the help of some books and the requirement list on MSDN. It just felt incredible. Even if I’m no longer in the world of certification, I’m still very proud of it.

4. Scott Hanselman.

First blog ever that I have put in my RSS aggregator. I’m following him since a long time and he inspired me a lot. It’s because of him that I am a blogger. He’s coming to the .NET User Group of Québec next week and I can’t wait to meet him.

5. Jean-Paul Boodhoo

Never met the man. I first heard of him in an episode on DnrTv about design patterns. It seem he has a lot passion… If you have never heard of him, head here. I wish I was as passionate as him. I am, but he his more :).

This was my top 5 of the peoples who had the most impact on me. But I want to talk about a 6th person. He probably don’t want me to talk about him so I will not give any name. Before meeting him, I was already into Agile development. But he taught me a lot about other aspect of the methodology. Everything that can’t be learn in a book to be more precise. But thing haven’t got very well at some point and after a lot of different events we lost touch. Anyway, I am very recognizing to have worked with him.

 

Posted in General | No Comments »

var keyword (or Implicitly Typed Local Variables)

Posted by Sebastien Lachance on April 17, 2008

If you are like me and installed the nightly build of Resharper 4, you might have seen the recommendation it made to use the keyword “var” almost everywhere. But why?

Here is my answer :

First of all, you must know that the keyword var is not like “Variant”. It is not late-bound or loosely typed. The compiler will be able to infer the type from the right side of the expression. In many case, it’s optional, but sometime you don’t have a choice. It’s the case with Anonymous Types :

var customer = new {ID = 1, Name = “Sebastien”, CreditCardNumber = “You can dream!”};
 
It is also often seen with LINQ.
 
Should you use it everywhere you can? Well, it’s a matter of preferences. Mine is to use it only when necessary. If the code is harder to understand when using var, then declare the variable explicitly.
 
Technorati Tags: ,,

Posted in .NET | No Comments »

Exploring Anonymous Methods

Posted by Sebastien Lachance on April 16, 2008

My desire to explore Delegates and Anonymous Methods came from my next exploration, which will be the the Lambda feature. So, I will probably do an article on it in a near future.

So, what exactly is an anonymous method? It’s a C# 2.0 feature. Whenever you encounter the need to pass something as a delegate parameter, you can use an anonymous method.

Example :

This class has a method that expect a delegate that has no parameter and no return value.

public class Action
{
    public delegate void MyActionDelegate();

    public void Execute(MyActionDelegate myActionDelegate)
    {
        myActionDelegate.Invoke();
    }
}

Previously, you would have declared a method that has no parameter and no return value and passed it to the Execute method. Like this :

public static void DoSomething()
{
    Console.WriteLine(“This is not an anonymous method.”);
}

static void Main(string[] args)
{
    Action action = new Action();

    action.Execute(DoSomething);
}

An the output would be :

DelegateOutput

With an anonymous method, we reduce the code and by the same occasion, augment code readability.

static void Main(string[] args)
{
    Action action = new Action();
    action.Execute(delegate() { Console.WriteLine(“This is inside an anonymous method.”); });
}

 

AnonymousOutput

If the delegate has expected a parameter you could have done it like :

action.Execute(delegate(string s) { Console.WriteLine(s); });

And if the delegate have an return value, make sure you return one of the correct type :

action.Execute(delegate(string s) { return s; });

 

Accessing variables located outside the anonymous block :

A feature of an anonymous method is the ability to access variables located outside the anonymous scope (anonymous-method-block). Those variables called “outer variables”. It is better explained by an example :

string myString = “Outside the anonymous method.”;
action.Execute(delegate(string s) { Console.WriteLine(myString); });

AnonymousScope

The exception to this rule are the ref and out parameters, which cannot be accessed by the anonymous method. You also can’t put unsafe code in the anonymous method.

Real life example

Maybe not (it’s always hard to come with great example), but it illustrate how you can use an anonymous method to find all string matching “String5″ inside a collection of string. Just imagine doing the same thing in your collection of orders or products.

List<string> myListOfString = new List<string>();

for (int x = 0; x < 10; x++)
{
    myListOfString.Add(“String” + x);
}

List<String> returnedStrings = myListOfString.FindAll(delegate(string s) { return s == “String5″; });

 

Conclusion

Mastering Anonymous Methods is a great skill to have in you toolbox. But be careful, if you need to reuse the same code again and again, you better have to create a method and put the code in it. Don’t try to impress your friends too much. :)

 

Posted in .NET | No Comments »

Refreshing my memory : Delegates in C#

Posted by Sebastien Lachance on April 9, 2008

I haven’t really used delegates since I was programming with the .NET Framework 1.0. Since I have some spare time left, I decided to ‘”refresh my memory”. I have prepared a little cheat-sheet that you can use as a reminder for the delegates functionalities in the .NET Framework 3.0.

 

1. What is a delegate?

A delegate is a data structure that refers to one or multiples static methods and/or instance methods. You can use this when you have a dynamic list of methods to be called that you don’t know ahead of time.

2. How to create a delegate?

public class TestClass
{
    private delegate void myDelegate(string name);
}

The signature of the declaration is very important! The methods that will be contained in the delegate must perfectly match the declaration. In this case, the methods that will be allowed must be void and take a single string as a parameter.

When using the delegate keyword, you are actually creating a System.MulticastDelegate.

 

3. How do I instantiate a delegate?

public void TestMethod()
{
    ClassTest test = new ClassTest();

    //Instantiating a delegate with an instance method
    var del1 = new myDelegate(test.InstanceMethod);

    //Instantiating a delegate with a static method
    var del2 = new myDelegate(ClassTest.StaticMethod)
}

 

4. How do I call the method contained in the delegate?

del1.Invoke(“This is a test.”);

The Invoke method will actually have the same signature as your delegate signature. So you benefit of a strongly-typed way to use the delegate feature. There is also a BeginInvoke and an EndInvoke method to program asynchronously.

 

5. But you said that you can have more than one method in the delegate?

Actually yes. There is several ways to add more methods, but the easiest way is :

del1 += ClassTest.StaticMethod;

When calling Invoke (or BeginInvoke) each one will be executed in the order that they were added to the delegate. If an exception occurs at any point, the execution is canceled and the remaining methods will not be called. And you will get an exception of course.

 

5. Anything else?

Yes, a delegate is immutable. Each time you add a method entry point, a new delegate is created for you.

Posted in .NET | No Comments »

A new job

Posted by Sebastien Lachance on April 5, 2008

Last week, I have left my job at bxsystems. I had an opportunity that I could not refuse. I have worked for 3 years and 8 months with the most talented peoples I ever encountered. They are great professionals and I am sure they will continue to be successful in their careers. This is where all started for me, where I started to get passionate about programming. I had a lot of freedom and a lot of learning opportunities.

I am very grateful for everything. For a beginner, it could not be a better place. Thank you!

Posted in General | 1 Comment »

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 »