C#
Dynamic objects and ReSharper

 

As you might have heard by now, C# 4.0 (or is it just 4?…) comes with a new keyword: dynamic. This means that you could do something like the following:

image

Simply put, ExpandoObject is a class that allows you to add and remove members at runtime. This allows us to call methods that are resolved at runtime. As such, the previous code will compile.

Just as you can declare methods, you can also declare properties:

image

This no doubt can come in handy when working with ViewModels and ASP.NET MVC.

However, there is one minor problem with dynamic objects: you lose intellisense, which means that if in your view, instead of typing dynaCustomer.FirstName, you type dynaCustomer.FristName, you won’t get any errors until you run the app.

image

And that’s where ReSharper can help:

image

This is the same code, but with ReSharper activated inside Visual Studio 2010! I typed the FirstName property for the first time. After that, I have full intellisense support for it. The same would apply to methods:

image

That puts dynamic into perspective.

18 Comments Filed Under [ Tools C# ]
It’s all about the delivery


The Dependency Inversion Principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

(Source WikiPedia).

Throw that at a terrible programmer, and all you’ll get is a terrible programmer that is annoyed and hates you. So true!

Take the following method:

        public void PrintHelloMessage()
        {
            Console.WriteLine("Hello");
        }

Now ask a developer to add a new method to print the message ‘Goodbye’. Do you think he would do:

        public void PrintGoodbyeMessage()
{
Console.WriteLine("Goodbye");
}


or:

        public void PrintMessage(string message)
{
Console.WriteLine(message);
}

Most likely, he’d do the latter. Why? Because he realizes he’s gaining a benefit by passing a parameter to a method. He knows that if tomorrow you ask him for a “Good Afternoon” message, he won’t have to write a new method.

What is Dependency Injection? It’s one way of complying with the Dependency Inversion Principle. However, when you think about it, what does it boil down to? Passing a parameter to a method, which happens to be a constructor. It seems simple enough doesn’t it? Yet, it’s hard for people to understand it. Why? because they don’t see the value in it.

Explaining a principle to someone without them understanding the benefits and values they get out of it is useless, and that is why concepts such as Dependency Injection or Inversion of Control seem overly complex to the vast majority of developers (believe it or not, those of us that use these things are still a very big minority). It’s complex because they haven’t been explained the values of it. They’ve just been thrown some definition and they are expected to understand that it’s bad for one class to create an instance of another class it uses.

Present a developer with the following code:

    public class AuthServices
    {
        public void AuthUser(string username, string password)
        {
            var authDAL = new AuthDAL();
 
            var user = authDAL.GetUserByUsername(username);
 
            if (user != null)
            {
                if ...
            }
 
        }
    }

and ask them how they’d go about testing this code without having access to a database. Ask them how they’d go about changing AuthDAL for some fake DAL that doesn’t really connect to a database.

They’ll probably come up with the solution of passing the AuthDAL class in as a parameter, and eventually realizing that multiple methods will use the same class, they’ll pass it in via the constructor and set it as an instance field. As long as their AuthDAL has virtual methods, they can create any fake DAL that overrides those methods and returns some dummy value. They might argue that they don’t want virtual methods. And that’s fine. Tell them to define the parameter as an interface. In fact, they probably have already heard of a principle that says that you should program to an interface and not a class. They’ll eventually end up with this code:

  public class AuthServices
{
IAuthDAL authDAL;

public AuthServices(IAuthDAL authDAL)
{
_authDAL = authDAL;
}

public void AuthUser(string username, string password)
{
var user = _authDAL.GetUserByUsername(username);

if (user != null)
{
if ...
}

}
}

 

And voila! You have Dependency Injection via Constructor.

Once they *get* that, then explain to them other benefits, you know the real benefits they get from doing this: decoupled code, easy maintenance, promotion of SRP, etc.  and then throw the principle in their face:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

And they’ll see how it all makes sense.

It’s not about throwing or not throwing books. It’s about showing people how something can help them, how they get value of it.

Upcoming talks

 

Start of the “conference season” again and I’ll be doing a tour of a few countries and places. Hope to meet up with some of you at some place and time. This time I’ll try and have all sessions ready so I can spend my time more productively at the bar/restaurant

- 21st to 25th September at BASTA! in Germany. Talks on ASP.NET MVC, jQuery, TDD, Design Principles.

- 27th to 30th September at Entwickler Konferenz in Germany. Talks on ASP.NET MVC, TDD.

- 12th to 13th October at DevReach in Bulgaria. Talks on ASP.NET MVC, Design Principles.

- 16th to 17th October at TTT/CodeCamp in Tarragona. Talks on MEF and Design Principles.

- 18th to 21st October at SDC in The Netherlands. Talks on ASP.NET MVC.

- 29th October at Micrsoft in Madrid. Workshop on Design Principles (Link available soon)

I’ve also pre-recorded 3 sessions for an online virtual conference on ASP.NET MVC, jQuery and Mocks, all in Delphi Prism and it’s happening right now on CodeRage

 

 

-

Spanish Keyboard layout for C# Developers

 

I use a Spanish Keyboard which is kind of a nuisance when developing in C#. It’s mainly due to the key layout for curly braces. Every time you need curly braces, you have to press AltGr (Ctrl+Alt) along with another key. Other annoying keys are the semicolon and the square brackets.

image

(Image licensed under the Creative Commons Attribution ShareAlike 3.0, obtained from Wikimedia Commons)

So after years of frustration, I finally decided to call it a day. Today I ran into the Microsoft Keyboard Layout Creator which allows you to create custom keyboard layouts. It’s pretty simple to use and extremely flexible since it allows you define dead keys also (which was part of the my problem when attempting to do it manually using the Scancode Maps). You can change key mappings or define a whole new keyboard layout from scratch.

My new mapping is based on the original Spanish layout, switching the key combinations required for curly braces and square brackets. Instead of getting a tilde by default, you now get braces and brackets. If you want the original characters, you need to use AltGr. I’ve switched the semicolon and comma around also. You no longer need to use shift to obtain a semicolon. I’ll see how it works out, although I must admit while writing this post, every time I’ve wanted to insert a comma, I’ve ended up with a ;

The tool creates a convenient executable so that you can install the new mapping on any machine without a lot of fuss. I’m including both the executables (x86, 64bit, etc.) along with the project file to this post. Feel free to use it or adjust it to your own needs. Get it here

3 Comments Filed Under [ C# ]
Fluent NHibernate

I've recently started a new internal project and decided to use NHibernate. I've used NHibernate previously on several projects and one of the things I didn't like was the mapping. That's where you waste the most time and for refactoring it sucks. Every time you need to create a new property or change an existing one, you need to make sure you've updated the XML mapping file.

I had decided to check out the fluent nhibernate project that I had heard about. I thought even though it didn't do away with the mapping, at least you had it in code, so you could easily refactor and do away with some of the mapping errors you initially face. Luckily before I started this project, I ran across Ayende's post on the new Auto-Mapping features of Fluent NHibernate, and I must say, I've been blown away (my twitter followers are probably starting to get sick of me).

I'm now able to do true TDD without having to touch a line of SQL or XML. The only reason I open up SQL Management Studio is to just make sure that the automapping is working correctly, and it is. It handles one to many, many to one, many to many, anything you could think of. And the beauty of it is, that if there is something it can't handle, you can still map it yourself in code.

Take this class:

 

   1: public class Customer
   2: {
   3:     public virtual int Id { get; set; }
   4:     public virtual string NameFirst { get; set; }
   5:     public virtual string NameLast { get; set; }
   6:     public virtual ICollection<Invoice> Invoices { get; set; }
   7: }
   8:  
   9: public class Invoice
  10: {
  11:     public virtual int Id { get; set;}
  12:     public virtual string Number { get; set; }
  13:     public virtual DateTime Date { get; set; }
  14:     // Rest omitted...
  15: }

 

The only thing I have to do, to configure this is:

 

   1: persistenceModel.AddEntityAssembly(assembly)
   2:     .Where(entity => entity.Namespace == "iMeta.Example.Domain.Entities" && entity.GetProperty("Id") != null)
   3:     .WithConvention(convention => convention.GetForeignKeyName = p => p.Name + "Id")
   4:     .Configure(config);


That's it. The only thing that I don't seem to know how to handle yet is components. For now I'm adding some manual mapping (something I'm missing?). So for instance, if Customer has an Address property like so:

   1: public class Address 
   2: {
   3:     public virtual string Street { get; set;}
   4:     public virtual string City { get; set;}
   5:     public virtual string State { get; set;}
   6: }

and the corresponding property on Customer:

   1: public class Customer
   2: {
   3:     ...
   4:     public virtual ICollection<Address> Addresses { get; set; }
   5: }

the resulting configuration would be (line 4 is new):

   1: persistenceModel.AddEntityAssembly(assembly)
   2:     .Where(entity => entity.Namespace == "iMeta.Example.Domain.Entities" && entity.GetProperty("Id") != null)
   3:     .WithConvention(convention => convention.GetForeignKeyName = p => p.Name + "Id")
   4:     .ForTypesThatDeriveFrom<Customer>(map => map.Component<Address>(t => t.Addresses,
   5:                                                                          c =>
   6:                                                                          {
   7:                                                                              c.Map(t => t.Street);
   8:                                                                              c.Map(t => t.City);
   9:                                                                              c.Map(t => t.State);
  10:                                                                          }))
  11:     .Configure(config);

If you don't add this, it will create a table in the database of type Address and reference the customer with a foreign key, as opposed to flattening out Address to fields in the Customer table.

If you combine all this with a call to SchemaExport (Nhibernate Tools namespace), you can have it create your database schema for you. Do this in your tests and you no longer have to worry about cleaning up your database before each test or creating scripts that need to be run as part of your CI build. Very cool!

StructureMap System.InvalidProgramException

I just upgraded to the latest release of StructureMap (2.5) and spent a good portion of time trying to figure out a bug I was having in a complex dependency graph. The original exception is a StructureMap exception, with code 207, which per documentation, you need to look at the inner exception. The problem is that the inner exception isn't awfully helpful:

System.InvalidProgramException : JIT Compiler encountered an internal limitation.

Initially I thought it was related to the WithCtorArg method that allows you to pass in parameters to the constructor, but after stripping everything down to try and come up with a test case, it seems that the issue occurs when you have a class that the container resolves which has a public static property, like so:

   1: public interface ISomeClass
   2: {
   3:     void SomeMethod();
   4: }
   5:  
   6: public class SomeClass : ISomeClass
   7: {
   8:  
   9:     public static int SomeProperty { get; set; }    
  10:  
  11:     public void SomeMethod()
  12:     {
  13:     }
  14:  
  15:  
  16: }

 

Here's the StructureMap configuration test:

   1: [Fact]
   2: public void TestStructureMap()
   3: {
   4:     ObjectFactory.Initialize( x => x.ForRequestedType<ISomeClass>().TheDefault.Is.OfConcreteType<SomeClass>());
   5:  
   6:     ObjectFactory.GetInstance<ISomeClass>();
   7: }

 

As soon as you make the property private or make it an instance property, the container resolves fine. I tested the same thing with Unity and there doesn't seem to be an issue.

I tested the same code with 2.4.9 and it seems to work.

Add Comment Filed Under [ C# IoC ]
Design Principles event next month in Belgium

I'll be doing a talk in Belgium next month at the Visual Studio User Group, where I'll be covering topics such as Separation of Concerns, Single Responsibility, Interface Segregation, Dependency Injection and Inversion of Control, along with examples of IoC containers. There's limited space (90) and already 55 signed up, so if you're in or around the neighbourhood, got nothing better to do than here my brag, come along. I think they are organizing a geek dinner afterwards so it should be fun. Although the talk will be in C#, the important things to grasp are the concepts, not the language, be it Visual Basic, Delphi or whatever else (obviously it needs to be a OO language).

Linq to Sql is dead. Did you abstract well?

Here's an update on the roadmap for Linq2Sql. The post is pretty much confirming that they're killing off the project.

A project we started recently, we had to make a choice of which ORM to use. Since Entity Framework wasn't still up to par (and in certain aspects probably still isn't), and the team had experience with Linq2Sql, we decided to use that. However, from day one, we made a conscientious choice of not leaking anything of L2S into our domain objects.

This meant that we didn't use the L2S objects, but in turn used our own POCO classes. Therefore the sole purpose of L2S was to map data from the DB, what the job of an ORM is. Recently, and before the announcement, we found a lot of shortcomings when working with L2S and aggregate roots (I won't get into the details since Steve is planning a series of posts on the subject and how to handle aggregate roots with the different existing ORM's). We've therefore decided to switch ORMs. The beauty of it is that because of the clear abstraction of L2S, it's going to be very easy to swap out L2S for another ORM.

Now that we have confirmation that L2S isn't going anywhere, if you have issues with the current version and were hoping to get them resolved in a future release, I guess you're out of luck. So the time comes to move on. If you've abstracted well, it shouldn't hurt that much.

Obviously if you don't have issues with L2S and no projections on needing new features, then stick to what you have. "If it ain't broken, don't fix it". But don't start any new projects with it. Even Microsoft don't recommend it anymore.

Optional Parameters in C# 4.0

Steve mentioned in his last blog post, the dynamic features of C#. Well there's another feature that's coming which is optional parameters and default values. Coming from a Delphi background, we've had optional parameters for a very long time and I've used them a lot. What are your thoughts on them?

In case you're not familiar:

   1: public void SomeMethod(string name, string surname, int code = 100);

 

If you call SomeMethod with only two parameters, the third one will have the default value of 100.

6 Comments Filed Under [ C# ]