Archive for category dotnet

Beware of the IEnumerables

Some time ago I wrote about the difference between List and Collection, and how you should use them. Usually you want to keep the details away from the users of your class, and an even tighter way to encapsulate a list of something is to expose IEnumerable<T>. Note that both IList<T> and ICollection<T> inherits this interface, so IEnumerable<T> exposes even less details to the user. Another benefit is now you can use yield behind the scenes to create your “list” on the fly.

But this also its pitfall. What do you think will be the output of this code?

   10   static void Main(string[] args)

   11   {

   12       var ola = new Pupil(){Name="Ola", IsMate = false};

   13       var trond = new Pupil() {Name = "Trond", IsMate = true};

   14       var pupils = new List<Pupil>(){ola,trond};

   15 

   16       IEnumerable<string> names = ClassMateNames(pupils);

   17 

   18       foreach (string name in names)

   19       {

   20           Console.WriteLine(name);

   21       }

   22   }

   23 

   24   private static IEnumerable<string> ClassMateNames(IEnumerable<Pupil> pupils)

   25   {

   26       foreach (Pupil pupil in pupils)

   27       {

   28           if (pupil.IsMate)

   29               yield return pupil.Name;

   30       }

   31   }

 

Yes, you’re right, the output is my only friend “Trond”:

image

But when are we really finding out who my friends are? The most natural thing is that I find them when I call ClassMateNames, as it is called first. That’s what I’d think anyway. But what if got in a fight with “Trond” between when I sort out my friends and list them to the console?

   35   private static void FightWith(Pupil pupil)

   36   {

   37       pupil.IsMate = false;

   38   }

   16   IEnumerable<string> names = ClassMateNames(pupils);

   17 

   18   FightWith(trond);

   19 

   20   foreach (string name in names)

   21   {

   22       Console.WriteLine(name);

   23   }

This gives me these friends:

image

How about that! The information that I no longer is friends with “Trond” has changed the list I thought I retrieved with the call to ClassMateNames. What is happening is called deferred execution, which delays the actual execution of the internals in the ClassMateNames to when I iterate it. This is exactly how LINQ to [insert TLA here] operate as well, so nothing is actually fetched until you need it.

In my case this was an advantage, because at the time I was listing my friends, I didn’t actually have any!

And the problem is?

The problem starts when you before and/or after the call to ClassMateNames set up and tear down a session, connection, or anything that the inside of the iterator rely on. Any fetching of IEnumerables inside using-blocks should also be considered smells in this regard. If you should clear the list of pupils right after you have sent it to ClassMateNames (you don’t need it anymore right?), you have introduced a very subtle bug as the list is empty at execution.

The advice are thus: IEnumerables and yield is definitively great tools, but be aware of the inherent difficulties and quirks of deferred execution and use them with caution both as producer and consumer!

No Comments

MSDN Live with Steve Ballmer keynote

ballmerMSDN Live has toured Norway this fall, with a handful of presentations for .NET developers. I attended the last one in Oslo on Tuesday, where Steve Ballmer made the keynote!

Most developers have seen the developers, developers, developers talk, and we had high expectations for this keynote. He was quite enthusiastic in Oslo as well, telling us about things he thinks will influence our industry in the foreseeable future. This search at Youtube seems to find the whole show.

The rest of the day I attended the main track, starting out with a Silverlight 2 presentation from Gøran Hansen. While Silverlight 1 was mostly about animations and media, I didn’t give much attention. But the second version looks promising, with the CLR and a subset of the .NET libraries present. What I miss though, is maybe some background about the fact that running .NET WinForms applications in IE in object-tags has been possible a long time (without the automatic deployment of the framework). Props however to MS for finally supporting more than Windows & IE only! Gøran did a great job presenting, I really enjoyed his presence on stage.

Next up was another presentation from Gøran, which gave the audience an introduction to ASP.NET Dynamic Data. For those of us who attended NDC2008 and Scott Hanselmans keynote there, it was plain repetition. The only difference might be that this was showing the final bits released with SP1 of the framework, and Scott showing us some earlier version. It seems like a great technology to get you up and running very quick, but I wonder how many pages you end up with in the CustomPage directory after a while. Even though the topic didn’t tickle my fancy, Gøran did a great job on this one as well.

Then it was time for lunch, rather late according to my stomach. But it tasted good, and there seemed to be enough to fill up all us starving geeks. As always during the breaks, old colleagues and friends sneak up on you and says hello. Which I really do appreciate!

After the break, Anders Norås gave a talk about SOA. More specifically about how we should start thinking along the lines of enterprise service buses and leave our old crusty webservices in the dust. I really do concur with a lot his ideas, and I’m always happy to see code with binsor-love. I also liked his onion-architecture, which resembles my standard layered architecture (no, not the "standard standard"). Hmmm, looks like another blog post (again).

