Renewed MVP

Excellent! I've been renewed as MVP C# for the 2nd year. I enjoy a lot working with the community and it's great to get this award. 

Thanks Cristina et al.

2 Comments Filed Under [ Various ]
Integrating OpenID and ASP.NET MVC

OpenID (Microsoft Passport done right), is gaining a lot of popularity and it's common to see it integrated into new and existing web sites. For those not familiar with OpenID, here's a quote from the web site:

 

For geeks, OpenID is an open, decentralized, free framework for user-centric digital identity. OpenID takes advantage of already existing internet technology (URI, HTTP, SSL, Diffie-Hellman) and realizes that people are already creating identities for themselves whether it be at their blog, photostream, profile page, etc. With OpenID you can easily transform one of these existing URIs into an account which can be used at sites which support OpenID logins.

I'm currently working on a project with ASP.NET MVC and since it requires a login, I decided to offer the option for users to use OpenID as a means of authentication. The "de-facto" library of choice it seems is .NET OpenID which is available on Google Code. It actually comes with a demo of how to use it with ASP.NET MVC but I have a feeling it was done with the very first CTP of MVC since there are direct accesses to the form object, etc. which isn't really necessary. Having said that, the library is extremely easy to use and I was up and running in about 5 mins. You can download the updated demo below. The code is extremely straight-forward, but if you have trouble understanding anything, just ping me.

Add Comment Filed Under [ Security ASP.NET MVC ]
Multiple Value types with Fluent NHibernate's AutoPersistenceModel

The AutoPersistenceModel in Fluent NHibernate doesn't support values types automatically (yet), but getting them to work isn't that difficult. Take the following example:

 

   1: public class Company
   2: {   
   3:     public virtual int Id { get; set; }   
   4:     public virtual string Name { get; set; }   
   5:     public virtual ICollection<Contact> Contacts { get; set; }   
   6:     public virtual ICollection<Address> Addresses { get; set; }   
   7: }   
   8:  
   9: public class Contact   
  10: {  
  11:     public virtual string NameFirst { get; set; }  
  12:     public virtual string NameLast { get; set; }  
  13:     public virtual string Telephone { get; set; }  
  14:     public virtual string Email { get; set; }  
  15: }  
  16:  
  17: public class Address   
  18: {  
  19:     public virtual string Street { get; set; }  
  20:     public virtual string City  { get; set; }  
  21:     public virtual string State { get; set; }  
  22:     public virtual string Country { get; set; }  
  23: }  

 

Contact and Address are value types, that is, the only way to get to them is via the aggregate root, which is Company. Here's the AutoPersistenceModel of Fluent NHibernate:

 

   1: persistenceModel.AddEntityAssembly(assembly)
   2:                 .Where(entity => entity.Namespace == "iMeta.Examples.Domain.Entities" && entity.GetProperty("Id") != null)
   3:                 .WithConvention(convention => convention.GetForeignKeyName = p => p.Name + "Id")
   4:                 
   5:  
   6:             .ForTypesThatDeriveFrom<Company>(map =>
   7:                                                {
   8:                                                    map.HasMany<Contact>(t => t.Contacts).Component( c =>
   9:                                                                                     {
  10:                                                                                         c.Map(t => t.NameFirst);
  11:                                                                                         c.Map(t => t.NameLast);
  12:                                                                                         c.Map(t => t.Telephone);
  13:                                                                                         c.Map(t => t.Email);
  14:                                                                                     }).AsList();
  15:                                                    map.HasMany<Address>(t => t.Addresses).Component(c =>
  16:                                                                                    {
  17:                                                                                        c.Map(t => t.Street);
  18:                                                                                        c.Map(t => t.City);
  19:                                                                                        c.Map(t => t.State);
  20:                                                                                        c.Map(t => t.Country);
  21:                                                                                    })
  22:                                                        .AsList();
  23:                                                    
  24:                                                })
  30:                .Configure(config);

 

We are using telling the AutoPersistenceModel that for types that derive from Company (currently there is no support for inheritance but its named like this for future support), map the Contacts and Addresses properties to a collection of components. That simple!

I'm assuming, and hoping, that in future versions this will be supported automatically so there won't be a need for this. 

Add Comment Filed Under [ nhibernate ]
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!

XAML Power Toys

I've been dabbling in WPF lately. Nothing too fancy, just fixing up some parts of an application we're currently working on and integration with Reporting Services. One of the things that is quite time-consuming in WPF is layout, specially when it comes to laying out business forms (i.e. a set of fields on a form to collect data). An alternative to a writing all this by hand (or using some flavor of Expression) is to use the XAML Power Toys, which generates the XAML for you based on a series of input values.

Instead of explaining all the cool features it has here, just go to the site

Add Comment Filed Under [ Productivity WPF ]
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 ]
Agile is not Chaos

There is a human tendency, albeit a bad one, to stereotype. Take for instance the words traffic and chaos. In many cases, you can imagine a chaotic crossroad in India or China, with people and cars crossing in all directions. It's not because there aren't traffic jams anywhere else in the World, it's because of stereotyping. We are constantly sent links and funny videos of horrendous traffic jams in certain countries, and that is why these images come to mind. 

image

