An accessible guide for beginner-to-intermediate programmers to concepts, real-world applications, and latest features of C# 11 and .NET 7, with hands-on exercises using Visual Studio 2022 and Visual Studio Code
Key FeaturesExplore the newest additions to C# 11, the .NET 7 class libraries, and Entity Framework Core 7Create professional websites and services with ASP.NET Core 7 and BlazorBuild your confidence with step-by-step code examples and tips for best practicesBook Description
Extensively revised to accommodate the latest features that come with C# 11 and .NET 7, this latest edition of our guide will get you coding in C# with confidence.
You’ll learn object-oriented programming, writing, testing, and debugging functions, implementing interfaces, and inheriting classes. Next, you’ll take on .NET APIs for performing tasks like managing and querying data, working with the filesystem, and serialization. As you progress, you’ll also explore examples of cross-platform projects you can build and deploy, such as websites and services using ASP.NET Core.
Instead of distracting you with unnecessary graphical user interface code, the first eleven chapters will teach you about C# language constructs and many of the .NET libraries through simple console applications. In later chapters, having mastered the basics, you’ll then build websites, web services, and browser apps using ASP.NET Core, the Model-View-Controller (MVC) pattern, and Blazor.
C# 11 and .NET 7 - Modern Cross-Platform Development Fundamentals will give you a solid foundation to start building apps and services with confidence. By the end of this book, you’ll be able to create rich web experiences and have a solid grasp on object-oriented programming that you can build upon.
What you will learnBuild rich web experiences using Blazor, Razor Pages, the Model-View-Controller (MVC) pattern, and other features of ASP.NET CoreBuild your own types with object-oriented programmingWrite, test, and debug functionsQuery and manipulate data using LINQIntegrate and update databases in your apps using Entity Framework Core modelsBuild and consume powerful services using the latest technologies, including Web API and Minimal APIWho This Book Is For
This book is primarily for beginners, but intermediate-level C# and .NET programmers who have worked with C# in the past and want to catch up with the changes made in the past few years will also find plenty of useful information in it. Prior exposure to C# or .NET is not a prerequisite, but you should have a general understanding of programming before you jump in.
If you already have some C# and .NET skills and want to focus on developing apps, we recommend that you pick up Mark’s other .NET book, Apps and Services with .NET 7, instead.
Table of ContentsHello C#, Welcome .NET!Speaking C#Controlling Flow, Converting Types, and Handling ExceptionsWriting, Debugging, and Testing FunctionsBuilding Your Own Types with Object-Oriented ProgrammingImplementing Interfaces and Inheriting ClassesPackaging and Distributing .NET TypesWorking with Common .NET TypesWorking with Files, Streams, and SerializationWorking with Data Using Entity Framework CoreQuerying and Manipulating Data Using LINQIntroducing Web Development Using ASP.NET CoreBuilding Websites Using ASP.NET Core Razor PagesBuilding Websites Using the Model-View-Controller PatternBuilding and Consuming Web ServicesBuilding User Interface Components Using Blazor
Author(s): Mark J. Price
Edition: 7
Publisher: packt
Year: 2022
C# 11 and .NET 7 – Modern Cross-Platform Development Fundamentals, Seventh Edition: Start building websites and services with ASP.NET Core 7, Blazor, and EF Core 7
1 Hello, C#! Welcome, .NET!
Join our book community on Discord
Setting up your development environment
Choosing the appropriate tool and application type for learning
Deploying cross-platform
Downloading and installing Visual Studio 2022 for Windows
Downloading and installing Visual Studio Code
Understanding .NET
Understanding .NET Framework
Understanding the Mono, Xamarin, and Unity projects
Understanding .NET Core
Understanding the journey to one .NET
Understanding .NET support
What is different about modern .NET?
Understanding .NET Standard
.NET platforms and tools used by the C# and .NET book editions
Topics covered by Apps and Services with .NET 7
Understanding intermediate language
Comparing .NET technologies
Building console apps using Visual Studio 2022
Managing multiple projects using Visual Studio 2022
Writing code using Visual Studio 2022
Compiling and running code using Visual Studio
Understanding top-level programs
Adding a second project using Visual Studio 2022
Building console apps using Visual Studio Code
Managing multiple projects using Visual Studio Code
Writing code using Visual Studio Code
Compiling and running code using the dotnet CLI
Adding a second project using Visual Studio Code
Exploring code using .NET Interactive Notebooks
Creating a notebook
Writing and running code in a notebook
Saving a notebook
Adding Markdown and special commands to a notebook
Executing code in multiple cells
Using .NET Interactive Notebooks for the code in this book
Reviewing the folders and files for projects
Understanding the common folders and files
Understanding the solution code on GitHub
Making good use of the GitHub repository for this book
Raising issues with the book
Giving me feedback
Downloading solution code from the GitHub repository
Using Git with Visual Studio Code and the command line
Looking for help
Reading Microsoft documentation
Getting help for the dotnet tool
Getting definitions of types and their members
Looking for answers on Stack Overflow
Searching for answers using Google
Subscribing to the official .NET blog
Watching Scott Hanselman's videos
A companion book to continue your learning journey
Practicing and exploring
Exercise 1.1 – Test your knowledge
Exercise 1.2 – Practice C# anywhere with a browser
Exercise 1.3 – Explore topics
Exercise 1.4 – Explore themes of modern .NET
Summary
02 Speaking C#
Join our book community on Discord
Introducing the C# language
Understanding language versions and features
Understanding C# standards
Discovering your C# compiler versions
Understanding C# grammar and vocabulary
Showing the compiler version
Understanding C# grammar
Statements
Comments
Blocks
Examples of statements and blocks
Understanding C# vocabulary
Comparing programming languages to human languages
Changing the color scheme for C# syntax
Help for writing correct code
Importing namespaces
Verbs are methods
Nouns are types, variables, fields, and properties
Revealing the extent of the C# vocabulary
Working with variables
Naming things and assigning values
Literal values
Storing text
Storing numbers
Storing real numbers
Storing Booleans
Storing any type of object
Storing dynamic types
Declaring local variables
Getting and setting the default values for types
Exploring more about console apps
Displaying output to the user
Getting text input from the user
Simplifying the usage of the console
Getting key input from the user
Passing arguments to a console app
Setting options with arguments
Handling platforms that do not support an API
Understanding async and await
Improving responsiveness for console apps
Practicing and exploring
Exercise 2.1 – Test your knowledge
Exercise 2.2 – Test your knowledge of number types
Exercise 2.3 – Practice number sizes and ranges
Exercise 2.4 – Explore topics
Summary
3 Controlling Flow, Converting Types, and Handling Exceptions
Join our book community on Discord
Operating on variables
Exploring unary operators
Exploring binary arithmetic operators
Assignment operators
Exploring logical operators
Exploring conditional logical operators
Exploring bitwise and binary shift operators
Miscellaneous operators
Understanding selection statements
Branching with the if statement
Pattern matching with the if statement
Branching with the switch statement
Pattern matching with the switch statement
Simplifying switch statements with switch expressions
Understanding iteration statements
Looping with the while statement
Looping with the do statement
Looping with the for statement
Looping with the foreach statement
Storing multiple values in an array
Working with single-dimensional arrays
Working with multi-dimensional arrays
Working with jagged arrays
Summarizing arrays
Casting and converting between types
Casting numbers implicitly and explicitly
Converting with the System.Convert type
Rounding numbers
Taking control of rounding rules
Converting from any type to a string
Converting from a binary object to a string
Parsing from strings to numbers or dates and times
Handling exceptions
Wrapping error-prone code in a try block
Checking for overflow
Throwing overflow exceptions with the checked statement
Disabling compiler overflow checks with the unchecked statement
Practicing and exploring
Exercise 3.1 – Test your knowledge
Exercise 3.2 – Explore loops and overflow
Exercise 3.3 – Practice loops and operators
Exercise 3.4 – Practice exception handling
Exercise 3.5 – Test your knowledge of operators
Exercise 3.6 – Explore topics
Summary
4 Writing, Debugging, and Testing Functions
Join our book community on Discord
Writing functions
Understanding top-level programs and functions
Times table example
Writing a function that returns a value
Converting numbers from cardinal to ordinal
Calculating factorials with recursion
Documenting functions with XML comments
Using lambdas in function implementations
Debugging during development
Using Visual Studio Code integrated terminal during debugging
Creating code with a deliberate bug
Setting a breakpoint and start debugging
Navigating with the debugging toolbar
Debugging windows
Stepping through code
Customizing breakpoints
Hot reloading during development
Hot reloading using Visual Studio 2022
Hot reloading using Visual Studio Code and the command line
Logging during development and runtime
Understanding logging options
Instrumenting with Debug and Trace
Configuring trace listeners
Switching trace levels
Unit testing
Understanding types of testing
Creating a class library that needs testing
Writing unit tests
Throwing and catching exceptions in functions
Understanding usage errors and execution errors
Commonly thrown exceptions in functions
Understanding the call stack
Where to catch exceptions
Rethrowing exceptions
Implementing the tester-doer pattern
Practicing and exploring
Exercise 4.1 – Test your knowledge
Exercise 4.2 – Practice writing functions with debugging and unit testing
Exercise 4.3 – Explore topics
Summary
5 Building Your Own Types with Object-Oriented Programming
Join our book community on Discord
Talking about OOP
Building class libraries
Creating a class library
Defining a class in a namespace
Understanding members
Instantiating a class
Importing a namespace to use a type
Understanding objects
Storing data within fields
Defining fields
Understanding access modifiers
Setting and outputting field values
Storing a value using an enum type
Storing multiple values using an enum type
Storing multiple values using collections
Understanding generic collections
Making a field static
Making a field constant
Making a field read-only
Initializing fields with constructors
Writing and calling methods
Returning values from methods
Combining multiple returned values using tuples
Defining and passing parameters to methods
Overloading methods
Passing optional and named parameters
Controlling how parameters are passed
Understanding ref returns
Splitting classes using partial
Controlling access with properties and indexers
Defining read-only properties
Defining settable properties
Accessing the autogenerated private field
Requiring properties to be set during instantiation
Defining indexers
More about methods
Implementing functionality using methods
Implementing functionality using operators
Implementing functionality using local functions
Pattern matching with objects
Defining flight passengers
Enhancements to pattern matching in C# 9 or later
Working with records
Init-only properties
Understanding records
Positional data members in records
Practicing and exploring
Exercise 5.1 – Test your knowledge
Exercise 5.2 – Explore topics
Summary
6 Implementing Interfaces and Inheriting Classes
Join our book community on Discord
Setting up a class library and console application
Making types safely reusable with generics
Working with non-generic types
Working with generic types
Raising and handling events
Calling methods using delegates
Defining and handling delegates
Defining and handling events
Implementing interfaces
Common interfaces
Comparing objects when sorting
Comparing objects using a separate class
Implicit and explicit interface implementations
Defining interfaces with default implementations
Managing memory with reference and value types
Defining reference and value types
How reference and value types are stored in memory
Equality of types
Defining struct types
Defining record struct types
Releasing unmanaged resources
Ensuring that Dispose is called
Working with null values
Making a value type nullable
Understanding null-related initialisms
Understanding nullable reference types
Controlling the nullability warning check feature
Declaring non-nullable variables and parameters
Checking for null
Inheriting from classes
Extending classes to add functionality
Hiding members
Overriding members
Inheriting from abstract classes
Preventing inheritance and overriding
Understanding polymorphism
Casting within inheritance hierarchies
Implicit casting
Explicit casting
Avoiding casting exceptions
Inheriting and extending .NET types
Inheriting exceptions
Extending types when you can't inherit
Using an analyzer to write better code
Suppressing warnings
Fixing the code
Understanding common StyleCop recommendations
Practicing and exploring
Exercise 6.1 – Test your knowledge
Exercise 6.2 – Practice creating an inheritance hierarchy
Exercise 6.3 – Explore topics
Summary
7 Packaging and Distributing .NET Types
Join our book community on Discord
The road to .NET 7
.NET Core 1.0
.NET Core 1.1
.NET Core 2.0
.NET Core 2.1
.NET Core 2.2
.NET Core 3.0
.NET Core 3.1
.NET 5.0
.NET 6.0
.NET 7.0
Improving performance from .NET Core 2.0 to .NET 5 and later
Checking your .NET SDKs for updates
Understanding .NET components
Understanding assemblies, NuGet packages, and namespaces
Understanding the Microsoft .NET project SDKs
Understanding namespaces and types in assemblies
Understanding NuGet packages
Understanding frameworks
Importing a namespace to use a type
Relating C# keywords to .NET types
Sharing code with legacy platforms using .NET Standard
Understanding defaults for class libraries with different SDKs
Creating a .NET Standard 2.0 class library
Controlling the .NET SDK
Publishing your code for deployment
Creating a console app to publish
Understanding dotnet commands
Getting information about .NET and its environment
Managing projects
Publishing a self-contained app
Publishing a single-file app
Reducing the size of apps using app trimming
Decompiling .NET assemblies
Decompiling using the ILSpy extension for Visual Studio 2022
No, you cannot technically prevent decompilation
Packaging your libraries for NuGet distribution
Referencing a NuGet package
Packaging a library for NuGet
Exploring NuGet packages with a tool
Testing your class library package
Porting from .NET Framework to modern .NET
Could you port?
Should you port?
Differences between .NET Framework and modern .NET
Understanding the .NET Portability Analyzer
Understanding the .NET Upgrade Assistant
Using non-.NET Standard libraries
Working with preview features
Requiring preview features
Enabling preview features
Generic mathematics
Practicing and exploring
Exercise 7.1 – Test your knowledge
Exercise 7.2 – Explore topics
Exercise 7.3 – Explore PowerShell
Summary
8 Working with Common .NET Types
Join our book community on Discord
Working with numbers
Working with big integers
Working with complex numbers
Understanding quaternions
Generating random numbers for games and similar apps
Working with text
Getting the length of a string
Getting the characters of a string
Splitting a string
Getting part of a string
Checking a string for content
Joining, formatting, and other string members
Building strings efficiently
Pattern matching with regular expressions
Checking for digits entered as text
Regular expression performance improvements
Understanding the syntax of a regular expression
Examples of regular expressions
Splitting a complex comma-separated string
Storing multiple objects in collections
Common features of all collections
Improving performance by ensuring the capacity of a collection
Understanding collection choices
Working with lists
Working with dictionaries
Working with queues
Sorting collections
More specialized collections
Working with immutable collections
Good practice with collections
Working with spans, indexes, and ranges
Using memory efficiently using spans
Identifying positions with the Index type
Identifying ranges with the Range type
Using indexes, ranges, and spans
Working with network resources
Working with URIs, DNS, and IP addresses
Pinging a server
Practicing and exploring
Exercise 8.1 – Test your knowledge
Exercise 8.2 – Practice regular expressions
Exercise 8.3 – Practice writing extension methods
Exercise 8.4 – Explore topics
Summary
9 Working with Files, Streams, and Serialization
Join our book community on Discord
Managing the filesystem
Handling cross-platform environments and filesystems
Managing drives
Managing directories
Managing files
Managing paths
Getting file information
Controlling how you work with files
Reading and writing with streams
Understanding abstract and concrete streams
Writing to text streams
Writing to XML streams
Simplifying disposal by using the using statement
Compressing streams
Encoding and decoding text
Encoding strings as byte arrays
Encoding and decoding text in files
Reading and writing with random access handles
Serializing object graphs
Serializing as XML
Generating compact XML
Deserializing XML files
Serializing with JSON
High-performance JSON processing
Controlling JSON processing
New JSON extension methods for working with HTTP responses
Migrating from Newtonsoft to new JSON
Practicing and exploring
Exercise 9.1 – Test your knowledge
Exercise 9.2 – Practice serializing as XML
Exercise 9.3 – Explore topics
Summary
10 Working with Data Using Entity Framework Core
Join our book community on Discord
Understanding modern databases
Understanding legacy Entity Framework
Understanding Entity Framework Core
Creating a console app for working with EF Core
Using a sample relational database
Using SQLite
Creating the Northwind sample database for SQLite
Managing the Northwind sample database with SQLiteStudio
Using the lightweight ADO.NET provider for SQLite
Using Microsoft SQL Server for Windows
Setting up EF Core
Choosing an EF Core database provider
Connecting to a database
Defining the Northwind database context class
Defining EF Core models
Using EF Core conventions to define the model
Using EF Core annotation attributes to define the model
Using the EF Core Fluent API to define the model
Building EF Core models for the Northwind tables
Adding tables to the Northwind database context class
Setting up the dotnet-ef tool
Scaffolding models using an existing database
Configuring preconvention models
Querying EF Core models
Filtering included entities
Filtering and sorting products
Getting the generated SQL
Logging EF Core
Pattern matching with Like
Generating a random number in queries
Defining global filters
Loading patterns with EF Core
Eager loading entities
Enabling lazy loading
Explicit loading entities
Manipulating data with EF Core
Inserting entities
Updating entities
Deleting entities
Pooling database contexts
Working with transactions
Controlling transactions using isolation levels
Defining an explicit transaction
Code First EF Core models
Understanding migrations
Practicing and exploring
Exercise 10.1 – Test your knowledge
Exercise 10.2 – Practice exporting data using different serialization formats
Exercise 10.3 – Explore topics
Exercise 10.4 – Explore NoSQL databases
Summary
11 Querying and Manipulating Data Using LINQ
Join our book community on Discord
Writing LINQ expressions
What makes LINQ?
Building LINQ expressions with the Enumerable class
Filtering entities with Where
Targeting a named method
Simplifying the code by removing the explicit delegate instantiation
Targeting a lambda expression
Sorting entities
Declaring a query using var or a specified type
Filtering by type
Working with sets and bags using LINQ
Using LINQ with EF Core
Building an EF Core model
Filtering and sorting sequences
Projecting sequences into new types
Joining and grouping sequences
Aggregating sequences
Sweetening LINQ syntax with syntactic sugar
Using multiple threads with parallel LINQ
Creating an app that benefits from multiple threads
Creating your own LINQ extension methods
Working with LINQ to XML
Generating XML using LINQ to XML
Reading XML using LINQ to XML
Practicing and exploring
Exercise 11.1 – Test your knowledge
Exercise 11.2 – Practice querying with LINQ
Exercise 11.3 – Explore topics
Summary
12 Introducing Web Development Using ASP.NET Core
Join our book community on Discord
Understanding ASP.NET Core
Classic ASP.NET versus modern ASP.NET Core
Building websites using ASP.NET Core
Building web and other services
New features in ASP.NET Core
ASP.NET Core 1.0
ASP.NET Core 1.1
ASP.NET Core 2.0
ASP.NET Core 2.1
ASP.NET Core 2.2
ASP.NET Core 3.0
ASP.NET Core 3.1
Blazor WebAssembly 3.2
ASP.NET Core 5.0
ASP.NET Core 6.0
ASP.NET Core 7.0
Structuring projects
Structuring projects in a solution or workspace
Building an entity data model for the Northwind database
Creating a class library for entity models using SQLite
Creating a class library for entity models using SQL Server
Understanding web development
Understanding Hypertext Transfer Protocol
Using Google Chrome to make HTTP requests
Understanding client-side web development technologies
Practicing and exploring
Exercise 12.1 – Explore topics
Summary
13 Building Websites Using ASP.NET Core Razor Pages
Join our book community on Discord
Exploring ASP.NET Core
Creating an empty ASP.NET Core project
Testing and securing the website
Controlling the hosting environment
Enabling a website to serve static content
Exploring ASP.NET Core Razor Pages
Enabling Razor Pages
Adding code to a Razor Page
Using shared layouts with Razor Pages
Using code-behind files with Razor Pages
Using Entity Framework Core with ASP.NET Core
Configure Entity Framework Core as a service
Manipulating data using Razor Pages
Injecting a dependency service into a Razor Page
Using Razor class libraries
Disabling compact folders for Visual Studio Code
Creating a Razor class library
Implementing a partial view to show a single employee
Using and testing a Razor class library
Configuring services and the HTTP request pipeline
Understanding endpoint routing
Configuring endpoint routing
Reviewing the endpoint routing configuration in our project
Setting up the HTTP pipeline
Summarizing key middleware extension methods
Visualizing the HTTP pipeline
Implementing an anonymous inline delegate as middleware
Enabling HTTP/3 support
Practicing and exploring
Exercise 13.1 – Test your knowledge
Exercise 13.2 – Practice building a data-driven web page
Exercise 13.3 – Practice building web pages for console apps
Exercise 13.4 – Explore topics
Summary
14 Building Websites Using the Model-View-Controller Pattern
Join our book community on Discord
Setting up an ASP.NET Core MVC website
Creating an ASP.NET Core MVC website
Creating the authentication database for SQL Server LocalDB
Exploring the default ASP.NET Core MVC website
Understanding visitor registration
Reviewing an MVC website project structure
Reviewing the ASP.NET Core Identity database
Exploring an ASP.NET Core MVC website
Understanding ASP.NET Core MVC initialization
Understanding the default MVC route
Understanding controllers and actions
Understanding the view search path convention
Understanding logging
Understanding filters
Understanding entity and view models
Understanding views
Customizing an ASP.NET Core MVC website
Defining a custom style
Setting up the category images
Understanding Razor syntax and expressions
Defining a typed view
Passing parameters using a route value
Understanding model binders in more detail
Validating the model
Understanding view helper methods
Querying a database and using display templates
Improving scalability using asynchronous tasks
Making controller action methods asynchronous
Practicing and exploring
Exercise 14.1 – Test your knowledge
Exercise 14.2 – Practice implementing MVC by implementing a category detail page
Exercise 14.3 – Practice improving scalability by understanding and implementing async action methods
Exercise 14.4 – Practice unit testing MVC controllers
Exercise 14.5 – Explore topics
Summary
15 Building and Consuming Web Services
Join our book community on Discord
Building web services using ASP.NET Core Web API
Understanding web service acronyms
Understanding HTTP requests and responses for Web APIs
Creating an ASP.NET Core Web API project
Reviewing the web service's functionality
Creating a web service for the Northwind database
Creating data repositories for entities
Implementing a Web API controller
Configuring the customer repository and Web API controller
Specifying problem details
Controlling XML serialization
Documenting and testing web services
Testing GET requests using a browser
Testing HTTP requests with the REST Client extension
Understanding Swagger
Testing requests with Swagger UI
Consuming web services using HTTP clients
Understanding HttpClient
Configuring HTTP clients using HttpClientFactory
Getting customers as JSON in the controller
Implementing advanced features for web services
Implementing a Health Check API
Implementing Open API analyzers and conventions
Implementing transient fault handling
Adding security HTTP headers
Enabling HTTP/3 support for HttpClient
Building web services using minimal APIs
Testing the minimal weather service
Adding weather forecasts to the Northwind website home page
Practicing and exploring
Exercise 15.1 – Test your knowledge
Exercise 15.2 – Practice creating and deleting customers with HttpClient
Exercise 15.3 – Explore topics
Summary
16 Building User Interfaces Using Blazor
Join our book community on Discord
Understanding Blazor
JavaScript and friends
Silverlight – C# and .NET using a plugin
WebAssembly – a target for Blazor
Understanding Blazor hosting models
Understanding Blazor components
What is the difference between Blazor and Razor?
Comparing Blazor project templates
Reviewing the Blazor Server project template
Understanding Blazor routing to page components
Running the Blazor Server project template
Reviewing the Blazor WebAssembly project template
Building components using Blazor Server
Defining and testing a simple Blazor Server component
Making the component a routable page component
Getting entities into a component
Abstracting a service for a Blazor component
Defining forms using the EditForm component
Building a shared customer detail component
Building customer create, edit, and delete components
Testing the customer components
Building components using Blazor WebAssembly
Configuring the server for Blazor WebAssembly
Configuring the client for Blazor WebAssembly
Testing the Blazor WebAssembly components and service
Improving Blazor WebAssembly apps
Enabling Blazor WebAssembly AOT
Exploring Progressive Web App support
Understanding the browser compatibility analyzer for Blazor WebAssembly
Interop with JavaScript
Libraries of Blazor components
Practicing and exploring
Exercise 16.1 – Test your knowledge
Exercise 16.2 – Practice by creating a times table component
Exercise 16.3 – Practice by creating a country navigation item
Exercise 16.4 – Explore topics
Summary
Copyright
Title Page
Dedication
Contents
Chapter 1: ‘I’m thinking’ – Oh, but are you?
Chapter 2: Renegade perception
Chapter 3: The Pushbacker sting
Chapter 4: ‘Covid’: The calculated catastrophe
Chapter 5: There is no ‘virus’
Chapter 6: Sequence of deceit
Chapter 7: War on your mind
Chapter 8: ‘Reframing’ insanity
Chapter 9: We must have it? So what is it?
Chapter 10: Human 2.0
Chapter 11: Who controls the Cult?
Chapter 12: Escaping Wetiko
Postscript
Appendix: Cowan-Kaufman-Morell Statement on Virus Isolation
Bibliography
Index