October 2008 - Posts

Book review: Joel on Software...
Fri, Oct 31 2008 20:17

Ok, this must be book with the longest title I've read until today. Here its complete name: Joel on Software and on Diverse and Occasionally Related Matters That Will Prove of Interest to Software Developers, Designers, and Managers, Whether By Good Fortune or Ill Lick, Work with Them in Some Capacity. Phew...That is really a long long title! This book is an aggregate of several of Joel's thoughts on software development that he has been publishing in his blog since 2000.

You can agree or disagree with Joel, but there's one thing everyone agrees on: Joel is a terrific and entertaining writer. He is able to capitalize on his extensive experience and ends up giving you lots and lots of stories that will probably amuse you (or, if you don't agree, will probably make you complain with the book :)). Ok, by now it's fair to say that you don't need to buy this book because everything that's there is publicly available on his blog. But, if like me, you're  a sucker for these kind of essays, then you'll surely end up buying this interesting book. My score: 9/10.

by luisabreu | with no comments
Filed under:
PDC 2008 ending...
Thu, Oct 30 2008 21:59

And for those of you that (like me!) didn't attend, it's now time to start watching the videos and start playing with the bits.

by luisabreu | with no comments
Filed under:
C# 4.0: Covariance and Contravariance on generics…sort of…
Thu, Oct 30 2008 10:44

One of the things that we’ll have in C# 4.0 is covariance/contravariace working on generics…I mean, sort of. Why do I say sort of? Well, because you’ll have to use the identifiers in and out for explicitly stating if you’ll be having covariance or contravariance and you can’t use them at the some time. Charlie Calvert has a good post on this subject, so you should read it before we go on.

Don’t get me wrong: having this basic support is better than having none, but I expected a little more from the C# team. I’m sure there’s a valid reason for making us use the in an out terms, but personally, I’d really prefer not to use any and let the damn thing be automatically infered. But to me that is not the worst part… what I really don’t like is that (and please tell me I’m wrong!) you cannot annotate a generic type with in and out simultaneously. In practice, this means that you should be able to use both features with simple interfaces (ex.: IEnumerable) but you won’t be able to use them withthe current collection interfaces because you’ll have cases where you want to use covariance and contravariance at the same time on a specific type…

btw, Eric Lippert has a great series on this topic.

Thoughts?

Update: Ok, didn’t I said that Eric had a great series? Yes he does and he convinced me that we need to think about it explicitly. Not convinced about not being able to say that a parameter can be in and out at the same time…

by luisabreu | 6 comment(s)
Filed under:
Microsoft’s PDC site is really pretty
Tue, Oct 28 2008 10:16

