Tuesday, August 22, 2006

Do not write repetitive code!

About 6 years ago I was doing ASP development. After a while I found myself writing classes and stored procedures that all followed the same structure. This was when I decided to stop writing "repetative" code and instead I wrote a program that would create my ASP and and stored procedures for me. I would still be using my program today except I did not want to maintain the program. Instead I've found something better to do the job! It is called CodeSmith. What you do is create a codesmith template, open it, run it, and either save or copy/paste whatever your output is.

I have create two templates which I will be sharing with you. The first one is a template which will create a C# class based on a sql database table. The second is a template which will create 5 stored procedures which your class uses to interact with the same table. The only catch is that the table must contain one field which is the primary key. When you open these templates check out the properties pane in CodeSmith. In the C# class template there is a property called ConnectionString_Name. You must set this to a named connection from your web.config file. In both templates you will see a property called SourceTable. Click on the field which will bring up the "..." button. When you click on this you can choose your datasource and select a table. If you do not have any datasources you will be able to add one.

Every time I use CodeSmith to generate this code it saves me about a days worth of work. You may also want to check out the CodeSmith template gallery. I hope you will find this as useful as I do.

0 comments: