Reader small image

You're reading from  Refactoring with C#

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781835089989
Edition1st Edition
Languages
Right arrow
Author (1)
Matt Eland
Matt Eland
author image
Matt Eland

Matt Eland is a Microsoft MVP in Artificial Intelligence (AI) who has been working with .NET since 2001. Matt has served as a senior engineer, software engineering manager, and .NET programming instructor. He is currently an AI specialist and senior consultant at Leading EDJE near Columbus, Ohio, where he helps companies with their software engineering and data science needs using C# and related technologies. Matt speaks and writes in his community and co-organizes the Central Ohio .NET Developers Group while pursuing a master's degree in data analytics.
Read more about Matt Eland

Right arrow

Refactoring Code with Roslyn Analyzers

In the last chapter, we saw how you can build Roslyn analyzers to flag issues in your code. In this chapter, we’ll improve our analyzers by giving them the ability to fix code issues by providing Quick Actions the user can invoke to modify their source code. We’ll also discuss some additional ways of deploying Roslyn analyzers that improve your ability to provide a consistent experience to your team members.

This chapter covers the following:

  • Building a Roslyn Analyzer code fix
  • Testing code fixes with RoslynTestKit
  • Publishing Roslyn analyzers as NuGet packages

Technical requirements

In this chapter, we’re starting right where we left off in Chapter 13.

The starting code for this chapter is available from GitHub at https://github.com/PacktPublishing/Refactoring-with-CSharp in the Chapter14/Ch14BeginningCode folder.

Case study – Cloudy Skies Airlines

In Chapter 13, we built a ToStringAnalyzer that detects classes that do not override the ToString method. This results in suggestions in the Visual Studio editor and a message in the error list.

Cloudy Skies Airlines has deployed this internally and found it to be generally helpful, but there are a few things that need improvement:

  • Although violations of the ToString override rule are flagged by the analyzer, not every developer is addressing this issue. When discussed internally, some developers stated they didn’t want to take the time to address it. Additionally, some of the newer developers didn’t fully understand the rule or what fixing it would look like.
  • Whenever a new analyzer is created or a bug in an existing analyzer is addressed, a new VSIX file must be created. Developers then need to download and install it to get the updated version. Because of this, it’s hard for the team to know which developers...

Building a Roslyn Analyzer code fix

Roslyn Analyzers allow you to provide options for users to automatically fix issues your analyzers detect in your code. They do this through something called a code fix provider, which can modify your document in an automated manner to resolve the diagnostic warning.

Think of it this way: diagnostic analyzers, like our OverrideToStringAnalyzer, help detect issues in your team’s code. On the other hand, code fix providers give you a way of fixing these issues.

Not all diagnostic analyzers will have code-fix providers, but in my experience, those that also provide code-fix providers tend to get addressed earlier and more consistently.

Let’s see how one works.

Creating a CodeFixProvider

First, we’ll add a new class to the Packt.Analyzers class library. We’ll call this class ToStringCodeFix. Replace its contents with the following code for a basic code fix:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis...

Testing Code Fixes with RoslynTestKit

In Chapter 13, we saw how the RoslynTestKit library helps your diagnostic analyzers flag code issues appropriately. In this chapter, we’ll revisit the library to verify our new code fix.

We will start by creating a new class in our test project named ToStringCodeFixTests due to our common naming conventions.

This class will start by declaring a test fixture like it did with the analyzer:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using RoslynTestKit;
namespace Packt.Analyzers.Tests;
public class ToStringCodeFixTests : CodeFixTestFixture {
 protected override string LanguageName
   => LanguageNames.CSharp;
 protected override CodeFixProvider CreateProvider()
   => new ToStringCodeFix();
 protected override IReadOnlyCollection<DiagnosticAnalyzer>
   CreateAdditionalAnalyzers()
   => new[]...

Publishing Roslyn Analyzers as NuGet packages

Using VSIX files to share code analyzers works, but isn’t an ideal solution.

Since VSIX files must be manually installed and updated, this means that with a team of software engineers, you’re never sure who has the extension installed at all or who is on which version of the extension.

Because each developer must install the VSIX themselves and keep it updated, this makes it harder to onboard new team members, release new analyzers or code fixes, or issue patches for issues found in your existing analyzers.

Thankfully, there’s a better option: NuGet package deployment.

Understanding NuGet package deployment

Analyzers and code fixes can be packed into NuGet packages and deployed to a NuGet feed so others can find them. Once in a NuGet feed, any developer on the team can install the package into one or more projects.

Once a NuGet package is installed, any developer who opens the project will automatically...

Summary

In this chapter, we saw how Roslyn Analyzers can be extended to provide code fixes along with the diagnostic information they already provided.

Code fixes work by interpreting the tree structure of your code and making modifications to that structure, resulting in a new document or solution. Visual Studio then reacts to these changes by updating the source code.

This means that code fixes can automatically make pre-configured modifications to your code to address known issues in a repeatable and safe manner.

We also discussed how NuGet package deployment allows you to wrap up your Roslyn Analyzers into a package and share them with other developers – either other developers on your team or other developers worldwide.

This concludes Part 3 of this book. In the final part of this book, we’ll explore some of the unique challenges and opportunities found in refactoring code in real-world organizations and teams.

Questions

  1. What is the relationship between a DiagnosticAnalyzer and a CodeFixProvider?
  2. How can you test a code fix?
  3. What are some of the advantages of NuGet deployment versus VSIX deployment?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Refactoring with C#
Published in: Nov 2023Publisher: PacktISBN-13: 9781835089989
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Matt Eland

Matt Eland is a Microsoft MVP in Artificial Intelligence (AI) who has been working with .NET since 2001. Matt has served as a senior engineer, software engineering manager, and .NET programming instructor. He is currently an AI specialist and senior consultant at Leading EDJE near Columbus, Ohio, where he helps companies with their software engineering and data science needs using C# and related technologies. Matt speaks and writes in his community and co-organizes the Central Ohio .NET Developers Group while pursuing a master's degree in data analytics.
Read more about Matt Eland