But I can’t find what I want (which, btw, are the videos. Yesterday it was really easy to see Ray Ozzie’s keynote: you just had to click the watch keynote button on the silverlight banner that exists on the top of the page. Now it’s gone and I can’t seem to find any link pointing to it anywhere on the site. So, I’ve ended up seing 15 minutes of Ray’s keynote and that’s it. wtf? Why is that link gone? Is it too much to ask for putting the damn videos online right after the events?

rant’s over!

by luisabreu | 2 comment(s)
Filed under:
Azure Service Platform presented on PDC
Mon, Oct 27 2008 23:13

I’m not there, but it seems like Ray Ozzie presented something called Azure Services Platform today during its keynote (I’m still seeing it now since I wasn’t at home when it happened). Looks interesting, but I’ll have to dig the documentation a little bit more before having an opinion about it…

by luisabreu | with no comments
Filed under: ,
Using the new Fluent NHibernate project
Fri, Oct 24 2008 14:38

If you’re a NHibernate user, you’ve surelly heard about the Fluent NHibernate, a project that allows you to define the mappings by using a fluent API. I didn’t really had the time for testing it until yesterday. Why did I only tested it yesterday? Simple: because I had to perform some major refactorings on the current project I’m working and that meant having to go through the XML mappings files and changing all those damn properties by hand. Yes, it was the perfect excuse for introducing the fluent mapping in my project.

Overall, I’m pleased with it, but since there really aren’t many docs on how to use them, I thought it would be a good idea to give some examples of its use here and to point one or two gotchas that you might get while using it. Before using it, do keep in mind that there are some options which aren’t implemented yet (but I think it’s fair to expect them to be implemented in a near future). Having said this, it’s time to show some examples. Lets start by building a dumb class and call it Entity:

class Entity{
  public Int32 Id{ get; private set; }
  public Int32 Version{ get; set; }
  public String Name{ get; set; } 
}

We’ve got an ID, a version and a property. Lets map them to columns of a table called Customers, without lazy loading:

class EntityMapping: ClassMap<Entity>{
  public EntityMapping(){
     WithTable( “Customers” ); //set table name
     SetAttribute( “lazy”, “false”); //no lazy loading
     Id( ent => ent.Id, “IdCustomer” ) //Id prop into column IdCostumer
       .WithUnsavedValue(0)
       .SetGeneratorClass(“identity”);
     Version( ent => ent.Version).TheColumnNameIs(“MyVersion”);
     Map( ent => ent.Name, “CustomerName”)
       .WithLenghtOf(200)
       .CanNotBeNull();
  }
}

This basic mapping introduces several important concepts. All the configuration classes should inherit from ClassMap<T>. Setting the table name is easy: just call the WithTable method and that’s it. You can also use the SetAttribute method for setting up the other attributes you would normally set on you <class> element. In the previous example, I’ve just used it to change the default lazy loading behaviour.

Setting the Id and Version properties are easy too: just call the Id and Version methods. Do notice that you didn’t really need to write all that code if you’re using the defaults (I never know which is which and that is why I generally end up writing everything I remember :))

Simple properties are mapped through the Map method. Notice that in the previous example we indicate all the column names because they’re different from the properties names we’ve been using.

First rant: I really don’t like calling these methods from the constructor because we’re talking about virtual methods. Unfortunately, the current version doesn’t have any other hook I can use for setting up the mappings.

Second rant: SetAttribute retuns void, which means that if you want to call it several times, you can’t use a fluent approach.

Ok, let’s move on. Now I want to add a collection of entities to my entity. In this case, Entity can have several Branches and  Branch belongs only to one entity. Here’s the necessary changes to the Entity class:

class Entity{
  //previous code
  private ISet<Branch> _branches;
  public ISet<Branch> Branches  {
     get { return new ImmutableSet<Branch>(_branches); }
     private set{ _branches = value;}
  } 
}

For now, you just need to keep in mind that Branch is an entity with some properties and that it has its own configuration file. You can easilly map this relationship by using code similar to this:

class Mapping: ClassMapping<Entity>{
    public Mapping() {
     //previous code
     HasMany<Branch>(ent => ent.Branches)
                .AsSet()
                .Cascade
                .All()
                .WithKeyColumn("IdEntidade");
  }
}

As you can see, you specify a set by calling the AsSet method and then, if you want, you can also set the cascade and key column name. You’ll also find other AsXXX methods that you can use for the other types of collections (ex.: bags).

Another thing which you’ll need to represent is many-to-one relationships. For instance, suppose we’ve updated the Entity class so that it looks like this:

class Entity{
  //previous code
  public DomainAction Action{ get; internal set; }
}

DomainAction is another entity which has its own table. The References method can be used here for mapping the many-to-one relationship between Entity and DomainAction:

class EntityMapping: ClassMap<Entity>{
  public Mapping() {
     //previous code
     References( ent => ent.Action, "ActionId")
               .Cascade
               .SaveUpdate();
  }
}

When you get the mappings, you’ll see that the Customer table will have a column called ActionId, which holds the ID of the associated Action. Ok, pretty similar to the previous configuration code, right? Oh. lets add a component to our entity. We’ll call it Address:

class Entity{
  //previous code
  public Address Address{ get; set; }
}

Address is a class that implements what I like to call the value object pattern. Just by looking at the mapping code, you should be able to see what’s going on:

class EntityMapping:ClassMap<Entity>{
  public EntityMapping(){
    //previous code
      Component<Address>(branch => branch.Address,
                              address =>
                                  {
                                      address.Map(a => a.Street, "St")
                                          .WithLengthOf(300);
                                      address.Map(a => a.ZipCode, "ZC")
                                          .WithLengthOf(100);
                                      address.References(a => a.CivilParish)
                                          .TheColumnNameIs("IdParish")
                                          .Cascade.None()
                                          .SetAttribute("lazy", "false");

                                  }
               );
   }
}

