“Key has already been added” exception with PageTypeBuilder

This is one of those exceptions you get and you know you have had them before but never remember the solution, and googling them doesn’t give you any answers. Time to fix that!

Background

I was in the process of creating lots of new page-types for a new EPiServer  website and suddenly it threw an exception after building and running the site. The exception message I got was “An item with the same key has already been added.” with the following Stack Trace:

[ArgumentException: An item with the same key has already been added.]
   System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +56
   System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +10290303
   System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) +12
   PageTypeBuilder.PageTypeResolver.AddPageType(Int32 pageTypeID, Type pageTypeType) +52
   PageTypeBuilder.Synchronization.PageTypeSynchronizer.AddPageTypesToResolver(List`1 pageTypeDefinitions) +159

What we can understand from the above Stack Trace is that when PageTypeBuilder adds a new page-type to the dictionary it fails because another item with the same key already exists. My colleagues and I were determined this key must be the page-type GUID that you specify in the attribute of a page-type. I opened the database and deleted all page-types directly, and then changed the GUIDs in my classes. This has to work – but it did not.

Solution

I gave up and continued working with my page-types. After a few minutes I found a page-type with an incorrect name – it was a duplicate of another page-type! I changed it to the right name and ran my site. Everything worked! I had been affected by the “copy-paste error”.

To sum it up: Every page-type must have a unique Name property or else it’ll fail in runtime.

It would be nice if PageTypeBuilder threw a friendly exception if the key already exists. If the exception message also mention which page-type (by ID or name) it would be really easy to find and solve the problem.

Maybe it’s time to submit a patch to the PageTypeBuilder project?

published in PageTypeBuilder, ASP.NET, EPiServer