Friday, October 29, 2010

Code Generation Using Custom Item Template, Custom Template Wizard and T4 Engine

Not long time ago, I faced the following requirement:

Company uses custom Data Access Layer, which is developed within company and which does not have any designer tool as Entity Framework or Linq to SQL frameworks have. (Actually the company uses CSLA – but it is modified and cannot be upgraded to latest version even if latest version of CSLA does have any designer tools – but as I know it does not)

The goal is to simplify the creation of new business objects along with data access code.

It is preferred o collect data about business object to be created in some kind of visual form and then generate the business object.

It is also desirable to add business object to Visual Studio solution automatically.

Before they used MyGeneration software, which is separate application running outside of Visual Studio. They had to generate code in it and then manually place the files into VS solution.

After investigating and evaluating few approaches – I stopped on the following:

1) I will use Custom Item Template for Visual Studio to import files into VS solution by using standard VS Add New Item dialog

2) I will use Custom Template Wizard to collect data before adding item to VS solution.

3) I will use T4 Engine to generate artefacts based on data collected in Custom Template Wizard and T4 templates that are predefined. I will use stand alone Custom Template Host


The process of business object creation after implementation looked like this:

Developer runs Add New Item dialog in WPF project:


Developer selects our Custom Item Template:


Developer provides name of business object to create:


After developer clicks Add – he is presented with our Custom Template Wizard:


Here developer can design the entity – set name, type (along with storage type – DBType, default value, mandatory status, whether it is foreign key – so it must be used in query method as parameter, whether the property is key etc.)

Here is a data model accumulated per business object line (property) :


Some pic with tooltips to attributes: image

This form also does validation of data entered by developer:

so When property IsAutoKey, it cannot have default value:


Key property cannot be Nullable:


Length is only enabled where applicable to data type:



Validation is applied to property name as well:



Some other validations:






When developer finishes entering business object data he can:

1) generate C# objects and add to solution right away

2) OR first generate SQL procedures for business object


Let’s review 2nd point.

To farther simplify SQL code execution, the Custom wizard also has ability to connect to DB and retrieve metadata for tables/views from it.

To connect to DB, you must provide parameters:


The parameters are stored per machine – so once set up – they will be in effect for any solution / instance of VS.

On this stage we can also import metadata from DB table/view and populate business object properties data.

Just click Import:



On the popped up window developer can choose table/view to import columns from.


When importing from DB table/view, business object name also changes on top:


Developer can choose to generate many types of BO – as RO, Writable, Root, Child etc. – every single one will be generated under the hood by using separate T4 template.


On any stage of working in Custom Wizard Form – the developer can generate scripts for business object:



In this window the following scripts are generated:

Table, Select SP, Update SP, Insert SP, Delete SP

The tool can be extended to have more scripts with any contents – as each script is generated from separate T4 template.

Developer can save any script on this stage:


(unfortunately developer will have to check in the file to source safe manually)

If developer clicks Execute, he will be able to run script right away:


And now the most important part Smile

Developer clicks “OK”, and business objects will be generated and inserted to VS solution at correct place automatically:



Now the architecture.


The code generates from T4 templates -



Each template is provided with custom data accumulated by wizard. The templates use data to generate code.




Hope this idea helps you deciding to use code generation in your projects : )


Now about technical implementation.


You (or any developer that wants to start using this) must build the project attached in the end of this article once – and that is it – it registers Custom Wizard, and zips template and copies it to templates directory for VS (see pre and post build events)




you can get complete source code (


Enjoy :)

Hope this helps


kick it on

Thursday, October 28, 2010

C# Coding Standards, What Standards Do You Use?


Coding standards is important to have in any software organisation.

Here is definition for “Coding Conventions” from Wikipedia:

Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices and methods for each aspect of a piece program written in this language. These conventions usually cover file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices and etc.Software programmers are highly recommended to follow these guidelines to help improve the readability of their source code and make software maintenance easier. Coding conventions are only applicable to the human maintainers and peer reviewers of a software project. Conventions may be formalized in a documented set of rules that an entire team or company follows, or may be as informal as the habitual coding practices of an individual. Coding conventions are not enforced by compilers. As a result, not following some or all of the rules has no impact on the executable programs created from the source code.

The Coding Standards document can be agreed to be respected in scope of separate project or in scope of all projects made within software company.

I tried to compose some kind of document myself.

It was internal and contained a lot of specific things, but I cleaned up the parts with specific points and left only main guidelines to publish on my blog.

Please let me know what do you think, Do you agree? Or you are not?


“Presentation Framework Coding Standards”

This document contains details on the following points:

· General Guidelines

· Naming

· Spacing

· Region names

· XAML markup formatting

General Guidelines

Don't write too long lines of code - they are not easily readable.





Don't write methods having bodies longer than 2 screens in height, - it may be a signal to split the method into two parts.

Leave commented code in class bodies only if commented code was never checked in (cannot be restored using source control). Otherwise - please always cleanup the classes from commented blocks of code.

Try to avoid the following code to improve readability:


Try to use instead brackets - they distinct the executing area more efficiently.:


Don't place two Classes/Stucts/Enums/Interfaces into one file, unless one class is member of another class.

Always explicitly provide access modifiers for any class level members.


We use the following naming rules when developing code in C# in UI projects:

Use Pascal casing for Class, Struct, Enum names





Use Camel casing for local variables and method parameters





Use "m" prefix for class level variables





Always name the variables using informative names, never use cryptic names.







Always start interfaces with I, followed by uppercase name of an interface (Pascal casing)





Name private, protected, internal and public methods using Pascal casing:





Don't use underscore in class variables, properties, methods, and any item name in presentation framework except resource keys and constants.





Attributes must end with "Attribute" suffix.

In UI application modules:

· Views must end with "View"

· Shells must end with "Shell"

· View Models must end with "ViewModel".

For resource keys of resources:

· Use keys "Command_<CommandName>" for Command-related resource

· Use "<ViewName>_<Key>" for string resource used on the view

· Use "<SomeGroupForTerminology>_<Key>" for string resources having meaning and used in whole system - here SomeGroupForTerminology will be grouping having some meaning - for example : "Prompt_AreYouSure".

Please use image names as follows:

· Use Pascal casing

· Don't use spaces or underscores in image names

· End image name with dimension if image has equal height and width (MyDocuments32.png)

· End image name with "<Width>X<Height>" if image width does not equal to its height (MyDocuments32X30.png)

Name constants using Camel casing when constant is local

Name all other constants using Pascal casing.

Name enumeration members using Pascal casing.

Please don't use Hungarian notation anywhere in presentation framework code except template part names in custom controls and resources (see above).

Please use the following naming for template parts in custom controls:



Use exactly one empty line between

· Methods

· Properties

· Region boundaries

· Regions







Don't use more than one empty line in any code in UI framework. It regards to code in method bodies, in property bodies etc. The code becomes extremely unreadable when empty lines are overused. This is because less code can be seen at one screen at once. To see more code and understand more developer has to scroll the editor.





Hint: Use Ctrl + K + D to format code

Region names

We use normally the following region names:

· Class level variables

· Constructors

· Properties

· Methods

· Overrides

· Actions

· Commands

· Event handlers

Please use new region names only if you cannot find appropriate name in the list above.

Please don't use quotes in region names, as:


Please always use regions when un-collapsed area becomes too large (let's say 300 lines). - in this case please use regions to farther categorize and sort the code so the functionality can be easily found.

Please never place the member to inappropriately named region.

It is very hard to find a member if it is not placed in logical place, for example placing Delete command into SaveCommand region.

Please use region for each new command declaration and related code.

Don't have duplicate regions in a single class - for example be careful to not have two regions named same name in one class.


Normally when nesting regions we use logical names (functionality-related) or names of main member (example-SaveCommand) for new region. Please place this kind of regions inside main regions listed above.

We use also separate region for each member Class of Struct or Enum:


XAML markup formatting

Please setup the following options in you Visual Studio options to make possible automatic formatting of XAML markup code once Ctrl + K + D is pressed.

1) clip_image056

2) clip_image058

3) clip_image060

4) clip_image062

Please don't use custom formatting as other UI developers will likely re-format XAML files to improve readability.


Update: link to Design Guidelines for Class Library Developers by Microsoft.


Please let me know what do you think