As you can see, we start by indicating that the Address property points to a component and then we need to specify the mappings between the columns of the table and each of the properties of that component class. Nothing really new there, right? Ok, so lets make things more interesting. Suppose we’ve got a collection of components…a good example might be a Contacts property, that returns a collection of Contact objects on the Entity class. That means we could have something like this:

class Entity{
  //previous code
  private ISet<Contact> _contacts;
  public ISet<Contact> Contacts
  {
            get { return  new ImmutableSet<Contact>(_contacts); }
            internal set { _contacts = value;}
  }
  //methods for adding/removing contacts not shown here
}

Now, the interesting part: mapping the properties to the database:

class EntityMapping: ClassMap<Entity>{
  public EntityMapping(){
     //previous code
     HasMany<Contact>(branch => branch.Contacts)
                .AsSet()
                .WithTableName("Contacts")
                .WithKeyColumn("IdEntity")
                .Component(ct =>
                               {
                                   ct.Map(c => c.Kind, "ContactType");
                                   ct.Map(c => c.Value, "Contacto");
                               });
  }
}

If break it apart, we can see that:

  • we have a set that should be kept on a table called Contacts;
  • We’re also creating a foreign key called IdEntity;
  • And then, the important part: we’ve got a collection of components!

I hope that by now I’ve convinced you on using this API. Just to make sure you see what I mean, lets add add some inheritance, ok? Lets suppose we have two new classes (Individual and Company) that expand the previous Entity class:

class Individual: Entity{
  //some properties go here
}

class Company: Entity{
  //it can also be a new type, with no properties
}

Since I wanted to keep both entities on the same table, I’ve ended up writing this on the mapping class:

public class EntityMapping:ClassMap<Entity>{
  //previous code
  DiscriminateSubClassesOnColumn("EntityKind",
                                             (Int32) (EntityKind.Single))
      .SubClass<Individual>()
      .IsIdentifiedBy((Int32) (EntityKind.Single))
      .MapSubClassColumns(e =>
        {
          // code for mapping the properties of derived class
         })
       .SubClass<Company>()
       .IsIdentifiedBy((Int32) (EntityKind.Company))~
       .MapSubClassColumns( e => { } );
}

What are we doing here? First, we’re saying that the table has a column named EntityKind which is used as a discriminator and we’re also setting its default value (I’m casting the enum to integer because that’s the type of my column on the database). Each subclass is introduced by the Sublass method and you’ll also need to pass the values that identify each instance of the derived type (notice the method IsIdentifiedBy call). If you have properties on the derived class, you can map them into the table by calling the MapSubClassColumns method. Notice that even if the new type doesn’t add new properties, you still need to call the MapSubClassColumns method over that subclass (as it’s done in the Company subclass).

Rant Three: Pay attention to the place where you call the DiscriminateSubClassesOnColumn method (it looks like there’s a bug on the way items are compared while ordering the several elements that are maintained internally by the mapping class). In my sample, I had to put it after the Version method. Putting it before resulted in getting the <discriminator> element after the <version>, and that means getting an exception while loading the XML for that class.

By now, we’ve already touched several things you’ll use in a NH application. There’s still one thing missing: how do we load the definitions from the new classes? One thing you can do is use reflection to load the configuration classes. Here’s some code you can probably reuse for doing that (it’s not really complete; I’m only putting it here to present some concepts):

//get NH Configuration object filled with info that generally
//comes from cfg file
var configuration = GetConfigurationWithDialectConnectionStringEtc();
AddTypesToConfiguration( configuration );
var factory = configuration.BuildSessionFactory();
//from here you can get the ISession you need…

The AddTypesToConfiguration method uses reflection to load the types. It looks something like this:

