Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Tools and Skills for .NET 8
Tools and Skills for .NET 8

Tools and Skills for .NET 8: Get the career you want with good practices and patterns to design, debug, and test your solutions 

Arrow left icon
Profile Icon Mark J. Price
Arrow right icon
₹799.99 ₹3,276.99
Book Jul 2024 778 pages 1st Edition
eBook
₹799.99 ₹3,276.99
Print
₹2,866.99 ₹4,096.99
Subscription
Free Trial
Renews at ₹800p/m
Arrow left icon
Profile Icon Mark J. Price
Arrow right icon
₹799.99 ₹3,276.99
Book Jul 2024 778 pages 1st Edition
eBook
₹799.99 ₹3,276.99
Print
₹2,866.99 ₹4,096.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹799.99 ₹3,276.99
Print
₹2,866.99 ₹4,096.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Tools and Skills for .NET 8

Introducing Tools and Skills for .NET

In this first chapter, the goals are understanding the tools and skills that you will learn in this book, setting up your development environment to use Visual Studio 2022, Visual Studio Code, or JetBrains Rider, and then setting up a database and projects to use in the rest of the chapters. Throughout this book, I will use the names Visual Studio, Code, and Rider to refer to these three code editors respectively.

I use the term modern .NET to refer to .NET 8 and its predecessors like .NET 6, which derive from .NET Core. I use the term legacy .NET to refer to .NET Framework, Mono, Xamarin, and .NET Standard. Modern .NET is a unification of those legacy platforms and standards.

Every chapter in this book introduces some tools and some skills, but some chapters are more focused on a particular tool or a particular skill.

This chapter covers the following topics:

  • Introducing this book and its contents
  • Setting up your development environment
  • Making good use of the GitHub repository for this book
  • Where to go for help
  • Setting up a database and projects for this book
  • Using .NET 9 with this book

The GitHub repository for this book has solutions using full application projects for all code tasks:

https://github.com/markjprice/tools-skills-net8/

After going to the GitHub repository, simply press the . (dot) key on your keyboard or change .com to .dev to change the repository into a live code editor based on Code using GitHub Codespaces. Code in a web browser is great to run alongside your chosen code editor as you work through the book’s coding tasks. You can compare your code to the solution code and easily copy and paste parts if needed.

Introducing this book and its contents

Before we dive into an overview of this book, let’s set the context by understanding that this is one of three books about .NET 8 that I have written that cover almost everything a beginner to .NET needs to know.

Companion books to complete your learning journey

This book is the third of three books in a trilogy that completes your learning journey through .NET 8:

  1. The first book, C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals, covers the fundamentals of the C# language, the .NET libraries, and using ASP.NET Core and Blazor for web development. It is designed to be read linearly because skills and knowledge from earlier chapters build up and are needed to understand later chapters.
  2. The second book, Apps and Services with .NET 8, covers more specialized .NET libraries like internationalization and popular third-party packages including Serilog and Noda Time. You learn how to build native ahead-of-time (AOT)-compiled services with ASP.NET Core Minimal APIs and how to improve performance, scalability, and reliability using caching, queues, and background services. You implement more services using GraphQL, gRPC, SignalR, and Azure Functions. Finally, you learn how to build graphical user interfaces for websites, desktop, and mobile apps with Blazor and .NET MAUI.
  3. This third book covers important tools and skills that a professional .NET developer should have. These include design patterns and solution architecture, debugging, memory analysis, all the important types of testing, whether it be unit, integration, performance, or web user interface testing, and then topics for testing cloud-native solutions on your local computer like containerization, Docker, and .NET Aspire. Finally, we will look at how to prepare for an interview to get the .NET developer career that you want.

A summary of the .NET 8 trilogy and their most important topics is shown in Figure 1.1:

Figure 1.1: Companion books for learning .NET 8 for beginner-to-intermediate readers

We provide you with a PDF file that has color images of the screenshots and diagrams used in this book. You can download this file from https://packt.link/gbp/9781837635207.

Audiences for this book

This book caters to two audiences:

  • Readers who have completed my book for learning the fundamentals of the C# language, .NET libraries, and using ASP.NET Core for web development, C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals, and now want to take their learning further.
  • Readers who already have basic skills and knowledge about C# and .NET and want to acquire practical skills and knowledge of common tools to become more professional with their .NET development, and in particular join a team of .NET developers.

Let’s look at an analogy:

  • First, an amateur cook might buy a book to learn fundamental skills, concepts, and terminology that any cook needs to make the most common dishes.
  • Second, an amateur cook might also buy a recipe book to learn how to apply that knowledge and those skills to make complete meals.
  • Third, to become a professional cook, they would also need to understand the roles in a professional kitchen, learn more specialized tools and skills that are needed when cooking meals for many more people in a professional environment, and how to work in a team of cooks.

These three scenarios are why I wrote three books about .NET.

The preface briefly introduces each chapter, but many readers skip the preface. So, let’s now review why each topic is covered in more depth.

Tools

There are many tools that a professional .NET developer should be familiar with. Some are built into most code editors like a debugger or source control integration, and some require separate applications and services like memory analysis and telemetry.

Even beginner developers know the basic tools included with a code editor like the main editing window, managing files in a project, how to set a breakpoint and start debugging, and then step through the code statement by statement, and how to run a project, so those topics will not be covered in this book.

Chapter 2, Making the Most of the Tools in your Code Editor, is about the less commonly used tools built into Visual Studio, Code, and Rider. The major tools like a debugger or memory analysis tools are covered in separate later chapters. This chapter covers topics like refactoring features and how to customize your code editor using standards like .editorconfig.

Chapter 3, Source Code Management Using Git, covers the most common tasks that you would perform with Git to manage your source code, especially when working in a team of .NET developers. Git is a distributed source control system, so developers have a local copy of the entire repository. This enables offline work, fast branching, and merging. Git is the most popular source code control system for .NET projects, and there are tools and extensions available for seamless integration with all code editors and command-line tools. GitHub is a popular Microsoft platform for hosting Git repositories and collaborating on software projects.

Chapter 4, Debugging and Memory Troubleshooting, is about using the debugging tools in your code editor. You will learn how to use the built-in debugging features, how to decorate your own code with attributes to make it easier to see what’s happening while debugging, and how to use tools in your code editor to track the usage of memory to improve your apps and services.

Chapter 5, Logging, Tracing, and Metrics for Observability, is about how to instrument your code to enable tracing, metrics, and logging during production, and how to implement telemetry using OpenTelemetry to monitor your code as it executes to enable observability.

Skills

As well as learning how to use the tools themselves, a professional .NET developer needs skills like documenting code, leveraging dynamic code, and implementing cryptographic techniques to protect code and data. You will also build a custom chatbot that uses a model enhanced with custom functions.

Chapter 6, Documenting Code, APIs, and Services, discusses how to best document your code to help other developers maintain it in the future using comments, and how to document your services and APIs to enable other developers to call them as designed. Forcing yourself to document your code has the side benefit that you will often spot places where you could improve the design and refactor your code and APIs.

Chapter 7, Observing and Modifying Code Execution Dynamically, introduces you to some common types that are included with .NET for performing code reflection, applying and reading attributes, working with expression trees, and most usefully, creating source generators.

Chapter 8, Protecting Data and Apps Using Cryptography, is about protecting your data from being viewed by malicious users using encryption, and from being manipulated or corrupted using hashing and signing. You will also learn about using authentication and authorization to protect applications from unauthorized users.

Chapter 9, Building a Custom LLM-based Chat Service, covers how to build a custom chat service that integrates a large language model (LLM) and custom functions based on business data.

Chapter 10, Dependency Injection, Containers and Service Lifetime, is about reducing tight coupling between components, which is especially critical to performing practical testing. This also enables you to better manage changes and software complexity.

Testing

One of the most important tools and skills for a .NET developer is testing to ensure quality. Testing spans the whole life cycle of development, from testing a small unit of behavior to end-to-end testing of the user experience and system integration. The earlier in the development process that you test, the lower the cost of fixing any mistakes that you discover.

Chapter 11, Unit Testing and Mocking, introduces testing practices that will improve your code quality. Unit testing is easy to get wrong and can become useless, undermining the team’s trust. Get it right, and you will save time and money and smooth out the development process.

Chapter 12, Integration and Security Testing, introduces a higher level of testing across all components of a solution, and the types of testing needed to maintain the security of your projects.

