Monday, July 19, 2010

Code Generation with VS 2010


Have been off for quite some time, so its good to be back  blogging. I will start off with a relatively light post.

All of us know that you can create Architectural Diagrams in VS 2010 using the architecture menu. But once, you have done creating the diagrams how do you actually make the diagrams generate code? The last thing you want to do is to create the diagrams and write the code for it manually.

Though VS 2010 does not have built in support for code generation, you can have it generate code by downloading and installing Visualisation and Modelling Feature Pack.

Once you download and install the feature pack from the link above, there are a couple of small things you have to do to get your diagrams ready for code generation. The first thing is to set a profile to your model. i.e tell the model which language to generate code.

You can do this by viewing the properties of the model explorer. You should see an attribute called Stereotypes as shown in the diagram below.



Select C# namespace. As you can see, the whole code generation works on T4. So if you want to have code generated in SQL for example you could just write your text transformation templates and you should be ready to go.

Actually, there is a very good blog here on how exactly to write your own T4 templates for code generation.

Once you have done that, you can then configure how your classes and namespaces should be named and organised. You do this by clicking on Architecture-> Configure Default code generation settings.


Beware, by default, the namespace is always the name of the model so be wary when you name the model because once you set it, you will not be able to change it. You should now be ready to start generating code. Right click on your modelling diagram and you should see a generate code menu as shown. You can set the path under which you want the class to be generated here.



1 comment: