IDE Team Discussion - Using CodeRush Templates to Generate Code

CodeRush users interested in creating templates that generate custom code based on elements inside a container (e.g., fields in a class, methods in a type, types in a namespace, comments in a file, etc.), might want to check out this YouTube video.

In it, the IDE Team discusses some work we're doing, where we need to add custom code to serialize and deserialize the fields of around 30 classes. The solution came in creating a template that iterates through the fields in each class and generates the appropriate serialization or deserialization code for each field.

The main template looks like this:

«:ccsr»

public override void WriteData(BinaryWriter writer)
{
 base.WriteData(writer);
 «ForEach(Field in this, WriteField)»}
 
public override void ReadData(BinaryReader reader)
{
 base.ReadData(reader);
 «ForEach(Field in this, ReadField)»}

Both the ReadField and WriteField templates will be called once for each field in the active class. Both of these templates have a number of alternate expansions. The expansion ultimately selected for a particular field is determined by context. You can set context with the Context Picker on the lower right of the Template options page.

To make this work, we created a new context, called TypeImplements, because many of the scenarios we needed to respond to were dependent upon the type of the field. For example, one of the alternate expansions for ReadField has this context:

TypeImplements(«?Get(itemType)»,System.Boolean)

You can pass parameters to contexts (like we've done here), by right-clicking the context in the Context Picker, and selecting "Parameters...".

The expansion for the ReadField template associated with the context above looks like this:

«?Get(itemName)» = reader.ReadBoolean();

«?Get(itemName)» returns the name of the field we're iterating over, while «?Get(itemType)» returns the full type name. Get is a custom StringProvider that you can use to retrieve the value of a template variable stored with the Set StringProvider (the ForEach TextCommand stores the itemName and itemType variables for you automatically before calling the ReadField and WriteField templates).

The new TypeImplements context added to solve this code generation challenge will ship with the next version of CodeRush.

Free DevExpress Products - Get Your Copy Today

The following free DevExpress product offers remain available. Should you have any questions about the free offers below, please submit a ticket via the DevExpress Support Center at your convenience. We'll be happy to follow-up.
No Comments

Please login or register to post comments.