Home > Articles > Programming > Visual Basic

Custom Code Refactoring with VB 2015 and the .NET Compiler Platform

Concluding his series on the coding experience in Visual Basic 2015, Alessandro Del Sole explains how to leverage the .NET Compiler Platform APIs to build custom refactoring tools that integrate into the code editor.
Like this article? We recommend

Like this article? We recommend

Introduction

In Part 1 of this series, you started working with the new code-focused experience in Visual Basic 2015. You saw how Visual Basic 2015 introduces integrated code refactoring tools for the first time, learning which and how many refactorings are already available for you to use. The very good news is that you can also create and share custom code refactorings that integrate into Visual Studio's code editor. This is possible because of the .NET Compiler Platform APIs, which empower the code editor and allow for creating custom refactorings other than code analyzers.

In Part 2 (which you should read before going further with this article), you started using the .NET Compiler Platform APIs, creating an analyzer that provides live code analysis as you type.

This article wraps up the series by showing you how to build a custom code refactoring that extends the Visual Basic toolbox in a domain-specific scenario.

Developing a Code Refactoring

Visual Basic 2015 ships with a number of built-in code refactorings, which provide a better way of reorganizing portions of code. However, in some situations you might need customized refactoring techniques. For instance, imagine you want to build a class library that perfectly adheres to the .NET Framework naming conventions. Among the many naming rules, one states that names for public fields must be in Pascal-case when the identifier is composed of multiple words (such as ProductQuantity). For the sake of simplicity, this article provides an example that capitalizes the first letter for the names of public fields, disregarding whether they are made of multiple words.

Creating a refactoring involves many techniques that you learned in the previous articles. The Syntax Visualizer tool helps you to understand where you need to introduce a refactoring and which syntax nodes and objects to use. To understand what you need to accomplish, we'll work with the following proposed example.

In a Console project, write the following field definition at the Module level:

Public oneString As String, oneInt As Integer, twoInt As Integer

Open the Syntax Visualizer. As Figure 1 shows, a field is represented by the FieldDeclaration syntax node and mapped by a FieldDeclarationSyntax object.

Figure 1 Field definitions in the .NET Compiler Platform.

Every FieldDeclaration has one VariableDeclarator element per identifier/type pair. The VariableDeclarator element is mapped by a VariableDeclaratorSyntax object. Every VariableDeclarator element has a ModifiedIdentifier element that represents the variable identifier, mapped by a ModifiedIdentifierSyntax object. Additional elements include SimpleAsClause, which represents the As keyword, PredefinedType, which represents a built-in type in the .NET Framework, and so on. Your goal is checking the first letter for each variable identifier, so you don't need a lot of syntax nodes; you simply need to find FieldDeclaration elements, their VariableDeclarator nodes, and the ModifiedIdentifier nodes. Let's get started.

Create a new project based on the Code Refactoring template and name it PublicFieldCodeRefactoring (see Figure 2).

Figure 2 Creating a new code refactoring project.

When the project is ready, it includes just one code file, called CodeRefactoringProvider.vb. The auto-generated class inherits from Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider, which offers the proper infrastructure to build a code refactoring via the ComputeRefactoringAsync method. This is where you write your refactoring logic. But first, add the following simple method, which returns a new string in which the first letter is uppercase:

Private Function ConvertName(oldName As String) As String
    Return Char.ToLowerInvariant(oldName(0)) + oldName.Substring(1)
End Function

Now move inside the ComputeRefactoringAsync method and delete all of its auto-generated content. The first thing to add is checking whether the current syntax node is of type FieldDeclarationSyntax and its modifier is Public; in fact, you need to avoid refactoring a Private, Protected, or Protected Friend field, because these fields allow their first letter to be lowercase. Add the following code:

Public NotOverridable Overrides Async Function _
    ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task

    Dim root = Await context.Document.
        GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False)

    ' Find the node at the selection.
    Dim node = root.FindNode(context.Span)

    Dim fieldDecl = TryCast(node, FieldDeclarationSyntax)
    If fieldDecl Is Nothing Or fieldDecl.Modifiers.
        ToFullString.Contains("Private") = False Then
        Return
    End If

Notice how the FieldDeclarationSyntax object exposes a property called Modifiers, of type SyntaxTokenList, which represents a collection of SyntaxToken objects and can be used to detect the visibility of the current field. Next, you can check whether at least one identifier in the field declaration should be refactored. Take a look at this code:

Dim mustRegisterAction As Boolean

For Each declarator In fieldDecl.Declarators
    'If at least one starting character is uppercase, must register an action
    If declarator.Names.Any(Function(d) _
                  Char.IsUpper(d.Identifier.Value.ToString(0))) Then
        mustRegisterAction = True
    Else
        mustRegisterAction = False
    End If
Next

