Beads 594671 1280

The story is one you probably know very well: Client is in a hurry, so we open the back-end to them in order to be able to enter data while the site is still in development, provided of course that the needed document types are ready.

(Don't say you haven't done it even once, I won't believe you).

The client starts adding, let's say, products, a LOT of them, and they're in the hundreds when you discover that the doctype you used for products does NOT yet have a default template (because you hadn't created it at the time you gave your client access to the back end). So, all those entries display that horrible "Choose" in the dropdown inside their Properties tab, where a selected template option should be. 

And, what's worse, even if you assign a default template at a later time, Umbraco will not update existing documents. You just have to edit and change the template for each one by hand.

So this has happened to us more than once, and I started thinking that there should be an easy way to deal with it instead of hacking SQL queries or writing execute-once code for Umbraco to fix it. 

I wrote this. PLEASE BACKUP YOUR DB before running it!

What it does is iterate all documents that do not have a template defined, look if their document types have a default template, and assign that template to the documents. (If a document's doctype does not have a default template, then nothing will happen). Oh, and of course it will run on application start only, so touching your web.config file or restarting your site will do the trick. It even logs what was changed so you can have a quick look afterwards. 

This code does this for ALL documents, so purposefully template-less documents may be assigned a template if there's a default template for their doctype. Use at your own risk.

You can include this file as-is in your app_code folder or integrate it into a separate project in Visual Studio. Wiith a few changes, it can even be adapted to do different things, like for example bulk-change templates for a specific doctype.

This code is usually needed to run once (or just a few times) while developing the site and probably should not be in a production site, especially when there are thousands of nodes, due to the time it takes to query the whole tree. I haven't made it "clever" in this context, but you can, of course, change it and evolve it to your liking.

Did I mention that you should BACKUP YOUR DB before including this in your site? I did.

Happy coding!