"Debugging your debugging habits" was up next with Rune Zakariassen from Microsoft. He showed us some tips & tricks for your debugging needs in Visual Studio, and presented a step-by-step recipe on how you best can find bugs in your code. I thought it was a nice presentation, even though my only real takeaway was the tracepoint functionality in VS. I’ve been a sucker for Debug.Writeline when I don’t want to impact the run of things stepping through, but this gives me an even less intrusive way keeping track of how the program executes.

Finally, Gøran entered the stage for the last time this day. He showed us how WPF databinding can be used with a variant of Model-View-Presenter called Presentation Model. The emphasis was really on this pattern, and how it helps attain SoC. He also mentioned DIP with the short version "Program to an interface, not an implementation". A good thing can’t be said enough so here is the original:

High level modules should not depend upon low level modules. Both should depend upon abstractions.

Abstractions should not depend upon details. Details should depend upon abstractions.

All things considered, yet another great talk from Gøran, keep up the good work and preach on about those design patterns and OO principles!

Yet again, great work by Rune @ Microsoft arranging this event. Until next time, I’m on twitter at http://twitter.com/haugern.

1 Comment

Norwegian Developer Conference 2008 Review

ndc2008Logo_thumb

I arrived Tuesday at NDC2008 full of anticipation and excitement; there were a lot of great talks scheduled as I could see it, and I had trouble choosing which ones to attend. I almost immediately found some old colleagues and class mates, which I hadn’t talked to in several years. That was really an added bonus, and I really appreciated the little "reunions".

Day 1

Scott Hanselman started the show with a keynote, showing us a little LINQ and the new Dynamic Data-bits. Hanselman was witty, and was a great presenter. There might have been a couple of things that did go to fast if you hadn’t seen a lot of .NET 3.5 before, but I guess most got at least a glimpse of what it can do.

After the keynote I was considering several sessions, but I decided to attend Mary Poppendiecks first session titled Thrashing. She went through the reasons for them, and what can be done to remedy it. As a reader of the Mythical Man Month, Slack, Peopleware, and others, I found she conveyed a lot of the same information found there, and I really share their views. A new aspect I hadn’t thought of before was queuing theory, which we apply consciously to hardware and related problems, but seldom to team and people dynamics. I will make a follow up post on the matter.

I’ve lately dabbled with some reflection, so next I attended Roy Osheroves talk Deep Reflection, hoping it would be as deep as promised (level 400 session). It certainly was, and I’m glad I’ve recently been looking at both Reflection.Emit and CodeDom-programming. It also helps to extensively take advantage of the vanilla reflection utilities regularly. This was a prerequisite, but it seemed like a lot of eyes glazed over when it was presented. He ended the session with a song, and I think he did his presentation on this heavy topic in a great way.

Supposed to be doing a talk about agility in Typemock (the firm), I gave Roys next session a chance. But the agenda had changed and we were introduced to Designing for Testability. I had this part mostly under control, so I was a bit disappointed that the original talk was exchanged. It was an introduction to IoC, DI, and IoC-containers, as well as our options when designing for testability with mocks or subclassing. This session ended in a song as well, and the lyrics was funny as always.

There was unfortunately another change in the agenda, Roy had originally a Threading-talk I’d like to see, but it was changed to a Testing your data access layer session. With this change, I attended Mary Poppendiecks talk on The Role of Leadership in Lean Software Development. Contrary to popular belief in most Agile circles, she thinks there is a place for leaders, not only self-organizing teams. I must admit that this is something I’ve personally experienced as well; when everyone is responsible, no one takes responsibility. I won’t go into more detail here, but I think it was a great talk, and she definitively hit home many points with me.

Day 2

I start out attending an Agile Panel discussion hosted by Scott Hanselman, featuring Mary Poppendieck, Roy Osherove, Ken Schwaber, Chet Hendrickson, and Ron Jeffries. An example topic was what are the first steps to become agile. It wasn’t that much of a discussion really, as all the panelists believe in the Agile values.

The next two sessions I followed the Agile crowd in general, and Jeffries & Hendrickson in particular in their first two talks about Natural Laws of Agile Software Development. They presented the same material I saw from Smidig (Agile) 2007 on the economics of releasing early. I think it shows the potential payoff of releasing early, but it misses some aspects of going to early into maintenance mode with the software. I think this has to be explored some more. After showing these teasers, they went more into how early and frequent releases can be done baking quality into the process through the means of TDD and Acceptance Tests.

While I was humming along with Ron & Chet, it seemed like Roy got quite a following. It was almost impossible to get a seat on his Advanced Unit Testing session. It really seems my fellow Norwegians are good & ready for some ALT.NET techniques & practices, especially unit testing. I eventually got a seat on the session, but I must admin I personally was a little bit disappointed as I’ve already been down most of the roads before. Hopefully it was another teaser for all those who are thinking of getting into the whole unit testing business.