private void AddTypesToConfiguration(Configuration configuration) {
  //need to get a reference to the assembly where the mapping files are
  var currentTypes = GetAssemblyWithMappingTypes(); 
  var methodsThatReturnXmlDocs = currentTypes
        .Where( existingType => GetMethodForExecution(existingType) != null)
        .Select(existingType => GetMethodForExecution(existingType))
        .ToList();
        //probably could improve this code, but I’ll leave it for you…
        foreach (var method in methodsThatReturnXmlDocs) {
           var doc = method(new MappingVisitor());
           configuration.AddDocument(doc);
        }
}

The GetMethodForExecution type returns a delegate that points to the method that will return the XML document with the mappings:

private Func<IMappingVisitor, XmlDocument>
                                       GetMethodForExecution(Type currentType) {
  //must be a non abstract, non generic class
  //with public instance constructor
  //again, this could probably be improved,
  //but that’s not my objective here…
  if (currentType.IsClass && !currentType.IsAbstract &&
       currentType.GetInterface(typeof(IMapping).FullName) != null &&
       !currentType.IsGenericType && 
       currentType.GetConstructor(Type.EmptyTypes) != null) { 
            var instance = Activator.CreateInstance(currentType);
            var methodInfo = currentType.GetMethod("CreateMapping");
            var method = (Func<IMappingVisitor, XmlDocument>) 
                                  Delegate.CreateDelegate(
                                     typeof (Func<IMappingVisitor, XmlDocument>),
                                     instance,
                                     methodInfo,
                                     true);
             return method;
         }
      return null;
}

All mapping classes implement the IMapping interface and that’s why I’m using that so see if the current type has mapping information. After getting a reference to a valid mapping type, I’ll try to get a reference to its CreateMapping method because that method returns an XmlDocument with the mapping information that will be added to the NH Configuration object.

So that’s it. There are still some more things I could talk about here, but these were the main topics I’ve learnt while building my sample. Even though there are still some bugs, I believe that I will keep using this famework in future projects.

by luisabreu | with no comments
Filed under: ,
SVN Codeplex access is down
Thu, Oct 23 2008 14:20

Just a few weeks ago I was really happy because I was able to start using Tortoise for getting projjects hosted at Codeplex. In these last few days, I just can’t access the damn site through SVN. This is not good, specially if like me, you’re a codeplex user and you don’t want to mess with any of those TFS clients. It looks like I will have to download the MVC code without relying on my beloved Tortoise…Does anyone know what’s going on?

by luisabreu | 2 comment(s)
Filed under: ,
C# 4.0 request: I would like to have design by contract…please?
Mon, Oct 20 2008 22:08

I think that adding verifiability to the language would be great. MS Research has been working on Spec# for some time now, but it seems like it’s always behind the current C# release (for instance, the current version works against C# 2.0, but who wants to go back after using C# 3.0? Not me…).

Yes, in the current release you can try to apply some of the features introduced by Design by Contract, but you’ll only get a limits subset of what Spec# gives you (and you’ll only be able to do runtime verification – I’ve got a small framework that does this and I’ll probably blog about this on the future).

So, like many others, I would also love to have Spec# features  merged into C# by default. Wouldn’t you love to have it on the next version of the language?

spec_2

by luisabreu | 1 comment(s)
Filed under:
Zune first impressions
Mon, Oct 20 2008 21:39

Last week I’ve finally received my black 8GB Zune. To be honest, I’m a little disappointed with it.In fact, I’m really disappointed with it. First, there’s the look and feel. After holding an IPod nano, you won’t really like the Zune (and yes, the nano is not as good as the real thing). Yes, the Zune is slim and small, but the IPod has something special that makes you want hold it forever (probably it’s that cool wheel). Navigation in the Zune is not bad, but it’s not better than in the IPod.

Now, the really bad thing about it: installing software and copying music to the Zune. Let me tell you that I’m not an ITunes user, but when I had to set up my mother’s IPod, I was able to do it in just a few minutes. Not the same experience with the Zune. First, I lost count of the number of times I had to restart the Zune because, somehow, the connection was always falling.

After updating the software, I couldn’t really copy any mp3 to the Zune. Once again, there were connection problems. Interestingly, I’ve found one or two posts that said that the connection problems might be caused when you have all your USB ports in use (which was my case). So, I decided to try my luck with the notebook. After a couple of connection problems, I was finally able to copy the damn music to the Zune.

