[This was originally posted at
http://timstall.dotnetdevelopersjournal.com/batch_code_generation_with_codesmith_console.htm]
I'm always keeping my eyes open for practical tools that save time and mental sanity. One of the most mentally-draining tasks is repetitious modifying of simple code. For example, many simple CRUD (Create-Read-Update-Delete) stored procedures, and their accompanying DAL and Business Objects are redundant. Ideally we could just auto-generate this given the inputs. Auto code generation is a great time saver, which frees us from boring tasks to focus on interesting ones.
CodeSmith is a great code generator. It has both a free and purchase version, it has a large support community, is time tested (been out for several years now), and has great functionality. It's based around writing templates with ASP syntax, which is much more friendly then using XSL or writing your own C# app to assemble the target code. Therefore part of a CodeSmith template may look like:
private void <%= SampleStringProperty %>() { // <%= GetSomething() %> // Do something }
|
There are plenty of tutorials about auto-generating your data access layer. But one thing I really like about CodeSmith is its batch processing. These are features I'd like in batch processing:
- Ability to call the tool from a command line, passing in an Xml config file
- Extend step 1 to generate many objects from a single Xml file, as opposed to calling the exe each time.
- Ability to merge your changes into an existing, non-generated document.
- Ability to auto-generate a document, but leave certain sections open to customization
The first two help with batch processing, such that you could generate an entire layer at once. The last two help with versioning and customization. You need to both made custom modifications to templates, and then not have those overwritten upon re-running the tool.
CodeSmith offers both several help guides, and samples, to assist with these. Check:
- CodeSmith Console Tutorial in the CodeSmith Studio's Help section
- Samples at: "CodeSmith\v3.0\SampleProjects\ConsoleSamples\GenerateCode.bat"
If all you have is a hammer, everything looks like a nail. With a good code-generation tool, you start viewing all those redundant tasks very differently.