FieldDeclarationSyntax exposes a property called Declarators, of type SeparatedSyntaxList(Of VariableDeclaratorSyntax), which contains the list of VariableDeclarator elements in the field. Each exposes the Names property, of type SeparatedSyntaxList(Of ModifiedIdentifierSyntax), which contains the list of identifiers in the VariableDeclarator. The code iterates each VariableDeclarator: if at least one variable name starts with an uppercase letter, it sets with True a Boolean variable that determines whether an action must be registered for refactoring the current field. The ModifiedIdentifierSyntax type exposes the Identifier property, which represents the actual variable identifier. You'll work with it later; for now, its Value property is used to detect the form of the first letter in its string representation. If at least one identifier matches the condition, you register an action for the current syntax node as follows:

If mustRegisterAction = False Then
    Return
Else
    Dim action = CodeAction.Create("Make first char uppercase",
                                   Function(c) RenameFieldAsync(context.
                                   Document, fieldDecl, c))

    ' Register this code action.
    context.RegisterRefactoring(action)
End If

You create an action by invoking the Create method from the Microsoft.CodeAnalysis.CodeActions.CodeAction class; arguments are the text shown in the Light Bulb and a delegate that performs the refactoring. The latter, as for analyzers, receives the current document instance, the current syntax node, and a cancellation token as its arguments. The RenameFieldAsync method begins by getting an instance of the semantic model and the syntax root for the current document, which is something you already saw with analyzers:

Private Async Function RenameFieldAsync(document As Document,
                       fieldDeclaration As FieldDeclarationSyntax,
                       cancellationToken As CancellationToken) _
                       As Task(Of Document)

    Dim semanticModel = Await document.
        GetSemanticModelAsync(cancellationToken).
        ConfigureAwait(False)

    Dim root = Await document.GetSyntaxRootAsync

The logic of your action requires iterating variable declarators in the current field; for each declarator, you will need to generate new identifiers for variables whose name starts with a lowercase letter. Finally, you have to generate new declarators and a new document based on the supplied changes. Start by storing the collection of existing variable declarators and declaring two collections of ModifiedIdentifierSyntax and VariableDeclaratorSyntax objects, as follows:

Dim oldDeclarators = fieldDeclaration.Declarators
Dim listOfNewModifiedIdentifiers As _
    New SeparatedSyntaxList(Of ModifiedIdentifierSyntax)
Dim listOfNewModifiedDeclarators As _
    New SeparatedSyntaxList(Of VariableDeclaratorSyntax)

The next step is iterating the collection of variable declarators and their names in order to generate new ModifiedIdentifierSyntax objects with new names. The following code demonstrates this process (read inline comments for better understanding):

'Iterate the declarators collection
For Each declarator In oldDeclarators
    'For each variable name in the declarator...
    For Each modifiedIdentifier In declarator.Names
        'Get a new proper name
        Dim tempString = ConvertName(modifiedIdentifier.ToFullString)

        'Generate a new ModifiedIdentifierSyntax based on
        'the previous one's properties but with a new Identifier
        Dim newModifiedIdentifier As ModifiedIdentifierSyntax =
            modifiedIdentifier.
            WithIdentifier(SyntaxFactory.ParseToken(tempString)).
            WithTrailingTrivia(modifiedIdentifier.GetTrailingTrivia)

        'Add the new element to the collection
        listOfNewModifiedIdentifiers =
            listOfNewModifiedIdentifiers.Add(newModifiedIdentifier)
    Next
    'Store a new variable declarator with new variable names
    listOfNewModifiedDeclarators =
        listOfNewModifiedDeclarators.Add(declarator.
        WithNames(listOfNewModifiedIdentifiers))

    'Clear the list before next iteration
    listOfNewModifiedIdentifiers = Nothing
    listOfNewModifiedIdentifiers = New _
        SeparatedSyntaxList(Of ModifiedIdentifierSyntax)
Next

Once you have a list of new VariableDeclaratorSyntax objects, you can generate a new FieldDeclarationSyntax like this:

Dim newField = fieldDeclaration.
    WithDeclarators(listOfNewModifiedDeclarators)

The FieldDeclarationSyntax.WithDeclarators method allows you to specify the variable declarators for the field instance. As you did with analyzers, you finally generate a new syntax node, replacing the old FieldDeclarationSyntax node with the newly created one:

    Dim newRoot As SyntaxNode =
        root.ReplaceNode(fieldDeclaration, newField)

    Dim newDocument =
        document.WithSyntaxRoot(newRoot)

    Return newDocument
End Function

You can now press F5 to start the experimental instance and test your code refactoring. If you right-click the field declaration and select Quick Actions, you can see a preview of how the code will be refactored, as demonstrated in Figure 3.

Figure 3 The new code refactoring suggests edits in the Light Bulb.

Conclusions

As well as for analyzers, custom refactorings offer additional domain-specific possibilities and can help developers to write better code. Your effort is pretty easy; you write the analysis logic, and the compiler's APIs do the rest, including the integration with Visual Studio and the Light Bulb. Now that we've reached the end of this article series, it should be much clearer how the .NET Compiler Platform offers new and amazing scenarios, especially for developers whose business is building and selling libraries and/or user controls, because they can now include live code analysis with their APIs.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020