And that app you use to copy/delete stuff from your Zune…it’s simply awful. So, yes, I can tell you that I won’t be recommending it to anyone…

by luisabreu | 3 comment(s)
Filed under:
Book review: Managing humans
Mon, Oct 20 2008 18:38

I've just finished reading this interesting book by Michael Lopp. I think that we can all agree that interacting with people is a lot harder than interacting with machines. Michael's book will give you several insights into this difficult art. No, this book isn't only for managers. If you're a developer working for some manager, then you'll also get something out of this book.

And it's a thin book too. I've just read it in 3 days while riding the bus (which means I took me about 2h to read it from cover to cover - each ride takes between 20 and 25 minutes). Ok, before giving it my score, there's one thing you need to know: the book is based on several posts originally published on the author's blog. So, you must expect some "unpredictable" changes in topic which might through you a little bit off.

Having said that, here's my score: 8/10.

by luisabreu | with no comments
Filed under:
FxCop: removing rules
Mon, Oct 20 2008 15:20

One of the things I’ve been using lately is FxCop. It’s really an interesting tool and I’ve corrected several API problems on my classes after starting using it. In fact, I’ve only found two problems until now:

  1. Interface explicit implementation
  2. Incorrect spelling of names

Ok, let’s start by problem number 1. Here’s the code I’m using:

public class Something: ISomething{
  void ISomething.DoSomething(){
    DoSomething();
  }
  protected virtual void DoSomething(){
    //…
  }
}

When FxCop sees this rule, it will automatically report the InterfaceMethodsShouldBeCallableByChildTypes error. The error message says that something like this:

"Explicit method implementations are defined with private accessibility. Classes that derive from classes with explicit method implementations and choose to re-declare them on the class will not be able to call into the  base class implementation unless the base class has provided an alternate method with appropriate accessibility. “

Most of the time, I do end up using public implementation method, but sometimes I only want to allow access to that method through the interface. That’s what I’m trying to do in the previous example. Now, if you look at the code, you’ll see that a derived class can customize the behavior of the method by overriding the DoSomething protected method. So, this is one error I don’t like and I tend to classify it as a false positive.

The second problem is even funnier: I’m getting the IdentifiersShouldBeSpelledCorrectly and CompoundWordsShouldBeCasedCorrectly errors. After somme googling, I’ve managed to understand that FxCop ends up using the Office dictionary for checking the words you use in your member names. Well, it happens that my server doesn’t have office installed, so it starts giving me lots and lots of false positives. Looking at the docs, you’ll see that you can add an xml file for adding the allowed and disallowed words.

Since I’m using the command line tool (fxcopcmd), I thought that there should be a way to stop processing some rules. After looking on the docs, I found nothing. So, I’ve decided running the fxcopcmd executable and I’ve found that there is a rid parameter that lets you add or remove rules. So, if you want to remove the annoying spelling rule, you can run something like this:

fxcopcmd –f:myassembly.dll –rid:-”Microsoft.Naming#CA1033” /console

And now you should stop seeing those spelling warnings all over the place.

by luisabreu | with no comments
Filed under: ,
ASP.NET MVC beta is out
Fri, Oct 17 2008 9:08

Check Scott Gu’s post for all the details. I think it’s time to go back and pick where I left in the MVC series…

by luisabreu | with no comments
Filed under: ,
Portugal, governments and crisis
Wed, Oct 15 2008 23:25

Whenever I see a politician speaking, I always remember this cool whiskas's add. You know, they speak speak bla bla bla and you know that they mean "we'll rip you more money this year!". Well, like Marcus Gronholm, I think it's time to say I'm fed up (but with these guys that are in charge of my country, instead of with the car).

Finally I've seen someone which speaks the same language as me. I'm talking about Professor Medina Carreira's interview, which really pins down several of the problems that exist in my country. If you understand Portuguese, then you take 30 mins and watch his interview on Jornal das 9.

by luisabreu | with no comments
Filed under:
Silverlight 2.0 is out
Tue, Oct 14 2008 15:38

I’ve just seen this on Scott Hanselman’s blog. I’ll make an effort to look at it, though I’m still not convinced about it…

