Home > Articles > Programming > C#

Like this article? We recommend Creating a Code Fix

Creating a Code Fix

Let's start by creating a new diagnostic project called IfClauseDiagnostic. The template generates three different projects for you: the diagnostic, a test project, and a vsix installer that installs the diagnostic. You can follow along with the code in GitHub.

The default project for this solution is the vsix installer. If you press Ctrl-F5 at this point, you'll launch a new copy of Visual Studio, with your code fix installed. Your diagnostic is only active in this second copy because Visual Studio starts that copy using a different registry hive for add-ins. Your new diagnostic is installed only in that separate hive. This workflow is a bit cumbersome, so I like to rely on unit testing when I create diagnostics and code fixes.

Before writing our diagnostic, let's look at the template-generated code, including the tests. The template creates a sample diagnostic that replaces any lower-case characters in a type name (class, struct, or interface) with the equivalent uppercase character. Check out the branch 01-TemplateFiles to see the generated code.

Let's begin by examining the two unit tests generated by the template:

  • A test whose input is the empty string. This test expects the diagnostic to do nothing.
  • A test containing a type name with lowercase characters. This test expects the diagnostic to find and replace that code.

These tests are implemented using a base class, CodeFixVerifier, that contains numerous helper methods that make writing tests for a diagnostic and code fix much easier. The most important routines verify the changes that your code fix would make to a section of code. Perfecting that code can be difficult, and these utility routines make it much easier to validate your code fixes. As you write your own diagnostics, add new tests here for different variations on the code that your diagnostic should be finding.

The format of each of test is similar:

  1. Create a string to represent the code.
  2. If the string represents code that triggers your diagnostic, create a DiagnosticResult that represents the diagnostics.
  3. If the string represents code that triggers your diagnostic, create a string that represents the fixed code.
  4. Send the source code to the diagnostic, and then check the results provided by the CodeFixVerifier class. Note that in all tests where your diagnostic should not be triggered, the CodeFixVerifier class can ensure that the diagnostic is not triggered.

As we work on the project, we'll follow the same format for our unit tests. In fact, I'll replace the source and fixed code to validate the if clause tests.

Moving on from the unit tests, let's look at the sample diagnostic that the template generates. By examining this code, we'll learn how to create our specific diagnostic in the proper way. Let's start with the DiagnosticAnalyzer class. This code analyzes source to find type names that have lowercase letters. The diagnostic has three parts:

  • Rule structure
  • Initializing the diagnostic
  • Scanning code for possible violations

Here's the definition of the rule for the lowercase diagnostic:

internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
    DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning,
    isEnabledByDefault: true);

Most of the arguments for the DiagnosticDescriptor are human-readable strings. Some of them are important in how the diagnostic works:

  • DiagnosticId, which is a string, must be unique to identify this diagnostic. As I'll show later, this ID is also used to match the diagnostic with the code fix.
  • Category should match the FxCop category for your diagnostic. The categories are listed on MSDN.
  • DiagnosticSeverity is an enum that indicates this diagnostic's warning level (error, warning, info, or hidden). You use this value to indicate how the user learns about your diagnostic. The more severe the error, the more prominent the warning.

This Rule object is returned by the SupportedDiagnostics public property:

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
    { get { return ImmutableArray.Create(Rule); } }

The template code supports a single diagnostic, but the property returns an array. Your diagnostic may support multiple diagnostics.

The final setup action taken by this class is in the overridden Initialize() method:

public override void Initialize(AnalysisContext context)
{
    context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);
}

This method registers any analysis actions in your diagnostic. The template code has only one. The first parameter is the method that analyzes the code (we'll look at this shortly). The remaining parameters are a params array of SymbolKind enums that represent the source symbols your analyzer examines.

Finally, let's look at the AnalyzeSymbol method. This method examines the source context, looking for violations of your diagnostic rules:

private static void AnalyzeSymbol(SymbolAnalysisContext context)
{
    var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;

    // Find just those named type symbols with names containing lowercase letters.
    if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower))
    {
        // For all such symbols, produce a diagnostic.
        var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0],
            namedTypeSymbol.Name);

        context.ReportDiagnostic(diagnostic);
    }
}

The template code looks at the symbol, which represents a type name, and examines it for any lowercase characters. If any are found, the code creates a diagnostic object representing the rule and the code location, and it reports that diagnostic. If the code has no mistakes, the diagnostic does nothing.

If you want to write a diagnostic, but aren't sure how to automate the fix, this is all you need to implement. As we build the fix for the If clauses, we'll write a code fix to add the braces where necessary. That means we'll be building and modifying the CodeFixProvider to modify the code. The CodeFixProvider has three responsibilities related to fixing the code. First, it must override GetFixableDiagnosticIds() to let Visual Studio know which diagnostic IDs it can fix. Note that it uses the same diagnostic ID from the DiagnosticAnalyzer class:

public sealed override ImmutableArray<string> GetFixableDiagnosticIds()
{
    return ImmutableArray.Create(IfClauseDiagnosticAnalyzer.DiagnosticId);
}

Next, it needs to register the method that would modify the code, if the user chooses that option. That's done in the override of ComputeFixesAsync:

public sealed override async Task ComputeFixesAsync(CodeFixContext context)
{
    var root = await context.Document
        .GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

    var diagnostic = context.Diagnostics.First();
    var diagnosticSpan = diagnostic.Location.SourceSpan;

    // Find the type declaration identified by the diagnostic.
    var declaration = root.FindToken(diagnosticSpan.Start)
        .Parent.AncestorsAndSelf().OfType<TypeDeclarationSyntax>().First();

    // Register a code action that will invoke the fix.
    context.RegisterFix(
        CodeAction.Create("Make uppercase",
        c => MakeUppercaseAsync(context.Document, declaration, c)),
        diagnostic);
}

The argument to this function is a CodeFixContext that represents the code that was identified by the DiagnosticAnalyzer. The code finds the location in the document that must be modified, and it registers the action that will fix the code.

This code follows some very important practices for creating code fixes. The semantic and syntactic trees are immutable, so you can't simply replace nodes in place. Instead, what you'll do is create a copy of the entire solution where you've made the modifications you want. That's not as hard as it sounds, because the APIs include utility methods that provide many of the transformations you'll need. The MakeUppercaseAsync method uses one of those utility methods to ensure that the rename operation updates all references to the type as well:

private async Task<Solution> MakeUppercaseAsync(Document document,
    TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken)
{
    // Compute new uppercase name.
    var identifierToken = typeDecl.Identifier;
    var newName = identifierToken.Text.ToUpperInvariant();

    // Get the symbol representing the type to be renamed.
    var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
    var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);

    // Produce a new solution that has all references to that type renamed,
    // including the declaration.
    var originalSolution = document.Project.Solution;
    var optionSet = originalSolution.Workspace.Options;
    var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution,
        typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);

    // Return the new solution with the now-uppercase type name.
    return newSolution;
}

The transformations may take time, so this async method returns a Task<Solution>. You can see that it's building a new Solution object that is a copy of the original, with the chosen type symbol renamed.

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