Chapter 13, Benchmarking Performance, Load, and Stress Testing, introduces how to properly use the BenchmarkDotNet library to monitor your code to measure performance and efficiency. Then, you will see how to perform load and stress testing on your projects to predict required resources and estimate the costs of deployment in production using Bombardier and NBomber.

Chapter 14, Functional and End-to-End Testing of Websites and Services, introduces you to testing APIs and web user interfaces using Playwright for automation.

Chapter 15, Containerization Using Docker, introduces you to the concept of containerization and specifically using Docker to virtualize hosts for services in complex solution architectures.

Chapter 16, Cloud-Native Development Using .NET Aspire, introduces you to .NET Aspire, an opinionated way to manage a cloud-native development environment. It automates local deployments during development and includes integrations with tools you learned about earlier in the book like OpenTelemetry for observability, Docker containers for microservices, and so on.

Design and career development

The final part of this book is about more theoretical concepts like design patterns, principles, and software and solution architecture, and ends with a chapter that wraps everything up with preparing for an interview to get the career that you want with a team of developers and other professionals.

Chapter 17, Design Patterns and Principles, introduces you to the SOLID design patterns as well as other common patterns and principles like DRY (Don’t Repeat Yourself), KISS (Keep It Simple, Stupid), YAGNI (You Ain’t Gonna Need It), and PoLA (Principle of Least Astonishment).

Chapter 18, Software and Solution Architecture Foundations, covers software and solution architecture, including using Mermaid to create architecture diagrams.

Chapter 19, Your Career, Teamwork, and Interviews, covers what you need to get the career you aspire to. To achieve this, you must impress with your resume and at an interview. This chapter covers commonly asked questions in interviews and suggested answers that fit with your experience to help you give realistic responses.

Setting up your development environment

Before you start programming, you’ll need a code editor for C#. Microsoft has a family of code editors and integrated development environments (IDEs), which include:

  • Visual Studio: Visual Studio 2022 for Windows. (Visual Studio 2022 for Mac reaches end-of-life on August 31, 2024, and is not recommended.)
  • Code: Visual Studio Code for Windows, Mac, Linux, the Web, or GitHub Codespaces.
  • Rider: JetBrains Rider, which is available for Windows, Mac, or Linux but does have a license cost. Rider is popular with more experienced .NET developers.

Choosing the appropriate tool and application type for learning

What is the best tool and application type for learning how to use tools and skills with C# and .NET?

I want you to be free to choose any C# code editor or IDE to complete the coding tasks in this book, including Visual Studio, Code, Rider, or a code editor that I’ve never heard of.

In this book, I give general instructions that work with all tools so you can use whichever tool you prefer.

Using Visual Studio for general development

Visual Studio can create most types of applications, including console apps, websites, web services, desktop, and mobile apps. Visual Studio only runs on Windows 10 version 1909 or later, or Windows Server 2016 or later, and only on 64-bit versions. Version 17.4 is the first version to support native ARM64.

Warning!

Visual Studio for Mac does not officially support .NET 8 and it will reach end-of-life in August 2024. If you have been using Visual Studio for Mac then you should switch to Code for Mac or Rider for Mac, or use Visual Studio in a virtual machine on your local computer or in the cloud using a technology like Microsoft Dev Box. The retirement announcement can be read here: https://devblogs.microsoft.com/visualstudio/visual-studio-for-mac-retirement-announcement/.

Using Code for cross-platform development

The most modern and lightweight code editor to choose from, and the only one from Microsoft that is cross-platform, is Code. It can run on all common operating systems, including Windows, macOS, and many varieties of Linux, including Red Hat Enterprise Linux (RHEL) and Ubuntu. Code is a good choice for modern cross-platform development because it has an extensive and growing set of extensions to support many languages beyond C#.

Being cross-platform and lightweight, it can be installed on all platforms that your apps will be deployed to for quick bug fixes and so on. Choosing Code means a developer can use a cross-platform code editor to develop cross-platform apps.

Code is by far the most popular IDE, with over 74% of professional developers selecting it in the Stack Overflow 2023 survey, which you can read at the following link: https://survey.stackoverflow.co/2023/#most-popular-technologies-new-collab-tools-prof.

Using GitHub Codespaces for development in the cloud

GitHub Codespaces is a fully configured development environment based on Code that can be spun up in an environment hosted in the cloud and accessed through any web browser. It supports Git repositories, extensions, and a built-in command-line interface so you can edit, run, and test from any device. Since it runs in the cloud and you interact with it via a web browser there is nothing to download and install, and since it is based on Code, it works the same way Code does on your local computer.

More Information

You can learn more about GitHub Codespaces at the following link: https://github.com/features/codespaces. Microsoft Dev Box is another way to host a development environment: https://azure.microsoft.com/en-us/products/dev-box.

Reviews of GitHub Codespaces are available at the following links:

Using Rider for cross-platform development

Rider is a third-party code editor from JetBrains, the maker of IntelliJ IDEA, the leading Java and Kotlin IDE, and ReSharper, the popular Visual Studio plugin for .NET developers. Rider runs on multiple platforms: Windows, macOS, and Linux.

It has a license fee, but developers who use it are often professionals who appreciate the extra features it has like live code inspections, context actions, and refactorings. Using Rider can be an indicator of a more advanced developer.

You should expect new versions of Rider to support the latest version of .NET a few weeks after Visual Studio. For example, .NET 8 was released on November 14, 2023, and Visual Studio with official support for .NET 8 was released on the same day. But Rider version 2023.3 with official support for .NET 8 was not released until December 7, 2023.

Although JetBrains is a fantastic company with great products, both Rider and the ReSharper extension for Visual Studio are software, and all software has bugs and quirky behavior. For example, they might show errors like “Cannot resolve symbol” in your Razor Pages, Razor views, and Blazor components. Yet, you can build and run those files because there is no actual problem.

If you use Rider and you have installed the Unity Support or Heap Allocation Viewer plugins, then it will complain a lot about boxing. A common scenario when boxing happens is when value types like int and DateTime are passed as positional arguments to string formats. This is a problem for Unity projects because they use a different memory garbage collector than the normal .NET runtime. For non-Unity projects, like all the projects in this book, you can ignore these boxing warnings because they are not relevant. You can read more about this Unity-specific issue at the following link: https://docs.unity3d.com/Manual/performance-garbage-collection-best-practices.html#boxing.

What I used

To write and test the code for this book, I used the following hardware and software:

  • Visual Studio on:
    • Windows 11 on an HP Spectre (Intel) laptop
  • Code on:
    • macOS on an Apple Silicon Mac mini (M1) desktop
    • Windows 11 on an HP Spectre (Intel) laptop
  • Rider on:
    • Windows 11 on an HP Spectre (Intel) laptop
    • macOS on an Apple Silicon Mac mini (M1) desktop

I hope that you have access to a variety of hardware and software too because seeing the differences on various platforms deepens your understanding of development challenges, although any one of the preceding combinations is enough to learn how to build practical apps and websites.

Deploying cross-platform

Your choice of code editor and operating system for development does not limit where your code gets deployed.

.NET 8 supports the following platforms for deployment:

  • Windows: Windows 10 version 1607 or later. Windows 11 version 22000 or later. Windows Server 2012 R2 SP1 or later. Nano Server version 1809 or later.
  • Mac: macOS Catalina version 10.15 or later and in the Rosetta 2 x64 emulator. Mac Catalyst: 11.0 or later.
  • Linux: Alpine Linux 3.17 or later. Debian 11 or later. Fedora 37 or later. openSUSE 15 or later. Oracle Linux 8 or later. Red Hat Enterprise Linux (RHEL) 8 or later. SUSE Enterprise Linux 12 SP2 or later. Ubuntu 20.04 or later.
  • Android: API 21 or later.
  • iOS and tvOS: 11.0 or later.

You can review the latest supported operating systems and versions at the following link: https://github.com/dotnet/core/blob/main/release-notes/8.0/supported-os.md.

Downloading and installing Visual Studio

Many professional .NET developers use Visual Studio in their day-to-day development work. Even if you choose to use Code to complete the coding tasks in this book, you might want to familiarize yourself with Visual Studio too.

If you do not have a Windows computer, then you can skip this section and continue to the next section, where you will download and install Code on macOS or Linux.

Since October 2014, Microsoft has made a professional quality edition of Visual Studio available to students, open-source contributors, and individuals for free. It is called Community Edition. Any of the editions are suitable for this book. If you have not already installed it, let’s do so now:

  1. Download Visual Studio version 17.10 or later from the following link: https://visualstudio.microsoft.com/downloads/.

