Book Image

Roslyn Cookbook

Book Image

Roslyn Cookbook

Overview of this book

Open-sourcing the C# and Visual Basic compilers is one of the most appreciated things by the .NET community, especially as it exposes rich code analysis APIs to analyze and edit code. If you want to use Roslyn API to write powerful extensions and contribute to the C# developer tool chain, then this book is for you. Additionally, if you are just a .NET developer and want to use this rich Roslyn-based functionality in Visual Studio to improve the code quality and maintenance of your code base, then this book is also for you. This book is divided into the following broad modules: 1. Writing and consuming analyzers/fixers (Chapters 1 - 5): You will learn to write different categories of Roslyn analyzers and harness and configure analyzers in your C# projects to catch quality, security and performance issues. Moving ahead, you will learn how to improve code maintenance and readability by using code fixes and refactorings and also learn how to write them. 2. Using Roslyn-based agile development features (Chapters 6 and 7): You will learn how to improve developer productivity in Visual Studio by using features such as live unit testing, C# interactive and scripting. 3. Contributing to the C# language and compiler tool chain (Chapters 8 - 10): You will see the power of open-sourcing the Roslyn compiler via the simple steps this book provides; thus, you will contribute a completely new C# language feature and implement it in the Roslyn compiler codebase. Finally, you will write simple command line tools based on the Roslyn service API to analyze and edit C# code.
Table of Contents (19 chapters)
Title Page
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Dedication

Preface

Software developers deal with source code on a day-to-day basis. Regardless of the technology or the programming language that they work on, there are a bunch of routine tasks that they must perform on their code:

  • Compile source code into the runtime-specific binary format
  • Analyze source code to identify issues in the source code
  • Edit source code to fix issues or refactor to improve maintenance, understandability, performance, security, and so on
  • Navigate source code to search patterns, references, definitions, and relationships
  • Debug source code to observe and fix runtime behavior for functionality, performances, security, and so on
  • Visualize collections of source components (projects), their properties, configuration, and so on

The .NET Compiler Platform (code named Roslyn) is a platform for .NET programming languages, C# and Visual Basic, to enable building tools and extensions to perform these routine programming tasks. Notably, this platform is shared between Microsoft s .NET compilers and the Visual Studio IDE for .NET development.

Roslyn is divided into multiple programming layers, with each layer exposing public APIs to write customized tools and extensions:

  • CodeAnalysis layer: Core syntax and semantic representation layer of source code. C# and Visual Basic compilers (csc.exe and vbc.exe) are written on top of this layer.
  • Workspaces layer: Project and solution layer that collects a set of logically related source files. These are not coupled to any specific host, such as Visual Studio.
  • Features layer: Set of IDE features built on top of the CodeAnalysis and Workspaces API such as code fixes, refactorings, IntelliSense, completion, finding references, and navigating to definition and so on. These are not coupled to any specific host, such as Visual Studio.
  • Visual Studio layer: Visual Studio workspace and project system that brings together and lights up all the compiler and IDE features.

Roslyn is essentially a stack of services that has been written with two core design principles: Extensibility (for layers above and third-party plugins) and Maintainability (it has well-documented and supported public APIs across these layers). External developers or third parties can do bunch of cool stuff on top of these services:

  • Write their own tools for any specific programming layer to accomplish any of the programming tasks noted previously.
  • Write simple plugins (for example diagnostic analyzers, code fixes and refactorings, completion and IntelliSense providers) for specific layers.
  • Perform advanced scenarios at any specific layer, such as implementing their own compiler, Workspace, IDE, or project system, and all the other functionality across the stack lights up automagically.

What this book covers

Chapter 1, Writing Diagnostic Analyzers, enables developers to write diagnostic analyzer extensions to the C# compiler and Visual Studio IDE to analyze source code and report warnings and errors. End users will see these diagnostics on building the project from the command line or Visual Studio and see them live while editing the source code in the Visual Studio IDE.

Chapter 2, Consuming Diagnostic Analyzers in .NET Projects, enables developers in the C# community to harness third-party Roslyn diagnostic analyzers for their C# projects. You will learn how to search, install, view, and configure diagnostic analyzers in Visual Studio.

Chapter 3, Writing IDE Code Fixes, Refactorings, and IntelliSense Completion Providers, enables developers to write code fix and code refactoring extensions to the Visual Studio IDE to edit C# source code to fix compiler/analyzer diagnostics and refactor source code, respectively. It also enables developers to write completion provider extensions to the C# IntelliSense in the Visual Studio IDE for an enhanced code editing experience.

Chapter 4, Improving Code Maintenance of C# Code Base, enables developers in the C# community to improve the code maintenance and readability of their source code by using the analyzers and code fixes that are built into the Visual Studio IDE, as well as some popular third-party implementations.

Chapter 5, Catch Security Vulnerabilities and Performance Issues in C# Code, enables C# community developers to catch security and performance issues in their C# code base by using popular third-party analyzers such as PUMA scan analyzers and FxCop analyers.

Chapter 6, Live Unit Testing in Visual Studio Enterprise, enables developers to use the new Roslyn-based feature in the Visual Studio 2017 Enterprise edition that enables smart live unit test (LUT) execution in the background. LUT automatically runs the impacted unit tests in the background as you edit code, and visualizes the results and code coverage live, in the editor, in real-time.

Chapter 7, C# Interactive and Scripting, enables developers to use C# interactive and scripting features in Visual Studio. C# scripting is a tool for quickly testing out C# and .NET snippets using a REPL (read-evaluate-print-loop), without the effort of creating multiple unit testing or console projects.

Chapter 8, Contribute Simple Functionality to Roslyn C# Compiler Open Source Code, enables developers to add new functionality to the open source Roslyn C# compiler. You will learn how to implement new C# compiler errors, add unit tests for them, and then send a pull request for your code changes to the Roslyn repo to incorporate them in the next version of the C# compiler.

Chapter 9, Design and Implement a New C# Language Feature, enables developers to design a new C# language feature and implement various compiler phases for this feature in the open source Roslyn C# compiler. You will learn the following aspects of compiler design and implementation: language design, parsing, semantic analysis and binding, and code generation, with suitable code examples.

Chapter 10, Command-Line Tools Based on Roslyn API, enables developers to write command-line tools using the Roslyn Compiler and Workspaces API to analyze and/or edit C# code.

What you need for this book

You require Visual Studio 2017 Community/Enterprise edition to execute the recipes in this book. You can install Visual Studio 2017 from https://www.visualstudio.com/downloads/. Additionally, there are some chapters that require you to install GitHub for desktop tooling from https://desktop.github.com/.

Who this book is for

The .NET developers and architects, who are interested in taking full advantage of the Roslyn-based extensions and tools to improve the development processes, will find this book useful. Roslyn contributors, that is the producers and C# community developers, will also find this book useful.

 

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, and user input are shown as follows: "Additionally, the .editorconfig files can be checked into the repo alongside the sources, so that the rules are enforced for every user that contributes to the repo."

A block of code is set as follows:

 private void Method_PreferBraces(bool flag)
  {
    if (flag)
    {
      Console.WriteLine(flag);
    }
  }    

Any command-line input or output is written as follows:

msbuild ClassLibrary.csproj /v:m

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Start Visual Studio, click File | New | Project..., create a new C# class library project, and replace the code in Class1.cs with code from the code sample at ClassLibrary/Class1.cs."

Note

Warnings or important notes appear in a box like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Roslyn-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/RoslynCookbook_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.