The Add Data Contract plugin is a CodeProvider with the usual CheckAvailability and Apply methods. The basic plumbing of this plugin is created with the NewCodeProvider CodeRush template detailed in this blogpost.

Add Namespace

In the DXCore, a using directive (or an imports directive in VB.Net) is called a NamespaceReference

To add a NamespaceReference to the current file it is first necessary to determine if one already exists. For this we construct a new ElementEnumerable capable of searching the current file for NamespaceReference objects. This is then used to return an IEnumerable<NamespaceReference>

The list of namespace is queried to determine if the new namespace is already referenced. There is nothing to be gained by referencing the same namespace twice. If it is found, then we return from the apply method without having performed any modifications.

Location, Location, Location

Next we determine the best location to insert our NamespaceReference.

If there are no existing NamespaceReferences, then the InsertionPoint is set to the start of the current document.

Alternatively, if there are some pre-existing NamespaceReferences, then the start of the last of these is picked as a sensible default.

Code Generation and Insertion

Next we create our new NamespaceReference object (passing in the string representing the namespace in question) and have CodeRush generate the actual code that represents this object. The last step in generating our NamespaceReference is to queue the insertion of this code at the InsertionPoint determined in the previous step

A Generic AddAttribute Method

There are 2 attributes which this plugin adds to various parts of the target class.

The DataContract attribute is to be added to the class itself. Then we need to iterate through the properties on the class, and add the DataMember attribute to each of those.

In order to make this as easy as possible, I decided to create a utility method capable of quickly adding a named attribute to any given LanguageElement.

In the method above, an ElementBuilder is used to create the Attribute and then the AttributeSection. For those that don’t know the AttributeSection is the pair of square brackets that the attribute sits inside. (These are angle brackets in VB.Net).

As before, code is then generated and queue an insert into the ActiveTextDocument at the correct location.

Putting it all Together

All of this is drawn together in the body of the apply method.

First we add the System.Runtime.Serialization namespace. Next we decorate the class with the DataContract attribute. Then we iterate through all the properties of the class decorating each of these with the DataMember attribute. We call ApplyQueueEdits to apply each of the queued operations to the document in a single step.

Finally we reparse the document and call the FormatFile action to perform any additional reformatting that might be necessary.