You must install version 17.10 or later for the new Copilot experience.

  1. Start the installer.
  2. On the Workloads tab, select the following:
    • ASP.NET and web development
    • .NET desktop development (because this includes console apps).
    • Desktop development with C++ with all default components (because this enables publishing console apps and web services that start faster and have smaller memory footprints).
  3. On the Individual components tab, in the Code tools section, select the following:
    • GitHub Copilot
    • Git for Windows
  4. Click Install and wait for the installer to acquire the selected software and install it.
  5. When the installation is complete, click Launch.
  6. The first time that you run Visual Studio, you will be prompted to sign in. If you have a Microsoft account, you can use that account. If you don’t, then register for a new one at the following link: https://signup.live.com/.
  7. The first time that you run Visual Studio, you will be prompted to configure your environment. For Development Settings, choose Visual C#. For the color theme, I chose Blue, but you can choose whatever tickles your fancy.
  8. If you want to customize your keyboard shortcuts, navigate to Tools | Options…, and then select the Environment | Keyboard option.

Visual Studio keyboard shortcuts

In this book, I will avoid showing keyboard shortcuts since they are often customized. Where they are consistent across code editors and commonly used, I will try to show them.

If you want to identify and customize your keyboard shortcuts, then you can, as shown at the following link: https://learn.microsoft.com/en-us/visualstudio/ide/identifying-and-customizing-keyboard-shortcuts-in-visual-studio.

Visual Studio Enterprise edition tools

Visual Studio Enterprise edition is designed for larger teams and organizations with advanced development, testing, and deployment needs. It adds exclusive capabilities tailored for enterprise-scale projects and advanced development scenarios. Licenses for the Enterprise edition cost thousands of dollars so are typically limited to people who work for large organizations. Therefore, I do not cover these features and tools in this book.

Some tools that are exclusive to Visual Studio Enterprise edition are shown in the following list:

  • IntelliTrace allows developers to record and replay application execution, enhancing the debugging process by providing a historical context of what happened before an issue occurred.
  • Code Map visualizes and explores complex codebases, making it easier to understand and navigate relationships and dependencies within the code.
  • Live Unit Testing automatically runs impacted unit tests in the background and displays real-time results and code coverage, ensuring immediate feedback on changes.
  • Microsoft Fakes supports the creation of shim and stub objects, enabling the testing of code in isolation by replacing parts of the application with mock objects.
  • Web load and performance testing allow developers to create, manage, and execute performance tests to evaluate the scalability and responsiveness of web applications under heavy load.
  • Coded UI testing supports the creation of automated tests for the user interface of applications, ensuring that the UI behaves as expected.
  • CodeLens enhances code understanding by providing insights directly within the editor, such as change history, code references, and work item details, without the need to navigate away from the code.
  • Architecture and dependency validation help ensure that development efforts adhere to predefined architecture dependencies and layering standards and constraints, preventing architectural drift.
  • Advanced static code analysis offers more comprehensive rules and capabilities for analyzing code quality and potential issues, beyond what is available in the other editions.
  • Release management provides advanced release management features and tools for automating the deployment process, helping teams deliver software more quickly and reliably.
  • Snapshot debugger allows developers to take snapshots of their production environments, enabling them to inspect the state and debug issues without impacting the live environment.
  • App Center Test allows automated UI testing on thousands of real devices in the cloud.

Downloading and installing Code

Code has rapidly improved over the past couple of years and has pleasantly surprised Microsoft with its popularity. If you are brave and like to live on the bleeding edge, then there is the Insiders edition, which is a daily build of the next version.

Even if you plan to only use Visual Studio for development, I recommend that you download and install Code and try the coding tasks in this chapter using it, and then decide if you want to stick with just using Visual Studio for the rest of the book.

Let’s now download and install Code, the .NET SDK, and the C# Dev Kit extension:

  1. Download and install either the Stable Build or the Insiders edition of Code from the following link: https://code.visualstudio.com/.

More Information

If you need more help installing Code on any operating system, you can read the official setup guide at the following link: https://code.visualstudio.com/docs/setup/setup-overview.

  1. Download and install the .NET SDK for version 8.0 from the following link: https://www.microsoft.com/net/download.

Good Practice

The latest SDK version at the time of writing in June 2024 is 8.0.301. Always install or update to the latest patched version.

  1. To install the C# Dev Kit extension using the user interface, you must first launch the Code application.
  2. In Code, click the Extensions icon or navigate to View | Extensions.
  3. C# Dev Kit is one of the most popular extensions available, so you should see it at the top of the list, or you can enter C# Dev Kit in the search box.

C# Dev Kit has a dependency on the C# extension version 2.0 or later, so you do not have to install the C# extension separately. Note that C# extension version 2.0 or later no longer uses OmniSharp since it has a new Language Service Protocol (LSP) host. C# Dev Kit also has dependencies on the .NET Install Tool for Extension Authors and IntelliCode for C# Dev Kit extensions, so they will be installed, too.

  1. Click Install and wait for supporting packages to download and install.

Good Practice

Be sure to read the license agreement for the C# Dev Kit. It has a more restrictive license than the C# extension: https://aka.ms/vs/csdevkit/license.

Installing other extensions

In later chapters of this book, you will use more Code extensions. If you want to install them now, all the extensions that we will use are shown in Table 1.1:

Extension name and identifier

Description

C# Dev Kit

ms-dotnettools.csdevkit

An official C# extension from Microsoft. Manage your code with a solution explorer and test your code with integrated unit test discovery and execution.

It includes the C# and IntelliCode for C# Dev Kit extensions.

C#

ms-dotnettools.csharp

This offers C# editing support, including syntax highlighting, IntelliSense, Go To Definition, Find All References, debugging support for .NET, and support for csproj projects on Windows, macOS, and Linux.

IntelliCode for C# Dev Kit

ms-dotnettools.vscodeintellicode-csharp

This provides AI-assisted development features for Python, TypeScript/JavaScript, C#, and Java developers.

MSBuild project tools

tintoy.msbuild-project-tools

This provides IntelliSense for MSBuild project files, including autocomplete for <PackageReference> elements.

SQL Server (mssql) for Visual Studio Code

ms-mssql.mssql

This is for developing SQL Server, Azure SQL Database, and SQL Data Warehouse everywhere with a rich set of functionalities.

REST Client

humao.rest-client

With this, you can send an HTTP request and view the response directly in Code.

ilspy-vscode

icsharpcode.ilspy-vscode

With this, you can decompile Microsoft Intermediate Language (MSIL) aka .NET assemblies. It supports modern .NET, .NET Framework, .NET Core, and .NET Standard.

Table 1.1: Code extensions used in this book

Managing Code extensions at the command prompt

You can manage Code extensions at the command prompt or terminal, as shown in Table 1.2:

Command

Description

code --list-extensions

List installed extensions.

code --install-extension <extension-id>

Install the specified extension.

code --uninstall-extension <extension-id>

Uninstall the specified extension.

Table 1.2: Working with extensions at the command prompt

For example, to install the C# Dev Kit extension, enter the following at the command prompt:

code --install-extension ms-dotnettools.csdevkit

I have created PowerShell scripts to install and uninstall the Code extensions in the preceding table. You can find them at the following link: https://github.com/markjprice/tools-skills-net8/tree/main/scripts/extension-scripts.

Understanding Code versions

Microsoft releases a new feature version of Code (almost) every month and bug-fix versions more frequently. For example:

  • Version 1.90.0, May 2024 feature release
  • Version 1.90.1, May 2024 bug fix release

The version of Code is less important than the version of the C# extension. While the C# extension is not required, it provides IntelliSense as you type, code navigation, and debugging features, so it’s something that’s very handy to install and keep updated to support the latest C# language features.

Code keyboard shortcuts

In this book, I will avoid showing keyboard shortcuts used for tasks like creating a new file since they are often different on different operating systems. The situations where I will show keyboard shortcuts are when you need to repeatedly press the key, for example, while debugging. These are also more likely to be consistent across operating systems.

If you want to customize your keyboard shortcuts for Code, then you can, as shown at the following link: https://code.visualstudio.com/docs/getstarted/keybindings.

I recommend that you download a PDF of keyboard shortcuts for your operating system from the following list:

Downloading and installing Rider

According to the Stack Overflow Survey 2023, about 20% of professional C# and .NET developers use Rider in their day-to-day development work. Rider is cross-platform so you can install and run it on Windows, macOS, and varieties of Linux. You can use an evaluation license key for a free 30-day trial.

JetBrains also offers Toolbox App to manage your IDEs easily and it’s free. It is especially useful for Linux users because Rider does not update through the apt (Advanced Package Tool) command like normal Linux programs. It also gives you access to early access programs for software like JetBrains Fleet, a next-generation code editor.

If you have not already installed Rider and you want to use it, let’s do so now:

  1. Download the latest version of Rider from the following link: https://www.jetbrains.com/rider/download/.

If you’re on Ubuntu 16.04 or later, you can install Rider from the command prompt or terminal, as shown in the following command: sudo snap install rider --classic

  1. Run the installer.
  2. Download the latest version of JetBrains Toolbox App from the following link: https://www.jetbrains.com/toolbox-app/.
  3. Run the installer.
  4. Navigate to https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022 and install the Build Tools for Visual Studio. These are necessary to use the native ahead-of-time (AOT) compiler.

If you have installed JetBrains ReSharper in Visual Studio, you will get the same tools as in Rider.

Other JetBrains tools

JetBrains offers a suite of tools designed to enhance productivity, code quality, and application performance for .NET developers. A brief overview of dotPeek, dotTrace, dotMemory, and dotCover, highlighting their capabilities and benefits, is included in the following list:

  • dotPeek: This tool can decompile .NET assemblies back to readable C# code, making it easier to explore and understand external code that lacks a source. It allows browsing the contents of assemblies, helping developers explore the structure and dependencies without needing the source code. It provides advanced navigation and search capabilities within decompiled code, such as quick jumping to symbol definitions and usages. It’s invaluable for understanding the inner workings of third-party libraries, frameworks, or any compiled .NET code without the original source. It can serve as a symbol server, making it possible to step into decompiled code during debugging sessions, aiding in the diagnosis of issues with external libraries. dotPeek is offered as a free tool, making advanced decompilation and assembly exploration accessible to all .NET developers.
  • dotTrace: This tool provides detailed performance profiling for .NET applications, identifying performance bottlenecks by measuring execution times and call frequencies. It supports sampling, tracing, and timeline modes, each suited to different types of performance analysis. It offers a comprehensive set of views and filters to analyze the profiling data, including call trees, hot spots, and timeline views. It helps developers optimize application performance by pinpointing slow-running code and inefficient algorithms.
  • dotMemory: This tool analyzes memory usage of .NET applications, identifying memory leaks and issues related to Garbage Collector (GC). It helps understand how memory is allocated and released, pinpointing excessive allocations that could lead to performance degradation. It allows the comparison of memory snapshots taken at different times, making it easier to identify memory leaks and the objects responsible. It facilitates memory optimization by providing insights into memory consumption patterns and detecting memory leaks.
  • dotCover: This tool measures how much of the codebase is covered by tests, highlighting covered and uncovered code blocks. It works with various testing frameworks and supports all .NET applications, enhancing test effectiveness. It provides a continuous testing mode that automatically runs tests in the background as code changes, offering immediate feedback on test coverage and success. It helps improve code quality by ensuring higher coverage of tests, which can lead to fewer bugs and more stable applications. It facilitates an efficient testing process by identifying untested code, allowing developers to focus on areas lacking test coverage.

Together, these JetBrains tools form a comprehensive toolkit that can significantly enhance the productivity and efficiency of .NET development teams.

Chrome AI tools

Chrome now has AI tools built-in that you can read about at the following link: https://developer.chrome.com/docs/devtools/console/understand-messages.

Making good use of the GitHub repository for this book

Git is a commonly used source code management system. GitHub is a company, website, and desktop application that makes it easier to manage Git. Microsoft purchased GitHub in 2018, so it will continue to be closely integrated with Microsoft tools.

I created a GitHub repository for this book, and I use it for the following:

  • To store the solution code for the book, which will be maintained after the print publication date
  • To provide extra materials that extend the book, like errata fixes, small improvements, lists of useful links, and longer articles that cannot fit in the printed book
  • To provide a place for readers to get in touch with me if they have issues with the book

Raising issues with the book

If you get stuck following any of the instructions in this book, or if you spot a mistake in the text or the code in the solutions, please raise an issue in the GitHub repository:

  1. Use your favorite browser to navigate to the following link: https://github.com/markjprice/tools-skills-net8/issues.
  2. Click New Issue.
  3. Enter as much detail as possible that will help me to diagnose the issue. For example:
    • The specific section title, page number, and step number
    • Your code editor, for example, Visual Studio, Code, Rider, or something else, including the version number
    • As much of your code and configuration that you feel is relevant and necessary
    • A description of the expected behavior and the behavior experienced
    • Screenshots (you can drag and drop image files into the issue box)

The following is less relevant but might be useful:

  • Your operating system, for example, Windows 11 64-bit, or macOS Big Sur version 11.2.3
  • Your hardware, for example, Intel, Apple Silicon, or ARM CPU

I want all my readers to be successful with my book, so if I can help you (and others) without too much trouble, then I will gladly do so.

Giving me feedback

If you’d like to give me more general feedback about the book, then you can email me at markjprice@gmail.com. My publisher, Packt, has set up Discord channels for readers to interact with authors and other readers. You are welcome to join us at the following link: https://packt.link/TS1e.

I love to hear from my readers about what they like about my books, as well as suggestions for improvements and how they are working with C# and .NET, so don’t be shy. Please get in touch!

Thank you in advance for your thoughtful and constructive feedback.

Downloading solution code from the GitHub repository

I use GitHub to store solutions to all the hands-on, step-by-step coding tasks throughout chapters and the practical exercises that are featured at the end of each chapter. You will find the repository at the following link: https://github.com/markjprice/tools-skills-net8.

If you just want to download all the solution files without using Git, click the green Code button and then select Download ZIP.

I recommend that you add the preceding link to your favorites or bookmarks.

Good Practice

It is best to clone or download the code solutions to a short folder path, like C:\tools-skills-net8\ or C:\book\, to avoid build-generated files exceeding the maximum path length. You should also avoid special characters like #. For example, do not use a folder name like C:\C# projects\. That folder name might work for a simple console app project but once you start adding features that automatically generate code, you are likely to have strange issues. Keep your folder names short and simple.

Where to go for help

This section is all about how to find quality information about programming on the web.

My books are specifically written in a tutorial style so that you can get started quickly and confidently before then switching to the official documentation for more details or specialized scenarios.

This technique is commonly used by developers to learn how to code. More than 50% use books or other physical media, and then more than 80% use other online resources, as shown in the Stack Overflow Survey 2023 at the following link: https://survey.stackoverflow.co/2023/#section-learning-to-code-learning-how-to-code.

Reading documentation on Microsoft Learn

The definitive resource for getting help with Microsoft developer tools and platforms is in the technical documentation on Microsoft Learn, and you can find it at the following link: https://learn.microsoft.com/en-us/docs.

Getting help for the dotnet tool

At the command prompt, you can ask the dotnet tool for help with its commands. The syntax is:

dotnet help <command>

This will cause your web browser to open a page in the documentation about the specified command. Common dotnet commands include new, build, and run.

Warning

The dotnet help new command worked with .NET Core 3.1 to .NET 6, but it returns an error with .NET 7 or later: Specified command 'new' is not a valid SDK command. Specify a valid SDK command. For more information, run dotnet help. Hopefully, the .NET team will fix that bug soon!

Another type of help is command-line documentation. It follows this syntax:

dotnet <command> -?|-h|--help

For example, dotnet new -?, dotnet new -h, or dotnet new --help output documentation about the new command at the command prompt.

LLMs like ChatGPT

One of the biggest changes in coding and development in the past year or so is the emergence of generative AI tools and LLMs that can help with coding tasks like completing a code statement, implementing an entire function, writing unit tests, and suggesting debugging fixes for existing code.

ChatGPT currently has several models: 3.5 and 4o (both free) and the Plus individual subscription ($20 per month). There are also Team and Enterprise subscriptions. You can compare options at the following link: https://openai.com/chatgpt/pricing/.

Let’s say you need to understand more about .NET tools and skills. You might enter the following prompt: “What are the most important tools and skills for a professional .NET developer to learn?”

The response would be something like the following:

“Hey there! When it comes to being a professional .NET developer, there are several essential tools and skills you should consider mastering. Here’s a detailed breakdown:

Tools:

  • Visual Studio: This IDE is the go-to choice for .NET development. Make sure you’re comfortable with its features and extensions.
  • Visual Studio Code: While Visual Studio is powerful, Visual Studio Code is a lightweight, versatile code editor that’s becoming increasingly popular among .NET developers.
  • .NET Core/.NET 5 and beyond: Stay up to date with the latest versions of the .NET framework. .NET 5 and its successors offer cross-platform support and performance improvements.
  • Git and GitHub: Version control is crucial. Git is a widely used distributed version control system, and GitHub provides a platform for collaborative development and code sharing.
  • Azure DevOps: Familiarize yourself with Azure DevOps for managing projects and continuous integration and continuous deployment (CI/CD) pipelines.
  • NuGet: Understanding package management with NuGet is essential for adding libraries and packages to your .NET projects.
  • Docker: Containerization is becoming increasingly important for deploying .NET applications. Docker can help you create and manage containers effectively.

Skills:

  • C#: As a .NET developer, C# is your primary language. Master object-oriented programming concepts, asynchronous programming, and LINQ.
  • ASP.NET Core: For web development, ASP.NET Core is the framework of choice. Learn about MVC architecture, Razor Pages, and API development.
  • Entity Framework Core: Understand how to work with databases using Entity Framework Core for efficient data access.
  • Dependency injection: Grasp the principles of dependency injection and how it’s used in .NET for managing object dependencies.
  • Unit testing: Writing unit tests using tools like xUnit or NUnit is crucial for ensuring the reliability of your code.
  • Web API design: If you’re building APIs, learn about RESTful design principles, authentication, and versioning.
  • Frontend technologies: Familiarize yourself with HTML, CSS, JavaScript, and frontend frameworks like React or Angular if you’re involved in web development.
  • Azure services: If you’re working in the cloud, explore Azure services like Azure Functions, Azure SQL Database, and Azure App Service.
  • Security: Understand security best practices, including authentication, authorization, and data protection.
  • Performance optimization: Learn about profiling, caching, and other techniques to optimize the performance of your applications.
  • Agile methodologies: Agile practices like Scrum and Kanban are widely used in software development. Understanding them can improve team collaboration.
  • Soft skills: Communication, problem solving, and teamwork are essential soft skills for any professional developer.

Now, I’ve covered quite a bit here, but remember that the tech landscape is always evolving. Staying curious and continuously learning is a vital skill in itself. If you have any specific questions or need more details on any of these topics, feel free to ask!”

There are a few topics that ChatGPT mentions that my books do not cover. These are:

  • Azure DevOps and Azure Services: For this book, I decided to remove requirements for Azure and other cloud services. I want all readers of my book to be able to complete all the tasks on their local computer without paying for a cloud account. I want to avoid pushing readers toward any particular cloud provider so from now on my books will be cloud agnostic.
  • Front-end technologies: HTML, CSS, and JavaScript, and the many, many client-side application frameworks like React and Angular.
  • Agile methodologies: This and other methodologies really need a whole book to cover them in depth. If I can find a way to usefully introduce them in only a few pages, then the next edition might do that.

Getting better help from LLMs using prompt engineering

You might have heard the term prompt engineering. This is an important skill for any professional to have since modern tasks will commonly be completed more efficiently by collaborating with an AI.

AI tools that integrate closely with your code editor like GitHub Copilot will be covered in Chapter 2, Making the Most of Your Code Editor.

To clarify or get a deeper understanding of a topic, or any piece of information, you can use the following prompt templates:

  • Explain [insert specific topic] in simple terms.
  • Explain to me like I’m a beginner in [field].
  • Explain to me in a natural, human-like manner.
  • Explain to me as if I’m 10 years old.
  • Write a detailed [essay/text/paragraph] for me about [topic] by adding all the information necessary.

Use affirmative directives and avoid negative formulations like “don’t.”

For complex answers, or when it responds with a shallow answer, include the phrase “think step-by-step.”

Assign a role to the large language models. For example, “You are an expert solution architect with decades of experience implementing .NET.”

If you’re unsure how to phrase a prompt, get the LLM to help you! For example:

“I want you to be my Prompt Engineer. Your goal is to assist me in creating the best prompt for my needs. The prompt will be used by you, ChatGPT. You will follow these steps: Your first response will be to ask me what the prompt should be about. I will provide my answer, but we will need to work together to improve it through continuous iterations by going through the next steps. Based on my input you will generate three sections:

  1. Revised prompt. Please provide your rewritten prompt. It should be clear, concise, and easily understood.
  2. Suggestions. Please provide ideas on what details to include in the prompt to enhance it.
  3. Questions. Please ask any relevant questions to gather additional information from me and improve the prompt.

We will continue this iterative process with me providing more information to you and you updating the prompt in the Revised prompt section until it’s complete. Thank you!”

If you own a PC with an Nvidia GTX card, then you can download a free chat app to customize and converse with local LLMs. It can even process files like PDFs. If any of you try adding a PDF of any of my books so that you can ask questions about them, please let me know how you get on. You can find out more at the following link: https://blogs.nvidia.com/blog/chat-with-rtx-available-now/.

AI usage by developers

According to the Stack Overflow Survey 2023 (https://survey.stackoverflow.co/2023/#section-sentiment-and-usage-ai-tools-in-the-development-process), “70% of all respondents are using or are planning to use AI tools in their development process this year. Those learning to code are more likely than professional developers to be using or use AI tools (82% vs. 70%).”

Getting help on Discord and other chat forums

Asking questions in programming forums and Discord channels is an art as much as it is a science. To maximize your chances of receiving a helpful answer, there’s a blend of clarity, specificity, and community awareness that you should aim for.

Here are some tips for asking questions:

  • Ask in a public channel, not in private: Please do not direct message an author with a question or a friend request. Remember, every question asked and answered builds the collective knowledge and resourcefulness of the whole community. Asking in public also allows other readers to help you, not just the author. The community that Packt and I have built around my books is friendly and smart. Let us all help you.
  • Research before asking: It’s important to look for answers yourself before turning to the community. Use search engines, official documentation, and the search function within the forum or Discord server. This not only respects the community’s time but also helps you learn more effectively. Another place to look first is the errata section of the book at the following link: https://github.com/markjprice/tools-skills-net8/blob/main/docs/errata/README.md.
  • Be specific and concise: Clearly state what you’re trying to achieve, what you’ve tried so far, and where you’re stuck. A concise question is more likely to get a quick response.
  • Specify the book location: If you are stuck on a particular part of the book, specify the page number and section title so that others can look up the context of your question.
  • Show your work: Demonstrating that you’ve made an effort to solve the problem yourself not only provides context but also helps others understand your thought process and where you might have gone wrong.
  • Prepare your question: Avoid too broad or too vague questions. Screenshots of errors or code snippets (with proper formatting) can be very helpful.

Oddly, I’ve been seeing more and more examples of readers taking photos of their screen and posting those. These are harder to read and limited in what they can show. It’s better to copy and paste the text of your code or the error message so that others can copy and paste it themselves. Or at least take a high resolution screenshot instead of a photo!

  • Format your code properly: Most forums and Discord servers support code formatting using Markdown syntax. Use formatting to make your code more readable. For example, surround code keywords in single backticks like this: `public void`, and surround code blocks with three backticks with an optional language code, as shown in the following code:
    ```cs
    using static System.Console;
    WriteLine("This is C# formatted code.");
    ```
    

Good Practice

After the three backticks that start a code block in Markdown, specify a language code like cs, csharp, js, javascript, json, html, css, cpp, xml, mermaid, python, java, ruby, go, sql, bash, or shell.

More Information

To learn how to format text in Discord channel messages, see the following link: https://support.discord.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline.

  • Be polite and patient: Remember, you’re asking for help from people who are giving their time voluntarily. A polite tone and patience while waiting for a response go a long way. Channel participants are often in a different timezone so may not see your question until the next day.
  • Be ready to actively participate: After asking your question, stay engaged. You might receive follow-up questions for clarification. Responding promptly and clearly can significantly increase your chances of getting a helpful answer. When I ask a question, I set an alarm for three hours later to go back and see if anyone has responded. If there hasn’t been a response yet, then I set another alarm for 24 hours later.

Incorporating these approaches when asking questions not only increases your likelihood of getting a useful response but also contributes positively to the community by showing respect for others’ time and effort.

Good Practice

Never just say “Hello” as a message on any chat system. You can read why at the following link: https://nohello.net/. Similarly, don’t ask to ask: https://dontasktoask.com/.

Setting up a database and projects for this book

We need a database and some projects that we can use throughout this book. To make it reasonably realistic, we need multiple projects that use common features like a SQL Server database, class libraries, unit tests, and so on.

We will define an entity data model as a pair of reusable class libraries. One part of the pair will define the entities like Product and Customer. The second part of the pair will define the tables in the database, the default configuration for how to connect to the database, and use the Fluent API to configure additional options for the model.

We will create three projects:

  • A class library for entity models like Category and Product named Northwind.EntityModels
  • A class library for an EF Core data context named Northwind.DataContext
  • An xUnit project for unit and integration tests named Northwind.Tests

Using a sample relational database

It would be useful to have a sample database that has a medium complexity and a decent number of sample records. Microsoft offers several sample databases, most of which are too complex for our needs, so instead, we will use a database that was first created in the early 1990s known as Northwind.

Let’s take a minute to look at a diagram of the Northwind database and its eight most important tables. You can use the diagram in Figure 1.2 to refer to as we write code and queries throughout this book:

A screenshot of a computer

Description automatically generated

Figure 1.2: The Northwind database tables and relationships

Note that:

  • Each category has a unique identifier, name, description, and picture. The picture is stored as a byte array in JPEG format.
  • Each product has a unique identifier, name, unit price, number of units in stock, and other columns.
  • Each product is associated with a category by storing the category’s unique identifier.
  • The relationship between Categories and Products is one-to-many, meaning each category can have zero, one, or more products.
  • Each product is supplied by a supplier company indicated by storing the supplier’s unique identifier.
  • The quantity and unit price of a product is stored for each detail of an order.
  • Each order is made by a customer, taken by an employee, and shipped by a shipping company.
  • Each employee has a name, address, contact details, birth, and hire dates, a reference to their manager (except for the boss, whose ReportsTo field is null), and a photo stored as a byte array in JPEG format. The table has a one-to-many relationship to itself because one employee can manage many other employees.

Setting up SQL Server and the Northwind database

Microsoft offers various editions of its popular and capable SQL Server product for Windows, Linux, and Docker containers.

If you have Windows, then you can use a free version that runs standalone, known as SQL Server Developer Edition. You can also use the Express edition or the free SQL Server LocalDB edition that can be installed with Visual Studio. To install SQL Server locally on Windows, please see the online instructions at the following link: https://github.com/markjprice/tools-skills-net8/blob/main/docs/sql-server/README.md. If you prefer to install SQL Server locally on Linux, then you will find instructions at the following link: https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-setup.

If you do not have a Windows computer or if you want to use a cross-platform database system, then please see the online-only section, Installing Azure SQL Edge in Docker, found at the following link: https://github.com/markjprice/tools-skills-net8/blob/main/docs/sql-server/edge.md.

You’ll need to have set up SQL Server, run the SQL script to create the Northwind database and confirm that you can connect to the database and view the rows in its tables like Products and Categories before continuing with the project. The following two subsections provide detailed steps to help you do so using either a local SQL Server or SQL Edge in Docker. You can skip this if you already have this set up.

Creating the Northwind database for a local SQL Server

To run a SQL script to create the Northwind sample database for a local SQL Server:

  1. If you have not previously downloaded or cloned the GitHub repository for this book, then do so now using the following link: https://github.com/markjprice/tools-skills-net8/.
  2. Copy the script to create the Northwind database for SQL Server from the following path in your local Git repository: /scripts/sql-scripts/Northwind4SQLServer.sql into a working folder.
  3. Start SQL Server Management Studio.
  4. In the Connect to Server dialog, for Server name, enter . (a dot), meaning the local computer name, and then click the Connect button. If you had to create a named instance, like tools-skills-net8, then enter .\tools-skills-net8.
  5. Navigate to File | Open | File....
  6. Browse to select the Northwind4SQLServer.sql file and then click the Open button.
  7. In the toolbar, click Execute, and note the Command(s) completed successfully message.
  8. In Object Explorer, expand the Northwind database, and then expand Tables.
  9. Right-click Products, click Select Top 1000 Rows, and note the returned results.
  10. Exit SQL Server Management Studio.

Creating the Northwind database for SQL Edge in Docker

To run a database script to create the Northwind sample database for SQL Edge in Docker:

  1. In your preferred code editor, open the Northwind4AzureSQLedge.sql file.
  2. Connect to SQL Edge in Docker using the following connection information:
    • Data Source aka server: tcp:127.0.0.1,1433
    • You must use SQL Server Authentication aka SQL Login i.e. you must supply a user name and password. Azure SQL Edge image has the sa user already created and you had to give it a strong password when you ran the container. We chose the password s3cret-Ninja.
    • Database: master or leave blank. We will create the Northwind database using a SQL script.
  3. Execute the SQL script:
    • If you are using Visual Studio, right-click in the script, select Execute, and then wait to see the Command completed successfully message.
    • If you are using Code, right-click in the script, select Execute Query, select the Azure SQL Edge in Docker connection profile, and then wait to see the Commands completed successfully messages.
  4. Refresh the data connection:
    • If you are using Visual Studio, then in Server Explorer, right-click Tables and select Refresh.
    • If you are using Code, then right-click the Azure SQL Edge in Docker connection profile and choose Refresh.
  5. Expand Databases, expand Northwind, and then expand Tables.
  6. Note that 13 tables have been created, for example, Categories, Customers, and Products. Also note that dozens of views and stored procedures have also been created.
  7. Next, we will define an entity data model for the Northwind database as a pair of reusable class libraries.

Good Practice

You should create a separate class library project for your entity data models. This allows easier sharing between backend web servers and frontend desktop, mobile, and Blazor clients.

Creating a class library for entity models using SQL Server

You will now create the entity models using the dotnet-ef tool:

  1. Using your preferred code editor, create a new project, as defined in the following list:
    • Project template: Class Library / classlib
    • Project file and folder: Northwind.EntityModels
    • Solution file and folder: Chapter01
  2. In the Northwind.EntityModels project, treat warnings as errors, and add package references for the SQL Server database provider and EF Core design-time support, as shown highlighted in the following markup:
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference
          Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
        <PackageReference
          Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference> 
      </ItemGroup>
    </Project>
    

If you are unfamiliar with how packages like Microsoft.EntityFrameworkCore.Design can manage their assets, then you can learn more at the following link: https://learn.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#controlling-dependency-assets.

Good Practice

By default, compiler warnings may appear if there are potential problems with your code when you first build a project, but they do not prevent compilation and they are hidden if you rebuild. Warnings are given for a reason, so ignoring warnings encourages poor development practices. I recommend that you force yourself to fix warnings by enabling the option to treat warnings as errors.

  1. Delete the Class1.cs file.
  2. Build the Northwind.EntityModels project.
  3. Open a command prompt or terminal for the Northwind.EntityModels folder.
  4. If you do not already have the dotnet-ef tool, then install the latest version, as shown in the following command:
    dotnet tool install --global dotnet-ef
    
  5. Instead of installing, you can update using the following command:
    dotnet tool update --global dotnet-ef
    

The next step assumes a database connection string for a local SQL Server authenticated with Windows Integrated Security. Modify it for Azure SQL Edge with a user ID and password if necessary.

  1. At the command line, generate entity class models for all tables, as shown in the following commands:
    dotnet ef dbcontext scaffold "Data Source=.;Initial 
    atalog=Northwind;Integrated Security=true;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer --namespace Northwind.EntityModels --data-annotations
    

Note the following:

  • The command to perform: dbcontext scaffold.
  • The connection string: "Data Source=.;Initial Catalog=Northwind;Integrated Security=true;TrustServerCertificate=True;"
  • The database provider: Microsoft.EntityFrameworkCore.SqlServer
  • The namespace for the generated classes: --namespace Northwind.EntityModels
  • To use data annotations as well as the Fluent API: --data-annotations
  1. Note that 28 classes were generated, from AlphabeticalListOfProduct.cs to Territory.cs.
  2. At the top of the NorthwindContext.cs file, import the namespace for working with ADO.NET types, as shown in the following code:
    using Microsoft.Data.SqlClient; // To use SqlConnectionStringBuilder.
    
  3. Modify the OnConfiguring method to dynamically set the connection string and set any sensitive parameters using environment variables, as shown in the following code:
    protected override void OnConfiguring(
      DbContextOptionsBuilder optionsBuilder)
    {
      // If not already configured by a client project. For example,
      // a client project could use AddNorthwindContext to override
      // the database connection string.
      if (!optionsBuilder.IsConfigured)
      {
        SqlConnectionStringBuilder builder = new();
        builder.DataSource = ".";
        builder.InitialCatalog = "Northwind";
        builder.TrustServerCertificate = true;
        builder.MultipleActiveResultSets = true;
        // If using Azure SQL Edge.
        // builder.DataSource = "tcp:127.0.0.1,1433";
        // Because we want to fail faster. Default is 15 seconds.
        builder.ConnectTimeout = 3;
        // If using Windows Integrated authentication.
        builder.IntegratedSecurity = true;
        // If using SQL Server authentication.
        // builder.UserID = Environment.GetEnvironmentVariable("MY_SQL_USR");
        // builder.Password = Environment.GetEnvironmentVariable("MY_SQL_PWD");
        optionsBuilder.UseSqlServer(builder.ConnectionString);
      }
    }
    
  4. In Customer.cs, the dotnet-ef tool correctly identified that the CustomerId column is the primary key and it is limited to a maximum of five characters, but we also want the values to always be uppercase. So, add a regular expression to validate its primary key value to only allow uppercase Western characters, as shown highlighted in the following code:
    [Key]
    [StringLength(5)]
    [RegularExpression("[A-Z]{5}")] 
    public string CustomerId { get; set; } = null!;
    

Creating a class library for the data context using SQL Server

Next, you will move the context model that represents the database to a separate class library:

  1. Add a new project, as defined in the following list:
    • Project template: Class Library / classlib
    • Project file and folder: Northwind.DataContext
    • Solution file and folder: Chapter01
  2. In the DataContext project, add a project reference to the EntityModels project, and add a package reference to the EF Core data provider for SQL Server, as shown in the following markup:
    <ItemGroup>
      <PackageReference
        Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
    </ItemGroup>
    <ItemGroup>
      <ProjectReference Include=
        "..\Northwind.EntityModels\Northwind.EntityModels.csproj" />
    </ItemGroup>
    

You can try out previews of EF Core 9 by specifying version 9.0-*. The target framework for your project should continue to use net8.0. By using a wildcard, you will automatically download the latest monthly preview when you restore the packages for the project. Once the EF Core 9 GA version is released in November 2024, change the package version to 9.0.0 or later. After February 2025, you will be able to do similar with EF Core 10 (use a package version of 10.0-*) but that will likely require a project targeting net10.0 so you will have to install a preview version of .NET 10 SDK as well.

  1. In the Northwind.DataContext project, delete the Class1.cs file.
  2. Build the Northwind.DataContext project.
  3. Move the NorthwindContext.cs file from the Northwind.EntityModels project/folder to the Northwind.DataContext project/folder.
  4. In the Northwind.DataContext project, add a class named NorthwindContextExtensions.cs, and modify its contents to define an extension method that adds the Northwind database context to a collection of dependency services, as shown in the following code:
    using Microsoft.Data.SqlClient; // SqlConnectionStringBuilder
    using Microsoft.EntityFrameworkCore; // UseSqlServer
    using Microsoft.Extensions.DependencyInjection; // IServiceCollection
    namespace Northwind.EntityModels;
    public static class NorthwindContextExtensions
    {
      /// <summary>
      /// Adds NorthwindContext to the specified IServiceCollection. Uses the SqlServer database provider.
      /// </summary>
      /// <param name="services">The service collection.</param>
      /// <param name="connectionString">Set to override the default.</param>
      /// <returns>An IServiceCollection that can be used to add more services.</returns>
      public static IServiceCollection AddNorthwindContext(
        this IServiceCollection services,
        string? connectionString = null)
      {
        if (connectionString == null)
        {
          SqlConnectionStringBuilder builder = new();
          builder.DataSource = ".";
          builder.InitialCatalog = "Northwind";
          builder.TrustServerCertificate = true;
          builder.MultipleActiveResultSets = true;
          // If using Azure SQL Edge.
          // builder.DataSource = "tcp:127.0.0.1,1433";
          // Because we want to fail fast. Default is 15 seconds.
          builder.ConnectTimeout = 3;
          // If using Windows Integrated authentication.
          builder.IntegratedSecurity = true;
          // If using SQL Server authentication.
          // builder.UserID = Environment.GetEnvironmentVariable("MY_SQL_USR");
          // builder.Password = Environment.GetEnvironmentVariable("MY_SQL_PWD");
          connectionString = builder.ConnectionString;
        }
        services.AddDbContext<NorthwindContext>(options =>
        {
          options.UseSqlServer(connectionString);
          // Log to console when executing EF Core commands.
          options.LogTo(Console.WriteLine,
            new[] { Microsoft.EntityFrameworkCore
              .Diagnostics.RelationalEventId.CommandExecuting });
        },
        // Register with a transient lifetime to avoid concurrency
        // issues with Blazor Server projects.
        contextLifetime: ServiceLifetime.Transient,
        optionsLifetime: ServiceLifetime.Transient);
        return services;
      }
    }
    
  5. Build the two class libraries and fix any compiler errors.

Good Practice

We have provided an optional argument for the AddNorthwindContext method so that we can override the SQL Server database connection string. This will allow us more flexibility, for example, to load these values from a configuration file.

Creating a test project to check the integration of the class libraries

Since we will not be creating a client project in this chapter that uses the EF Core model, we should create a test project to make sure the database context and entity models integrate correctly:

  1. Use your preferred code editor to add a new xUnit Test Project [C#] / xunit project named Northwind.Tests to the Chapter01 solution.
  2. In Northwind.Tests.csproj, modify the configuration to treat warnings as errors and add an item group with a project reference to the Northwind.DataContext project, as shown in the following markup:
    <ItemGroup>
      <ProjectReference Include=
        "..\Northwind.DataContext\Northwind.DataContext.csproj" />
    </ItemGroup>
    

Warning!

The path to the project reference should not have a line break in your project file.

  1. Build the Northwind.Tests project to build and restore project dependencies.
  2. Rename the file UnitTest1.cs to NorthwindEntityModelsTests.cs (Visual Studio prompts you to rename the class when you rename the file).
  3. In NorthwindEntityModelsTests.cs, if you are using Code, then manually rename the class to NorthwindEntityModelsTests.
  4. In NorthwindEntityModelsTests.cs, modify the class to import the Northwind.EntityModels namespace and have some test methods for ensuring that the context class can connect, the provider is SQL Server, and the first product is named Chai, as shown in the following code:
    using Northwind.EntityModels; // To use NorthwindContext and Product.
    namespace Northwind.Tests;
    public class NorthwindEntityModelsTests
    {
      [Fact]
      public void CanConnectIsTrue()
      {
        using (NorthwindContext db = new()) // arrange
        {
          bool canConnect = db.Database.CanConnect(); // act
          Assert.True(canConnect); // assert
        }
      }
      [Fact]
      public void ProviderIsSqlServer()
      {
        using (NorthwindContext db = new())
        {
          string? provider = db.Database.ProviderName;
          Assert.Equal("Microsoft.EntityFrameworkCore.SqlServer", provider);
        }
      }
      [Fact]
      public void ProductId1IsChai()
      {
        using (NorthwindContext db = new())
        {
          Product? product1 = db?.Products?.Single(p => p.ProductId == 1);
          Assert.Equal("Chai", product1?.ProductName);
        }
      }
    }
    

Running tests

Now we are ready to run the tests and see the results using either Visual Studio or Code.

Using Visual Studio:

  1. In Visual Studio, in Solution Explorer, right-click the Northwind.Tests project, and then select Run Tests.
  2. In Test Explorer, note that the results indicate that three tests ran, and all passed, as shown in Figure 1.3:

Figure 1.3: All the tests passed

Using Code:

  1. In Code, in the Northwind.Tests project’s TERMINAL window, run the tests, as shown in the following command:
    dotnet test
    

If you are using C# Dev Kit, then you can also build the test project and then run the tests from the Testing section in the Primary Side Bar.

  1. In the output, note that the results indicate that three tests ran, and all passed.

Using .NET 9 with this book

Microsoft will release .NET 9 at the .NET Conf 2024 on Tuesday, November 12, 2024, one week after the US Presidential election on November 5. Many readers will want to use this book with .NET 9, so this section explains how.

At the time of publishing in July 2024, .NET 9 is already available in preview, or you can wait for the final version in November 2024. But beware because once you install a .NET 9 SDK, then it will be used by default for all .NET projects unless you override it using a global.json file. You can learn more about doing this at the following link: https://learn.microsoft.com/en-us/dotnet/core/tools/global-json.

You can easily continue to target the .NET 8 runtime while installing and using future C# compilers, as shown in Figure 1.4 and illustrated in the following list:

  1. November 2023 onwards: Install .NET SDK 8.0.100 or later and use it to build projects that target .NET 8 and use the C# 12 compiler by default. Every month, update to .NET 8 SDK patches on the development computer and update to .NET 8 runtime patches on any deployment computers.
  2. February to October 2024: Optionally, install .NET SDK 9 previews each month to explore the new C# language and .NET library features. Note that you won’t be able to use new library features while targeting .NET 8. Read the monthly announcement posts to find out about the new features in that preview, found at the following link: https://github.com/dotnet/core/discussions/9234.
  3. November 2024 onwards: Install .NET SDK 9.0.100 or later and use it to build projects that continue to target .NET 8 and use the C# 13 compiler for its new features. You will be using a fully supported SDK and fully supported runtime. You can also use new features in EF Core 9 because it will continue to target .NET 8.
  4. February to October 2025: Optionally, install .NET 10 previews to explore new C# language and .NET library features. Start planning if any new library and ASP.NET Core features in .NET 9 and .NET 10 can be applied to your .NET 8 projects when you are ready to migrate.
  5. November 2025 onwards: Install .NET 10.0.100 SDK or later and use it to build projects that target .NET 8 and use the C# 14 compiler. You could migrate your .NET 8 projects to .NET 10 since it is a long-term support (LTS) release. You have until November 2026 to complete the migration when .NET 8 reaches end-of-life.
A screenshot of a computer program

Description automatically generated

Figure 1.4: Targeting .NET 8 for long-term support while using the latest C# compilers

When deciding to install a .NET SDK, remember that the latest is used by default to build any .NET projects. Once you’ve installed a .NET 9 SDK preview, it will be used by default for all projects, unless you force the use of an older, fully supported SDK version like 8.0.100 or a later patch.

To gain the benefits of whatever new features are available in C# 13, while still targeting .NET 8 for long-term support, modify your project file, as shown highlighted in the following markup:

<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <LangVersion>13</LangVersion> <!--Requires .NET 9 SDK GA-->
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Good Practice

Use a general availability (GA) SDK release like .NET 9 to use new compiler features while still targeting older but longer supported versions of .NET like .NET 8.

Practicing and exploring

Test your knowledge and understanding by answering some questions, getting some hands-on practice, and exploring with deeper research the topics in this chapter.

Exercise 1.1 – Online-only material

Make sure that you are ready to use multiple code editors. Chapter 1 of the C# 12 and .NET 8 - Modern Cross-Platform Development Fundamentals book has online sections showing how to get started with multiple projects using various code editors including Visual Studio, Code, or Rider.

You can read the sections at the following link: https://github.com/markjprice/cs12dotnet8/blob/main/docs/code-editors/README.md.

Exercise 1.2 – Practice exercises

If you do not yet have an OpenAI ChatGPT account, sign up for one and try asking it some questions: https://chat.openai.com/.

Exercise 1.3 – Test your knowledge

To get the best answer to some of these questions, you will need to do your own research. I want you to “think outside the book,” so I have deliberately not provided all the answers in the book.

I want to encourage you to get into the good habit of looking for help elsewhere, following the principle of “teach a person to fish.”

  1. How are .NET developers who choose to use Rider perceived compared to developers who have only ever used Visual Studio?
  2. What is a key phrase to use when prompt engineering ChatGPT?
  3. When you ask a question in a forum or Discord channel, what should you keep in mind?
  4. After its release in November 2024, you download and install .NET 9 SDK. How can you configure your projects to continue to target .NET 8 for long-term support and also enjoy the benefits of the C# 13 compiler?
  5. What is the GitHub repository for this book used for?

Appendix, Answers to the Test Your Knowledge Questions, is available to download from the following link: https://packt.link/isUsj.

Exercise 1.4 – Explore topics

Use the links on the following page to learn more about the topics covered in this chapter: https://github.com/markjprice/tools-skills-net8/blob/main/docs/book-links.md#chapter-1---introducing-tools-and-skills-for-net.

Summary

In this chapter:

  • You were introduced to the tools and skills that you will learn about in this book
  • You set up your development environment
  • You learned where to get help and how to get the best help from AI tools like ChatGPT
  • You set up a sample database named Northwind for SQL Server, and some .NET projects to define an EF Core model with tests for use in later chapters

In the next chapter, you will learn how to make the most of the tools in your code editor or IDE.

Join our book’s Discord space

Read this book alongside other users, and the author himself.

Ask questions, provide solutions for other readers, chat with the author via Ask Me Anything sessions, and much more.

https://packt.link/TS1e

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Coverage of key .NET tools and skills including refactoring, source code management, debugging, memory troubleshooting, and more
  • Practical guidance on using code editors effectively, implementing best practices, and protecting data
  • Explore cutting-edge techniques like building intelligent apps, cloud native development with .NET Aspire, and Docker containerization

Description

Unlock the full potential of .NET development with Tools and Skills for .NET 8. Dive into source code management using Git and learn how to navigate projects while ensuring version control. Discover advanced debugging techniques and troubleshooting strategies to identify and resolve issues, and gain practical insights on documenting your code, APIs, and services, fostering project clarity and maintainability. Delve into the world of cryptography, ensuring confidentiality and integrity throughout your development lifecycle. Elevate your skills as you explore cutting-edge topics such as building intelligent apps using custom LLM-based chat services, mastering dependency injection, optimizing performance through testing, and Docker containerization. Harness the power of cloud-native development with .NET Aspire, unlocking the benefits of modern cloud platforms. With guidance on software architecture best practices, this book empowers you to build robust, scalable and maintainable applications. Advance your career with invaluable insights on job readiness and interview preparation, positioning yourself as a top-tier candidate in today's competitive job market. Whether you're a seasoned .NET professional or an aspiring developer looking to enhance your skills, this book is your ultimate companion on the journey to .NET mastery.

What you will learn

  • Make the most of code editor tools for efficient development
  • Learn advanced debugging techniques and troubleshooting strategies
  • Understand how to protect data and applications using cryptography
  • Build a custom LLM-based chat service
  • Discover how to master dependency injection
  • Optimize performance through benchmarking and testing
  • Delve into cloud-native development using .NET Aspire
  • Advance your career with advice on job readiness and interviews

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 30, 2024
Length 778 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781837635207
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Jul 30, 2024
Length 778 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781837635207
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Table of Contents

22 Chapters
Preface Chevron down icon Chevron up icon
1. Introducing Tools and Skills for .NET Chevron down icon Chevron up icon
2. Making the Most of the Tools in Your Code Editor Chevron down icon Chevron up icon
3. Source Code Management Using Git Chevron down icon Chevron up icon
4. Debugging and Memory Troubleshooting Chevron down icon Chevron up icon
5. Logging, Tracing, and Metrics for Observability Chevron down icon Chevron up icon
6. Documenting Your Code, APIs, and Services Chevron down icon Chevron up icon
7. Observing and Modifying Code Execution Dynamically Chevron down icon Chevron up icon
8. Protecting Data and Apps Using Cryptography Chevron down icon Chevron up icon
9. Building an LLM-Based Chat Service Chevron down icon Chevron up icon
10. Dependency Injection, Containers, and Service Lifetime Chevron down icon Chevron up icon
11. Unit Testing and Mocking Chevron down icon Chevron up icon
12. Integration and Security Testing Chevron down icon Chevron up icon
13. Benchmarking Performance, Load, and Stress Testing Chevron down icon Chevron up icon
14. Functional and End-to-End Testing of Websites and Services Chevron down icon Chevron up icon
15. Containerization Using Docker Chevron down icon Chevron up icon
16. Cloud-Native Development Using .NET Aspire Chevron down icon Chevron up icon
17. Design Patterns and Principles Chevron down icon Chevron up icon
18. Software and Solution Architecture Foundations Chevron down icon Chevron up icon
19. Your Career, Teamwork, and Interviews Chevron down icon Chevron up icon
20. Epilogue Chevron down icon Chevron up icon
21. Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.