by luisabreu | with no comments
Filed under:
Book review: the myths of innovation
Fri, Oct 10 2008 21:55

Scott Berkun is really an entertaining writer. Today I’ve just finished reading his last book: The myths of innovation. Scott tries to point out several myths generally associated with innovations and explains really well why they’re myths. With lots of good examples that support his vision, Scott has written a really small addictive book that you won’t let go until you finish. Btw, if you follow the book’s Amazon link you’ll find a link to a short presentation Scott gave on this topic at Amazon. Score: 8.5/10.

by luisabreu | with no comments
Filed under:
Book review: High performance web sites
Fri, Oct 10 2008 21:44

One of the good things about laying down and resting is that you have more time for reading (that is, if you enjoy doing that). In these last couple of days I’ve finished reading High Performance Web Sites: Essential knowledge for front-end engineers. I wish I had this book some six or seven years ago. It would really have stopped lots of silly mistakes and several lost hours trying to improve the performance of my sites. Oh well, never mind…

With a little more over 150 pages (thanks for being so concise), Steve Sounders has written a really cool book with lots of advices on how to improve the performance of your front end. From CSS sprites to JS unifying, there are several rules that you should *really* follow when building sites. If you’re responsible for building web sites, then do yourself a favor and read this book. Score: 8.5/10.

by luisabreu | with no comments
Filed under:
Really smart, right?
Thu, Oct 9 2008 22:50

It seems like some guy decided to rob a car got caught because he had tattoed  his name and date birth on his neck.

by luisabreu | with no comments
Filed under:
RouteValueDictionary: abuse or elegance?
Sat, Oct 4 2008 23:02

Today I was reading an old post by Mike Tauty about the RouteValueDictionary and I remembered some old discussions on the RouteValueDictionary class. As many others, Mike sees the RouteValueDictionary as an abuse of the new anonymous type feature introduced by C# 3.0.

Me: well, I’m not so quick in saying that it’s an abuse. I mean, would you prefer to drop the anonymous type sugar syntax and use the object initializer syntax for passing values to that dictionary? I wouldn’t, but I’m interesting in knowing what others think about this…

by luisabreu | with no comments
Filed under: , ,
Book review: smart and get things done
Thu, Oct 2 2008 22:42

Here’s another interesting book I’ve finished reading. Yes, that is correct: another one (and that’s why you’re getting 2 reviews on the same day:)) When you start using the bus, that means that you have some time for catching up with your reading (and that is what I intend to do in the next months).

There’s one thing you’ve got to admit one thing: you may disagree with Joel, but the guy knows how to write and how to capture your attention! Regarding the book, it’s really a short book (which is good) that has several good tips that you might use if you’re responsible for hiring new guys for your team. If you follow Joel’s blog (I bet that everyone is dropping there at least once a month), then you’ll have a summary of several of his thoughts which are scattered all over the site.

Overall, I’m going to give it 8/10 (yes, I did enjoy it that much!)

by luisabreu | 1 comment(s)
Filed under:
Book review: The naked trader
Thu, Oct 2 2008 22:07

After some delaying, I’ve finally managed to read the Naked Trader: How anyone can still make money trading shares. No, I’m not going to invest all my finances in trading. Why? Well, because I’d only be able to buy 5 or 6 shares :) Thanks for asking!

Ok, so I needed to get some concepts on how things work in the financial markets and I ended up buying two books on the subject. This was one of those and I can say that, overall, it’s really an interesting read.

The author of the book is British, so you’d better get ready for some British humor. You’ll find lots of references on toast and tea :) If you’re not into shares, then this is a good book because the author uses a relaxed writing style and explains you several of the important concepts you need to know if you want to take your chances on the financial market. There’s advice on how to interpret market signs. Interestingly, most of the advices are really based on common sense (you’d think that the guys that put their money on the stock market would have that, but it seems like that isn’t really what happens with most guys).

Besides shares, there’s also some info on spread betting, which I found interesting (who would have thought that you could bet on shares going up or down?). Overall, I’m giving it a 7.5/10.

by luisabreu | with no comments
Filed under:
More Posts Next page »