Take for example the above image. I found it by typing in the words "traffic jam" in Flickr. It was the first one that popped up. Do the same in Google or any other search engine for images. You're bound to get a large proportion of similar images. I didn't even have to use the word chaos.

Consider a Project Manager, could be of any type of project, but for the sake of this post, and seeing that not only myself but many of my readers are somehow involved in software development (except those that find my blog because of this post or this post), we'll consider the project is software. John, the Project Manager has been accustomed for many years to the Waterfall Methodology. There is a clear and precise line of what a project should consist of and a diagram of how it should be performed.

image

One fine morning, Bill, the CEO, calls John into his office and says

John, I read this thing on CEO High Flyers'  magazine on the plane yesterday, called Agile. I want us to do it too. I'm not sure what it is, but I'm hearing good things about it. Let's become Agile.

So John goes back to his desk and starts to look up this whole Agile thing. He reads a little bit about XP, some things on Scrum and goes back to Bill the next day.

Bill, this Agile thing is insane. It's pretty much anyone does whatever they want and there is no control at all. Take this: they've got this "methodology" called Scrum, where people don't even get tasks assigned. You believe that? And there is absolutely no clear design phase, no testing, it's completely and utterly absurd. It's just chaotic.

Bill wasn't too amused. No tasks assigned? No control over who does what? Anyone can do as he or she pleases? Nonsense. He'd have none of that.

John at this point felt relieved. He'd been running projects using Waterfall for years, and albeit, yes they did run a little late, yes, sometimes the customer didn't really get what he wanted, yes many times the actual design had to be thought out again, but there was control. As long as there was control, it was ok. Agile on the other hand just seemed chaotic.

Stereotyping is also caused by lack of understanding, by being prejudice.

Is John to blame? Not at all. John was a developer himself once and he's been "brought up" one way. He'd constantly been shown that the only way for a project to succeed was to have a clear definition of what each person's role in the project was, what the exact phases were and what he had to work on at any given moment. To now throw that all away and take on an approach such as SCRUM where there is no task assignment, there are no clear boundaries between requirements, design and implementation, seemed too chaotic.

But is it really chaos? Is Agile about disorganization? Is Agile about no up-front design or testing? Here is where it gets difficult. Agile is like SOA, depends who you ask, at what time, at which location and you get a different answer. All of them are similar, but each person gives his or her definition of the word.

To define Agile in one sentence, Agile is about adapting to change.  Agile is not SCRUM. Agile is not XP. Agile is not about throwing design or testing out the windows. Agile is about being flexible, about being adaptable. How you go about doing that is another matter.

Waterfall does not fit in with Agile because it is rigid. There is a clear distinction about the different phases in which a project should be executed. By stepping outside of those phases, or going back, you are essentially breaking the methodology.

SCRUM is an alternative to Waterfall that fits in with Agile methodologies. Why SCRUM works and how it improves over traditional software management methodologies has largely to do with the people behind the project. I've covered two essential qualities that a team should have previously in a post about multi-disciplinary and confident and reliable team members.

However, the path to adopting SCRUM or any agile methodology is not easy. It takes time and discipline. The benefit though is that the ROI is very high.

What SCRUM is and the advantages it has over Waterfall, both for the team and ultimately and more importantly for the outcome of the project is best left to a future post. What is important to understand though is that Agile is not chaos, nor is it about doing away with practices. Try and not stereotype it.

and there's no opting out...

Just noticed this under one of the Build failure notification e-mails received from the TFS daemon:

 

- You are receiving this notification because of a subscription created by xxxx\Hadi Hariri Provided by Microsoft Visual Studio® Team System 2008 <http://msdn.microsoft.com/vstudio/teamsystem/>

 

Notice there's no "If you do not wish to receive future notifications please....."

 

Nope, you're screwed. Your best bet is to not break the build...or break me!

Identify code smells with tags

Visual Studio comes with TODO markers where you can mark sections of code with little comments to indicate that you need to do something. However, TODO sometimes becomes too generic. You start to mark tasks, features, futures, (bugs have their own by default) with the same tag. Fortunately you can add custom ones. If you have Re-sharper installed, you get additional benefits since it allows you to create filters, identify the tags inside comments and highlight them on the right margin.

One tag to add is SMELL. A code smell is a piece of code that works yet it just isn't right, and you know that the longer it's left in there, there worse it can get. It can lead to an unsustainable situation where the whole project can start to smell like a dump site. Other times it's just a small section that is isolated and won't have immediate side-effects, but would be good to get it cleaned up.

Now, I know the purists would probably scream and say that any smell should be eradicated then and there. Snap back to reality. Both you and I know that that's not always viable. Having said that, If it's a bad smell that can lead down a spiral of stink, then yes, it should be, taking into account schedules, etc.. but even in that case, you're not going to do it all at once, so you still need to identify the smells as you go cleaning them up.

Here's some screen shots of smells with Resharper

image

To define them, use Resharper's To-Do item entry

image

You can also see on the To-Do Explorer

image

TechEd Online Interview on ASP.NET MVC

While I was at TechEd in Barcelona last week, I had a chance to sit down with Mark Dunn from .NET Rocks and talk a little bit about ASP.NET MVC and jQuery. They've recorded the interview. You can watch it here