Using CodeRush in Microsoft Visual Studio

Introduction

This is my eleventh year writing the VB Today column for codeguru.com. According to my Editor that makes me the longest running columnist (that he knows of). My day job is technical evangelist for Developer Express. What makes the job great is I love the tools and use them daily. It is easy to promote, talk, and write about products that you love. This article explains how CodeRush can help you write code faster in Microsoft Visual Studio .NET, with less effort, and be one of those hyper-productive programmers of myth and legend. (A great example of this, is that Mark Miller using an XBox 360 guitar tweaked for CodeRush in Visual Studio.NET was able to program faster than almost all challengers, including me but not Dustin Campbell.)

In this article you will learn how to use CodeRush to write your VB.NET code and how to define new templates for your own inventions.

In My Own Words...

Mark Miller is wicked smart. I can write that because it's true (and he knows it.) Mark created CodeRush and has been creatively evangelizing it on behalf of Developer Express for many years. Some of you probably saw the XBox 360/Beatles extravaganza at PDC in 2009. Some of you probably saw the Verne Troyer 'mini me' craziness at PDC LA 2008?!

In my own words CodeRush is an extensible meta- programming tool that has hundreds of templates and supports custom templates. The templates represent code. You type a simple sort of shorthand and CodeRush injects the code associated with that template into your source file. The shortcuts are usually one or two characters, but the corresponding code that expands from the shortcut can be as big as you want. CodeRush uses markers and fields to show you where you need to fill in the blanks.

You will see how this works in the next section. The final section provides an introduction into defining a custom template, and the features that support custom templates. (CodeRush is a tucked away, but it is a feature- rich tool. Too much to cover in one article, but you will have a good idea of what is available.)

Using Existing Templates to Write VB Code

CodeRush is available from http://www.devexpress.com, and can be purchased as a separate download or with one of Developer Express' subscription plans. (You also have the option of using CodeRush Xpress as a free download from http://www.devexpress.com/Products/ Visual_Studio_Add-in/CodeRushX/.) The examples in this article were created with the commercial-purchased version- of CodeRush.

Note: CodeRush Xpress does not include support for the code templates discussed in this article.

When you install CodeRush it integrates into Microsoft Visual Studio on an added DevExpress menu. The templates for VB.NET and C# are ready to go once CodeRush is installed. The DevExpress menu provides access to the tools window, training content, options and a user guide, but the defined templates generate code when you type the template shortcut followed by the space bar inside any source code file open in Visual Studio.

The first thing to note is that core templates are pretty intuitive. Type 'c' space for the class template, 'v' space for variables, 'p' space for properties, and so on. For example, 'cc' space will generate a class constructor and permit you to select fields from the class that you would like to initialize inside the constructor (Sub New). There are hundreds of templates, and it takes some time to memorize more than a handful. However, the more you use CodeRush the more muscle memory will take over and learning and remembering templates that you use frequently unfolds very quickly.