Next up, I attended Mads Torgersens Microsoft LINQ Under the Covers: An In-Depth Look at LINQ. And under the covers it was indeed. He gave us a great peek into how a LINQ-expression was disassembled, and showed us the output through Reflector. I must admit it was hard to follow everything, but I was at least familiar with all the constructs. All in all a mindblowing experience, and Mads gets credit for his enthusiasm during the session.

Finally, I attended Mary Poppendiecks session on The Discipline of Going Fast. We got new insights into the Toyota Way, a little bit of history, and specifically the Stop-the-Line practice. I definitively will continue this flirt the Lean methodologies.

Conclusion

I’m very pleased, and I was exhausted after two days packed with great content. The only thing I have a complaint about is that a couple of Roys talks should have been moved to accommodate the massive interest his topics achieved.

For another review from a fellow Norwegian blogger look at Fredriks post. You may also see more pictures from Rune Grothaug, who did an amazing job arranging this as well.

I must thank the hosts for a great event, and I will come back next year!

No Comments

Using the using-statement and pattern in C#

How often do find yourself writing code like this to do some things in batch:

    BatchCalculator calc = new BatchCalculator();
    calc.Suspend();
    calc.CalculateSomething(something);
    calc.CalculateSomethingElse(something);
    calc.Resume();

Well, I do and I’m not really happy about sprinkling those Suspends and Resumes around everywhere I need to start and stop something. I see at least two common pitfalls with thishttp://www.flickr.com/photos/stuckincustoms/894698437/ solution and a minor hiccup:

  1. Somewhere down the pipe I’m bound to forget the call to Resume explicitly and I’ll have a bug on my hands.
  2. Somewhere in between the Suspend and Resume calls an Exception is thrown, Resume is never reached, and leaving the object in an unwanted state.
  3. It could be better looking!  ->

The short using-introduction

With the introduction of .NET and it’s managed environment and non-deterministic garbage collector, there were several figureheads in the industry that raised an eyebrow or two. There were also people raising more than their eyebrows as well, and according to legend and several .NET Rocks shows, Chris Sells (now a blue badge) was one. They allegedly made MS include an IDisposable interface with a simple method Dispose() to fill their garbage collection needs. And if that wasn’t enough, they included the using-statement which is a try-finally in disguise where the finally automatically calls IDisposable.Dispose()!

A couple of regulars in my world in that department are the IDbConnection interface and later (from 2.0 and onwards) the TransactionScope class, but it has also been recommended practice for any implementers of the IDisposable interface.

Yeah yeah, but what can I do with it?

With the aforementioned background in place we can exploit it to create a better and more fluent API for our batch-oriented processes. Let us simply dive into the code, and I introduce without further ado; the changed BatchCalculator:

public class BatchCalculator
{
    public IDisposable Suspend(){}
    public void Resume(){}
    public void CalculateSomethingElse(object something){}
    public void CalculateSomething(object something){}
}

Suspend now returns an IDisposable and we can replace our calling code to this:

    BatchCalculator calc = new BatchCalculator();
    using(calc.Suspend())
    {
        calc.CalculateSomething(something);
        calc.CalculateSomethingElse(something);
    }

Yes! That’s more like it. I definitively like to looks of that.

But how.. do I ensure a call to Resume?

This is where the "magic" happens. Let us make a class which implements IDisposable that gets returned from our Suspend method:

public class Suspender : IDisposable
{
    private readonly BatchCalculator m_calculator;
 
    public Suspender(BatchCalculator calculator)
    {
        m_calculator = calculator;
    }
 
    public void Dispose()
    {
        m_calculator.Resume();
    }
}

And our revised Suspend method:

public IDisposable Suspend()
{
    return new Suspender(this);
}

Now go look at the implemented Dispose-method in our Suspender-class. It just calls our Resume method on our BatchCalculator! So when the using-block is exited, the Dispose-method is called and hooray, mission accomplished.

Finishing touch

To increase the applicability of the Suspender-class I introduce the role interface IResumable:

public interface IResumable
{
    void Resume();
}

And implement it in BatchCalculculator:

public class BatchCalculator : IResumable
{
    public IDisposable Suspend()
    {
        return new Suspender(this);
    }
    public void Resume(){}
    public void CalculateSomethingElse(object something){}
    public void CalculateSomething(object something){}
}

Now the Suspender class can just wrap our new interface:

public class Suspender : IDisposable
{
    private readonly IResumable m_resumable;
 
    public Suspender(IResumable resumable)
    {
        m_resumable = resumable;
    }
 
    public void Dispose()
    {
        m_resumable.Resume();
    }
}

Final note

If we revisit our weak spots, have we solved them all? A definitive yes; using using guarantees that the Dispose()-method is called which in turn calls our wrapped method. I must also add I really like the syntactic sugar using represents.

This pattern is obviously at a tangent for what using and IDisposable was supposed to be used for. The MSDN library has this to say about IDisposable:

The primary use of this interface is to release unmanaged resources.

But why not leverage what we have available. After all, coding is done once. Reading it is another matter completely.

2 Comments

Remember to check out PartCover

Bil Simser just wrote about the lack of coverage tools for .NET in this article, and I agree with his points.

In our current project we’re using NCover and NCoverExplorer (older editions), which are working just fine as we’re still in the .NET 2.0 world. It seems there are some problems with the older versions (they have gone commercial on us) and the new .NET 3.5 framework.

This isn’t particularly good news, as we’re going to utilize VS 2008 and .NET 3.5 shortly. The choice is wether fleshing out 150 USD, or find an alternative. One of the comments on Bils post linked to another coverage utility; PartCover.

So, note to self: Check out PartCover when we’re going .NET 3.5.

No Comments

Automatic versioning with CruiseControl.Net and NAnt

I’ve created a similar setup as David Donald Belcham (a.k.a. igloocoder) mentions in this post for our current project at NOIS.

When I mean similar, we’re using the exact same tools for the job, with NAnt (asminfo task) & CC.NET. But there’s a couple of differences.

New labeller for CC.NET

The first, and minor difference is the labeller. I wanted the versions to work almost as the NAntContrib version task with the automatic build & revision based on day of year and time of day respectively. As most people were running the traditional ymmdd-format for the build, this effectively had to stop at the beginning of 07; 16 bit for the build number breaks that setup. So I settled for an algorithm which won’t break until the year 2066. The major & minor numbers is set manually.

I couldn’t seem to find such a labeller out there, and as I wanted the same number in the CC.NET build-number, and in the assemblies (and in the source control system as well, I’ll get back to that), CC.NET needed to be master. Not finding what I wanted, I created my own labeller for CC.NET, which gives me the build-numbering scheme I wanted.

With the extensibility-points in CC.NET it was great fun, and real easy to deploy my own. Here’s the whole thing:

using System;

using Exortech.NetReflector;

using ThoughtWorks.CruiseControl.Core;

 

namespace Haugern.Util.CCNet

{

    [ReflectorType("versionLabeller")]

    public class VersionLabeller : ILabeller

    {

        [ReflectorProperty("major", Required = true)]

        public int Major;

        [ReflectorProperty("minor", Required = true)]

        public int Minor;

 

        public string Generate(IIntegrationResult integrationResult)

        {

            if(integrationResult == null)

                throw new ArgumentNullException(“integrationResult”);

 

            DateTime now = DateTime.Now;

            return Major + “.” + Minor + “.” + ComputeBuild(now) + “.” + ComputeRelease(now);

        }

 

        private static string ComputeRelease(DateTime now)

        {

            return Math.Round((now.TimeOfDay.TotalSeconds/10)).ToString();

        }

 

        private static string ComputeBuild(DateTime now)

        {

            return now.ToString(“yy”) + now.DayOfYear.ToString(“000″);

        }

 

        public void Run(IIntegrationResult result)

        {

            result.Label = Generate(result);

        }

    }

}

Consistent Build Number

The second difference (well, in his defence, it’s not even mentioned), is that the exact same label should be set back into the source control system. In our case, we’re using TFS Source Control, and with the standard plugin it was easy to apply it there as well.

Now we got this great setup where we can track everything that happens back to the build-number as it is the same across the whole environment:

Application <-> Build server <-> Source Control

Consistent build number across the production line also means every build is a candidate for release.

Should some bug find it way through our thorough unit-testing & qa-scheme into the hands of our customers, finding the right version to search for it will not be a problem!

4 Comments

.Net Collection<T> vs. List<T>

Recently, we have gotten a couple of “fresh out of school” employees, and here the other day we went through the code of one of our applications and explained how it was built (at least how was supposed to be or “do as I tell you, don’t do as I do”).

Our O/R-mapper returns a generic Collection<T> when it is asked for a list / collection of some objects, and is consistent in doing so. The question however, was why that wasn’t a List<T>.

I had to admit I hadn’t dug into the material properly, so the question kindof got left there in open air. My bad excuse was of course I had been mostly doing managment stuff lately, and so was my companion presenter as well.

So to make a not so long story short, I had to dig into the collections that is found in .NET, and I explain them to myself for later reference, beginning with the aforementioned Collection<T> and List<T>.

The difference

Just to sum it up, Collection<T> is made for extensibility and List<T> is made for performance. See this and this from the FxCop guys.

For a full blown explanation, a great reference is also found here.

Use List<T> for all your heavy lifting internally, and expose a Collection<T> in your public API.

4 Comments