Here is a step by step example showing how, I for example, define a custom entity class using CodeRush. (The example is based on the Northwind Customers table for convenience.)

  1. Open the Server Explorer in Visual Studio
  2. Expand the Northwind connection
  3. Right-click the Customers table and select Open Table Definition
  4. Select all of the elements in the definition and copy and paste them into a code file (See Listing 1)
  5. Move the cursor outside of the Module after End Module and between the table definition
  6. Type 'c' and hit the space key
  7. The cursor position will be placed on the default class name, ClassName
  8. Quickly type in a new name-Customer-and press Enter
  9. Define each property very quickly by type 'p' and pressing the space key
  10. Use the pre-defined cursor positions to replace the field name, property name, and data type for the template, pressing enter after each revision
  11. After the last replaceable element is typed in the cursor will be placed at the end of the property statement. (Note that the property template generates a backing field too.)
  12. Repeat steps 9 and 10 for every field in the Customers table. (Since Customers' fields are all strings you can use 'ps'--the string property template--to speed things up
  13. Delete the field definition data information from the source file. (In just a minute or two you have a custom entity, see Listing 2)
  14. To generate a constructor that accepts all fields find an empty line in the class and type 'cc' space followed by enter to accept the default (see Listing 2)
  15. Cut and paste all of the class code to a separate source file (or use the context menu, hover over the class name select the Refactor! Menu item and click Move Type to File. Refactor! Pro is a refactoring tool from Developer Express, bundled with CodeRush and also available separately for $99.)

Using CodeRush in Microsoft Visual Studio

Listing 1: Quick starting a custom entity class:

  Module Module1
  
      Sub Main()
  
      End Sub
  
  End Module
  
  
  
  
  CustomerID	nchar(5)	Unchecked
  CompanyName	nvarchar(40)	Unchecked
  ContactName	nvarchar(30)	Checked
  ContactTitle	nvarchar(30)	Checked
  Address	nvarchar(60)	Checked
  City	nvarchar(15)	Checked
  Region	nvarchar(15)	Checked
  PostalCode	nvarchar(10)	Checked
  Country	nvarchar(15)	Checked
  Phone	nvarchar(24)	Checked
  Fax	nvarchar(24)	Checked

[class1.jpg]
Figure 1: The generate class template.

[define2.jpg]
Figure 2: Define each property with the property template, run by typing 'p' and space inside of the class.

Listing 2: The code generated by CodeRush created 143 lines of code by typing about 20 characters, or so:

  Public Class Customer
    Public Sub New()
  
    End Sub
  
  
    ''' <summary>
    ''' Initializes a new instance of the Customer class.
    ''' </summary>
    ''' <param name="customerID"></param>
    ''' <param name="companyName"></param>
    ''' <param name="contactTitle"></param>
    ''' <param name="contactName"></param>
    ''' <param name="address"></param>
    ''' <param name="city"></param>
    ''' <param name="region"></param>
    ''' <param name="postalCode"></param>
    ''' <param name="country"></param>
    ''' <param name="fax"></param>
    ''' <param name="phone"></param>
    Public Sub New(ByVal customerID As String, ByVal companyName As String, ByVal contactTitle As String, ByVal contactName As String, ByVal address As String, ByVal city As String, ByVal region As String, ByVal postalCode As String, ByVal country As String, ByVal fax As String, ByVal phone As String)
        _customerID = customerID
        _companyName = companyName
        _contactTitle = contactTitle
        _contactName = contactName
        _address = address
        _city = city
        _region = region
        _postalCode = postalCode
        _country = country
        _fax = fax
        _phone = phone
    End Sub
  
    Private _customerID As String
    Public Property CustomerID() As String
      Get
        Return _customerID
      End Get
      Set(ByVal Value As String)
        _customerID = Value
      End Set
    End Property
  
    Private _companyName As String
    Public Property CompanyName() As String
      Get
        Return _companyName
      End Get
      Set(ByVal Value As String)
        _companyName = Value
      End Set
    End Property
  
    Private _contactTitle As String
    Public Property ContactTitle() As String
      Get
        Return _contactTitle
      End Get
      Set(ByVal Value As String)
        _contactTitle = Value
      End Set
    End Property
  
    Private _contactName As String
    Public Property ContactName() As String
      Get
        Return _contactName
      End Get
      Set(ByVal Value As String)
        _contactName = Value
      End Set
    End Property
  
  
    Private _address As String
    Public Property Address() As String
      Get
        Return _address
      End Get
      Set(ByVal Value As String)
        _address = Value
      End Set
    End Property
  
    Private _city As String
    Public Property City() As String
    Get
      Return _city
    End Get
    Set(ByVal Value As String)
      _city = Value
    End Set
    End Property
  
    Private _region As String
    Public Property Region() As String
    Get
      Return _region
    End Get
    Set(ByVal Value As String)
      _region = Value
    End Set
    End Property
  
    Private _postalCode As String
    Public Property PostalCode() As String
    Get
      Return _postalCode
    End Get
    Set(ByVal Value As String)
      _postalCode = Value
    End Set
    End Property
  
    Private _country As String
    Public Property Country() As String
    Get
      Return _country
    End Get
    Set(ByVal Value As String)
      _country = Value
    End Set
    End Property
  
    Private _fax As String
    Public Property Fax() As String
    Get
      Return _fax
    End Get
    Set(ByVal Value As String)
      _fax = Value
    End Set
    End Property
  
    Private _phone As String
    Public Property Phone() As String
    Get
      Return _phone
    End Get
    Set(ByVal Value As String)
      _phone = Value
    End Set
    End Property
  
  
  End Class

[refactor3.jpg]
Figure 3: Refactor! Pro is another meta-programming Microsoft Visual Studio Add-In from Developer Express.

A huge benefit of using a meta-programming tool, aside from coding faster, is the fewer keystrokes you type the fewer typographic errors you will have to correct later. Compile the example to verify that the little bit of code you did write--changing field names--compiles correctly.

To test the code, open the server explorer. Copy and paste the connection string from the Properties window for the Northwind database plug in some vanilla ADO.NET code and populate the collection of customers. The results are shown in Listing 3.

Listing 3: Some vanilla ADO.NET code to populate the entity class written with CodeRush:

Imports System.Data.SqlClient Imports System.Reflection

  Module Module1
  
      Function SafeRead(Of T)(ByVal fieldname As String, ByVal reader As SqlDataReader, _
        ByVal defaultValue As T) As T
  
        Dim val As Object = reader(fieldname)
        If ((val Is System.DBNull.Value) Or (val Is Nothing)) Then
          Return defaultValue
        Else
          Return Convert.ChangeType(val, defaultValue.GetType())
        End If
      End Function
  
      Sub Main()
  
        Const connectionString As String = _
          "Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;" + _
          "Integrated Security=True"
  
        Dim customers As List(Of Customer) = New List(Of Customer)
  
  
        Using connection As SqlConnection = New SqlConnection(connectionString)
  
          connection.Open()
          Using command As SqlCommand = New SqlCommand("SELECT * FROM CUSTOMERS", connection)
  
            Dim reader As SqlDataReader = command.ExecuteReader
  
            While reader.Read()
  
              Dim customer As Customer = New Customer()
              customer.CustomerID = SafeRead("CustomerID", reader, "")
              customer.CompanyName = SafeRead("CompanyName", reader, "")
              customer.ContactTitle = SafeRead("ContactTitle", reader, "")
              customer.ContactName = SafeRead("ContactName", reader, "")
              customer.City = SafeRead("City", reader, "")
              customer.Address = SafeRead("Address", reader, "")
              customer.Country = SafeRead("Country", reader, "")
              customer.Fax = SafeRead("Fax", reader, "")
              customer.Phone = SafeRead("Phone", reader, "")
              customer.PostalCode = SafeRead("PostalCode", reader, "")
              customer.Region = SafeRead("Region", reader, "")
  
              customers.Add(customer)
            End While
  
          End Using
  
        End Using
  
  
        For Each cust As Customer In customers
          Console.WriteLine("=====================================")
          Console.WriteLine("Customer: {0}", cust.CustomerID)
          Console.WriteLine("=====================================")
  
          Console.WriteLine("Company Name: {0}", cust.CompanyName)
          Console.WriteLine()
  
        Next
  
        Console.ReadLine()
  
      End Sub
  
  End Module

The code uses vanilla ADO.NET with a small twist, the SafeRead method. I use this method sometime to put reading potentially DBNull fields in a safe way. You drag and drop the SafeRead method right into the Toolbox--code snippet--and reuse it anytime you want. All of the calls to SafeRead can be made easier to code by implementing a custom template which we'll do next.

Using CodeRush in Microsoft Visual Studio

Defining a Custom Template

If code is static, that is, there are no elements you need to replace or update in a particular situation then drag it into the Toolbox for later use. The last section recommended you do that with the SafeRead method itself; it is always the same. Each call to SafeRead takes a different field name, the same reader object, and a potentially changing default value. Here we can use a CodeRush template to speed up generating these calls.

To use SafeRead we will need to define a template that generates a call to SafeRead, for the three parameters: the field name, the name of the reader object (I always use "reader"), and the default value.

To get started select the DevExpress menu, click Options, and expand the Editor folder and select the Templates options page-see Figure 4.

[editor4.jpg]
Figure 4: The Editor|Selections|Templates section is where you will define the SafeRead template.

A Quick Tour of the DevExpress Options Dialog for CodeRush

Starting from the Top left you can enter a value in the top-left search edit field to find a specific page in the Options dialog. For example, typing Templates will open the defined templates. The tree on the left lets you navigate the many configurable sections of CodeRush, including things like available Refactorings, IDE shortcuts, and Tool Windows options. (Use Figure 5 as a visual guide for Template Option features.)

When the Templates options page is selected the tree in the middle provides you with access to the defined templates. As you can see from Figure 4 there are a growing number of templates. Above the tree is a search feature for the templates, and below the template's tree is the language selection feature. Since this will be a VB template, change the language to Basic. Below the template search bar are toolbar buttons for defining a new category, a new template, and deleting an item from the templates tree. The first magnifying glass button is used to find the next matching template and the smaller magnifier icon searches in the body of the template.

On the right side of the Template Options-from top to bottom is a comment for a given template. Above the expansion are buttons for creating and navigating through alternate template expansions (a single template can have more than one expansion determined by context). The expansion contains the CodeRush-ese that describes what the template will do when invoked. The buttons below the expansion editor field are for copying to the clipboard, positioning the cursor, inserting a BlockAnchor, and (a combo box for) selecting from a list of predefined commands. Below that are checkboxes for editor options, and the Use tree defines the context where the template is applicable, such as Code|InClass for a template that is active inside of a class.

Finally, there are options for triggering the template and dependent namespaces. The dependent namespaces will add Imports statements if you use a template that needs a particular namespace reference (refer to Figure 5). Whew!

[options5.jpg]
Figure 5: There is a lot of information in this one view of the Template Options, but basically it all exists to support customizing and managing templates/expansions.

Defining the SafeRead Template

There are several steps for defining the template. Each step is listed below with a break about half way through, testing the stub before using anchor features to define the replaceable elements.

  1. Click New Category and enter Custom in the new Category dialog.
  2. Click OK
  3. Click the custom category and then click the New Template button (to the right of the new category button)
  4. In the New template dialog type sr for the template. (You can use the search feature to determine if a template name is already in use or not)
  5. Optionally add a comment, and literally type a test expansion, a literal call to SafeRead is ok for now.
  6. In the Use section find the Code category and check InCodeBlock (InCodeBlock means the template will essentially expand any place a statement is legal). (We aren't done yet just stubbing the template out. The results to this point will look like Figure 6.)
  7. Click OK and test the template by typing sr+space in a code block-inside of a method.
  8. Return to the Options window. We're going to use the Templates tool buttons to create the following expansion (steps follow)

    [pre7.jpg]

  9. Add a quote and click the Caret button
  10. From the Command combo box select the Field command and add the literal value (fieldname) after the word Field and before the ". Field commands are used whenever you need to prompt for values after a template has expanded.
  11. Move to the end of the first parameter and click the BlockAnchor button (this will ensure the selection runs from here to the Caret command, which means the first parameter will be selected after the template expands)
  12. For the replaceable default value use the Field command again and type defaultValue to play the text role of the prompt the user will see
  13. Add the Target command, which is where the cursor will be placed after the expansion elements have been changed by the user. (This is an optional step as CodeRush adds a Target command at the end of a template by default.)
  14. Click OK and test the template.

Right after you type the template name, sr, the expansion will appear in your code as shown in Figure 7. There is way more to CodeRush than can be covered in an article, but you can access the CodeRush User Guide from the DevExpress menu. The guide will provide you with many more features and tips for creating expansions.

[stubbed6.jpg]
Figure 6: The stubbed template as the settings will appear in the dialog.

[expansion8.jpg]
Figure 7: The expansion in action with replaceable elements highlighted and ready for user modification.

CodeRush is a powerful tool that integrates nicely into Visual Studio. I use it all of the time, and it radically reduces the amount of time it takes me to write code. That said I know I have barely scratched the surface of its true potential. Just using common expansions for classes, fields, properties, methods, constructors, and events the amount of code you can produce is dramatically and substantially improved.

Refer to my blog post This is Your Brain on CodeRush for an example of an expansion that adds code for functional construction of an XDocument using LINQ.

Conclusion

CodeRush is a meta-programming tool that can radically improve how quickly any developer can produce code. CodeRush integrates seamlessly into Visual Studio, has hundreds of pre-defined templates and is extensible. As demonstrated in this article you can use combinations of code snippets in Visual Studio, existing expansions, and custom expansions to tailor your work environment to the way you want to write code and the kinds of code elements you need to be productive.

Thanks to Mark Miller for giving this article the once over.



About the Author

Paul Kimmel

Paul Kimmel is the VB Today columnist for CodeGuru and has written several books on object-oriented programming and .NET. Check out his upcoming book Professional DevExpress ASP.NET Controls (from Wiley) now available on Amazon.com and fine bookstores everywhere. Look for his upcoming book Teach Yourself the ADO.NET Entity Framework in 24 Hours (from Sams). You may contact him for technology questions at pkimmel@softconcepts .com. Paul Kimmel is a Technical Evangelist for Developer Express, Inc, and you can ask him about Developer Express at paulk@devexpress.com and read his DX blog at http:// community.devexpress.com/blogs/paulk.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • It's hardly surprising that half of small businesses fail within the first 1-5 years. It's not easy to launch a new product, single-handedly manage everything from IT to accounting, fend off the competition, and grow a customer base – all at the same time – even with a great concept. Offering awesome customer service can make the difference between a startup that flies and a startup that dies. Read this white paper to learn nine ways customer support can help you beat the competition and grow your …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds