C# 11 and .NET 7 – Modern Cross-Platform Development Fundamentals - Mark J. Price - E-Book

C# 11 and .NET 7 – Modern Cross-Platform Development Fundamentals E-Book

Mark J. Price

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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. Having mastered the basics, you’ll then start building websites, web services, and browser apps.

By the end of this book, you’ll be able to create rich web experiences and have a solid grasp of object-oriented programming that you can build upon.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 1098

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



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

Mark J. Price

BIRMINGHAM—MUMBAI

C# 11 and .NET 7 – Modern Cross-Platform Development Fundamentals

Seventh Edition

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Senior Publishing Product Manager: Suman Sen

Acquisition Editor – Peer Reviews: Saby Dsilva

Project Editor: Janice Gonsalves

Content Development Editor: Lucy Wan

Copy Editor: Safis Editing

Technical Editor: Tejas Mhasvekar

Proofreader: Safis Editing

Indexer: Tejal Daruwale Soni

Presentation Designer: Pranit Padwal

First published: March 2016

Second edition: March 2017

Third edition: November 2017

Fourth edition: October 2019

Fifth edition: November 2020

Sixth edition: November 2021

Seventh edition: November 2022

Production reference: 3110423

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-780-0

www.packt.com

Contributors

About the author

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years of experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught “train-the-trainer” classes to get Microsoft Certified Trainers up-to-speed on C# and .NET. Mark has spent most of his career training a wide variety of students from 16-year-old apprentices to 70-year-old retirees, with the majority being professional developers. Mark holds a Computer Science BSc. Hons. degree.

About the reviewer

Dave Brock is a development lead with experience in the architecture, design, and development of distributed, cloud-native applications. He was awarded a master’s degree in software engineering from DePaul University. With a focus on Microsoft technologies such as .NET and Azure, Dave writes at daveabrock.com and has been awarded the Microsoft MVP award twice for his community contributions. He resides in Madison, Wisconsin, and, when not reviewing books, enjoys running, hiking, and playing music, and, of course, is a proud dad to his two wonderful children, Emma and Colin.

Join our book’s Discord space

Join the book’s Discord workspace for Ask me Anything sessions with the author.

https://packt.link/csharp11dotnet7

Quick Chapter Reference

Hello, C#! Welcome, .NET! 1Speaking C# 45Controlling Flow, Converting Types, and Handling Exceptions 99Writing, Debugging, and Testing Functions 145Building Your Own Types with Object-Oriented Programming 199Implementing Interfaces and Inheriting Classes 249Packaging and Distributing .NET Types 311Working with Common .NET Types 355Working with Files, Streams, and Serialization 395Working with Data Using Entity Framework Core 435Querying and Manipulating Data Using LINQ 489Introducing Web Development Using ASP.NET Core 531Building Websites Using ASP.NET Core Razor Pages 561Building Websites Using the Model-View-Controller Pattern 601Building and Consuming Web Services 657Building User Interfaces Using Blazor 703Epilogue 747Index 751

Contents

Preface

Where to find the code solutions

What this book covers

What you need for this book

Get in touch

Hello, C#! Welcome, .NET!

Setting up your development environment

Choosing the appropriate tool and application type for learning

Pros and cons of the Polyglot Notebooks extension

Using Visual Studio Code for cross-platform development

Using GitHub Codespaces for development in the cloud

Using Visual Studio for Mac for general development

Using Visual Studio for Windows for general development

What I used

Deploying cross-platform

Downloading and installing Visual Studio 2022 for Windows

Microsoft Visual Studio for Windows keyboard shortcuts

Downloading and installing Visual Studio Code

Installing other extensions

Managing Visual Studio Code extensions at the command line

Understanding Microsoft Visual Studio Code versions

Microsoft Visual Studio Code keyboard shortcuts

Understanding .NET

Understanding .NET Framework

Understanding the Mono, Xamarin, and Unity projects

Understanding .NET Core

Understanding the journey to one .NET

Understanding Blazor WebAssembly versioning

Understanding .NET support

Understanding .NET Runtime and .NET SDK versions

Listing and removing versions of .NET

What is different about modern .NET?

Windows desktop development

Web development

Database development

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 the compiler-generated folders and files

Understanding top-level programs

Implicitly imported namespaces

Revealing the hidden code by throwing an exception

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 Polyglot Notebooks

Using Polyglot 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

Cloning the book solution code repository

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

Speaking C#

Introducing the C# language

Understanding language versions and features

Project COOL

C# 1

C# 1.2

C# 2

C# 3

C# 4

C# 5

C# 6

C# 7.0

C# 7.1

C# 7.2

C# 7.3

C# 8

C# 9

C# 10

C# 11

Understanding C# standards

Discovering your C# compiler versions

How to output the SDK version

Enabling a specific language version compiler

Switching the C# compiler for .NET 6

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

Implicitly and globally 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

Verbatim strings

Raw string literals

Raw interpolated string literals

Summarizing options for storing text

Storing numbers

Storing whole numbers

Exploring whole numbers

Storing real numbers

Writing code to explore number sizes

Comparing double and decimal types

Storing Booleans

Storing any type of object

Storing dynamic types

Declaring local variables

Specifying the type of a local variable

Inferring the type of a local variable

Using target-typed new to instantiate objects

Getting and setting the default values for types

Exploring more about console apps

Displaying output to the user

Formatting using numbered positional arguments

Formatting using interpolated strings

Understanding format strings

Getting text input from the user

Simplifying the usage of the console

Importing a static type for a single file

Importing a static type for all code files in a project

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

Controlling Flow, Converting Types, and Handling Exceptions

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

Why you should always use braces with if statements

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

Understanding how foreach works internally

Storing multiple values in an array

Working with single-dimensional arrays

Working with multi-dimensional arrays

Working with jagged arrays

List pattern matching with arrays

Summarizing arrays

Casting and converting between types

Casting numbers implicitly and explicitly

Converting with the System.Convert type

Rounding numbers

Understanding the default rounding rules

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

Errors using Parse

Avoiding exceptions using the TryParse method

Handling exceptions

Wrapping error-prone code in a try block

Catching all exceptions

Catching specific exceptions

Catching with filters

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

Writing, Debugging, and Testing Functions

Writing functions

Understanding top-level programs and functions

Times table example

Writing a times table function

A brief aside about arguments and parameters

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 the Visual Studio Code integrated terminal during debugging

Creating code with a deliberate bug

Setting a breakpoint and starting debugging

Using Visual Studio 2022

Navigating with the debugging toolbar

Using Visual Studio Code

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

Writing to the default trace listener

Configuring trace listeners

Switching trace levels

Adding packages to a project in Visual Studio 2022

Adding packages to a project in Visual Studio Code

Reviewing project packages

Logging information about your source code

Unit testing

Understanding types of testing

Creating a class library that needs testing

Writing unit tests

Running unit tests using Visual Studio 2022

Running unit tests using Visual Studio Code

Fixing the bug

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

Problems with 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

Building Your Own Types with Object-Oriented Programming

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

Avoiding a namespace conflict with a using alias

Renaming a type with a using alias

Understanding objects

Inheriting from System.Object

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

Defining multiple constructors

Writing and calling methods

Returning values from methods

Combining multiple returned values using tuples

C# language support for tuples

Naming the fields of a tuple

Deconstructing tuples

Deconstructing types

Defining and passing parameters to methods

Overloading methods

Passing optional and named parameters

Naming parameter values when calling methods

Controlling how parameters are passed

Simplified out parameters

Understanding ref returns

Splitting classes using partial

Controlling access with properties and indexers

Defining read-only properties

Defining settable properties

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

Simplifying data members in records

Practicing and exploring

Exercise 5.1 – Test your knowledge

Exercise 5.2 – Explore topics

Summary

Implementing Interfaces and Inheriting Classes

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

Checking for null in method parameters

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

Using is to check a type

Using as to cast a type

Inheriting and extending .NET types

Inheriting exceptions

Extending types when you can’t inherit

Using static methods to reuse functionality

Using extension methods to reuse functionality

Writing better code

Treating warnings as errors

Understanding warning waves

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

Packaging and Distributing .NET Types

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 with .NET 5 and later

Checking your .NET SDKs for updates

Understanding .NET components

Assemblies, NuGet packages, and namespaces

What is a namespace?

Dependent assemblies

Microsoft .NET project SDKs

Namespaces and types in assemblies

NuGet packages

Understanding frameworks

Importing a namespace to use a type

Relating C# keywords to .NET types

Mapping C# aliases to .NET types

Understanding native-sized integers

Revealing the location of a type

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

Creating new projects

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

Enabling assembly-level trimming

Enabling type-level and member-level trimming

Decompiling .NET assemblies

Decompiling using the ILSpy extension for Visual Studio 2022

Viewing source links with Visual Studio 2022

No, you cannot technically prevent decompilation

Packaging your libraries for NuGet distribution

Referencing a NuGet package

Fixing dependencies

Packaging a library for NuGet

Publishing a package to a public NuGet feed

Publishing a package to a private NuGet feed

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

.NET Portability Analyzer

.NET Upgrade Assistant

Using non-.NET Standard libraries

Working with preview features

Requiring preview features

Enabling preview features

Practicing and exploring

Exercise 7.1 – Test your knowledge

Exercise 7.2 – Explore topics

Exercise 7.3 – Explore PowerShell

Summary

Working with Common .NET Types

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

Activating regular expression syntax coloring

Improving regular expression performance with source generators

Storing multiple objects in collections

Common features of all collections

Improving performance by ensuring the capacity of a collection

Understanding collection choices

Lists

Dictionaries

Stacks

Queues

Sets

Collection methods summary

Working with lists

Working with dictionaries

Working with queues

Sorting collections

More specialized collections

Working with a compact array of bit values

Working with efficient lists

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

Working with Files, Streams, and Serialization

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

Understanding storage streams

Understanding function streams

Understanding stream helpers

Writing to text streams

Writing to XML streams

Simplifying disposal by using the using statement

Compressing streams

Working with tar archives

Reading and writing tar entries

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

Working with Data Using Entity Framework Core

Understanding modern databases

Understanding legacy Entity Framework

Using the legacy Entity Framework 6.3 or later

Understanding Entity Framework Core

Understanding Database First and Code First

Performance improvements in EF Core 7

Creating a console app for working with EF Core

Using a sample relational database

Using SQLite

Setting up SQLite for Windows

Setting up SQLite for macOS

Setting up SQLite for other OSes

Creating the Northwind sample database for SQLite

If you are using Visual Studio 2022

Managing the Northwind sample database with SQLiteStudio

Using the lightweight ADO.NET provider for SQLite

Using 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

Understanding data seeding with the Fluent API

Building EF Core models for the Northwind tables

Defining the Category and Product entity classes

Adding tables to the Northwind database context class

Setting up the dotnet-ef tool

Scaffolding models using an existing database

Customizing the reverse engineering templates

Configuring preconvention models

Querying EF Core models

Filtering included entities

Filtering and sorting products

Getting the generated SQL

Logging EF Core

Filtering logs by provider-specific values

Logging with query tags

Pattern matching with Like

Generating a random number in queries

Defining global filters

Loading patterns with EF Core

Eager loading entities using the Include extension method

Enabling lazy loading

Explicit loading entities using the Load method

Modifying data with EF Core

Inserting entities

Updating entities

Deleting entities

More efficient updates and deletes

Pooling database contexts

Working with transactions

Controlling transactions using isolation levels

Defining an explicit transaction

Defining Code First EF Core models

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

Querying and Manipulating Data Using LINQ

Why LINQ?

Comparing imperative and declarative language features

Writing LINQ expressions

What makes LINQ?

Building LINQ expressions with the Enumerable class

Understanding deferred execution

Filtering entities with Where

Targeting a named method

Simplifying the code by removing the explicit delegate instantiation

Targeting a lambda expression

Sorting entities

Sorting by a single property using OrderBy

Sorting by a subsequent property using ThenBy

Sorting by the item itself

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

Using Visual Studio 2022 with SQLite databases

Filtering and sorting sequences

Projecting sequences into new types

Joining and grouping sequences

Joining sequences

Group-joining sequences

Aggregating sequences

Be careful with Count!

Paging with LINQ

Sweetening LINQ syntax with syntactic sugar

Using multiple threads with parallel LINQ

Creating your own LINQ extension methods

Trying the chainable extension method

Trying the mode and median 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

Introducing Web Development Using ASP.NET Core

Understanding ASP.NET Core

Classic ASP.NET versus modern ASP.NET Core

Building websites using ASP.NET Core

Building websites using a content management system

Building web applications using SPA frameworks

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 model for use in the rest of the book

Creating a class library for entity models using SQLite

Improving the class-to-table mapping

Creating a class library for a Northwind database context

Creating a class library for entity models using SQL Server

Testing the class libraries

Understanding web development

Understanding Hypertext Transfer Protocol

Understanding the components of a URL

Assigning port numbers for projects in this book

Using Google Chrome to make HTTP requests

Understanding client-side web development technologies

Practicing and exploring

Exercise 12.1 – Test your knowledge

Exercise 12.2 – Know your webbreviations

Exercise 12.3 – Explore topics

Summary

Building Websites Using ASP.NET Core Razor Pages

Exploring ASP.NET Core

Creating an empty ASP.NET Core project

Testing and securing the website

Enabling stronger security and redirecting to a secure connection

Controlling the hosting environment

Enabling a website to serve static content

Creating a folder for static files and a web page

Enabling static and default files

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

Configuring Entity Framework Core as a service

Manipulating data using Razor Pages

Enabling a model to insert entities

Defining a form to insert a new supplier

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 request decompression support

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

Building Websites Using the Model-View-Controller Pattern

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

Starting the MVC website project

Exploring visitor registration

Reviewing an MVC website project structure

Reviewing the ASP.NET Core Identity database

Exploring an ASP.NET Core MVC website

ASP.NET Core MVC initialization

The default MVC route

Controllers and actions

The ControllerBase class

The Controller class

The responsibilities of a controller

The view search path convention

Logging using the dependency service

Entity and view models

Views

Understanding how cache busting with Tag Helpers works

Customizing an ASP.NET Core MVC website

Defining a custom style

Setting up the category images

Razor syntax and expressions

Defining a typed view

Passing parameters using a route value

Model binders in more detail

Disambiguating action methods

Passing a route parameter

Passing a form parameter

Validating the model

Defining views with HTML Helper methods

Defining views with Tag Helpers

Cross-functional filters

Using a filter to secure an action method

Enabling role management and creating a role programmatically

Using a filter to define a custom route

Using a filter to cache a response

Using output caching

Output caching endpoints

Output caching MVC views

Varying cached data by query string

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

Building and Consuming Web Services

Building web services using the 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

Understanding action method return types

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

Making GET requests using REST Client

Making other requests using REST Client

Understanding Swagger

Testing requests with Swagger UI

Enabling HTTP logging

Support for logging additional request headers in W3CLogger

Consuming web services using HTTP clients

Understanding HttpClient

Configuring HTTP clients using HttpClientFactory

Getting customers as JSON in the controller

Starting multiple projects

If you are using Visual Studio 2022

If you are using Visual Studio Code

Starting the web service and MVC client projects

Implementing advanced features for web services

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

Building User Interfaces Using Blazor

Understanding Blazor

JavaScript and friends

Silverlight – C# and .NET using a plugin

WebAssembly – a target for Blazor

Blazor hosting models

Blazor components

What is the difference between Blazor and Razor?

Comparing Blazor project templates

Reviewing the Blazor Server project template

CSS and JavaScript isolation

Blazor routing to page components

How to define a routable page component

How to navigate Blazor routes

How to pass route parameters

Understanding base component classes

How to use the navigation link component with routes

Running the Blazor Server project template

Reviewing the Blazor WebAssembly project template

Deployment choices for Blazor WebAssembly apps

Differences between Blazor Server and Blazor WebAssembly projects

Similarities between Blazor Server and Blazor WebAssembly projects

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

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

Epilogue

The next steps on your C# and .NET learning journey

Polishing your skills with design guidelines

A companion book to continue your learning journey

Other books to take your learning further

The eighth edition coming November 2023

Good luck!

Index

Landmarks

Cover

Table of Contents

Index

Share your thoughts

Once you’ve read C# 11 and .NET 7 - Modern Cross-Platform Development Fundamentals, Seventh Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. 

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781803237800Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

1

Hello, C#! Welcome, .NET!

In this first chapter, the goals are setting up your development environment; understanding the similarities and differences between modern .NET, .NET Core, .NET Framework, Mono, Xamarin, and .NET Standard; creating the simplest application possible with C# 11 and .NET 7 using various code editors; and then discovering good places to look for help.

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

https://github.com/markjprice/cs11dotnet7

Simply press the . (dot) key or manually change .com to .dev in the link to convert the GitHub repository into a live code editor based on Visual Studio Code using GitHub Codespaces, as shown in Figure 1.1:

Figure 1.1: GitHub Codespaces live editing the book’s GitHub repository

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/hmdd1.

Visual Studio Code in a web browser is great to run alongside your chosen local 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.

You do not need to use or know anything about Git to get the solution code of this book. You can download a ZIP file containing all the code solutions by using the following direct link, and then extract the ZIP file into your local filesystem: https://github.com/markjprice/cs11dotnet7/archive/refs/heads/main.zip.

Throughout this book, I use the term modern .NET to refer to .NET 7 and its predecessors like .NET 5 and .NET 6 that come 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.

After this first chapter, the book can be divided into three parts: first, the grammar and vocabulary of the C# language; second, the types available in .NET for building app features; and third, the fundamentals of cross-platform websites, services, and browser apps that you can build using C# and .NET.

Most people learn complex topics best by imitation and repetition rather than reading a detailed explanation of the theory; therefore, I will not overload you with detailed explanations of every step throughout this book. The idea is to get you to write some code and see it run.

You don’t need to know all the nitty-gritty details immediately. That will be something that comes with time as you build your own apps and go beyond what any book can teach you.

In the words of Samuel Johnson, author of the English dictionary in 1755, I have committed “a few wild blunders, and risible absurdities, from which no work of such multiplicity is free.” I take sole responsibility for these and hope you appreciate the challenge of my attempt to lash the wind by writing this book about rapidly evolving technologies like C# and .NET, and the apps that you can build with them.

If you have a complaint about this book, then please contact me before writing a negative review on Amazon. Authors cannot respond to Amazon reviews so I cannot contact you to resolve the problem and help you, or at least listen to your feedback and try to do better in the next edition. Please ask a question on the Discord channel for this book at https://packt.link/csharp11dotnet7, email me (my address is on the GitHub repository for the book), or raise an issue in the GitHub repository for the book at the following link: https://github.com/markjprice/cs11dotnet7/issues.

This chapter covers the following topics:

Setting up your development environmentUnderstanding .NETBuilding console apps using Visual Studio 2022Building console apps using Visual Studio CodeExploring code using Polyglot Notebooks (online section)Reviewing the folders and files for projectsMaking good use of the GitHub repository for this bookLooking for help

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 2022 for WindowsVisual Studio 2022 for MacVisual Studio Code for Windows, Mac, or LinuxVisual Studio Code for the WebGitHub Codespaces

Third parties have created their own C# code editors, for example, JetBrains Rider.

Choosing the appropriate tool and application type for learning

What is the best tool and application type for learning C# and .NET?

When learning, the best tool is one that helps you write code and configuration but does not hide what is really happening. IDEs provide graphical user interfaces that are friendly to use, but what are they doing for you underneath? A more basic code editor that is closer to the action while providing help to write your code is better while you are learning.

Having said that, you can make the argument that the best tool is the one you are already familiar with or that you or your team will use as your daily development tool. For that reason, 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, Visual Studio for Windows, Visual Studio for Mac, or even JetBrains Rider.

In this book, I give detailed step-by-step instructions for how to create multiple projects in both Visual Studio 2022 for Windows and Visual Studio Code, in Chapter 1. After that, I give names of projects and general instructions that work with all tools so you can use whichever tool you prefer.

The best application type for learning the C# language constructs and many of the .NET libraries is one that does not distract with unnecessary application code. For example, there is no need to create an entire Windows desktop application or a website just to learn how to write a switch statement.

For that reason, I believe the best method for learning the C# and .NET topics in Chapters 1 to 11 is to build console apps. Then, in Chapters 12to16, you will build websites, services, and web browser apps.

Pros and cons of the Polyglot Notebooks extension

Another benefit of Visual Studio Code is the Polyglot Notebooks extension. This extension provides an easy and safe place to write simple code snippets for experimenting and learning. For example, data scientists use notebooks to analyze and visualize data. Students use them to learn how to write small pieces of code for language constructs and to explore APIs.

Polyglot Notebooks enables you to create a single notebook file that mixes “cells” of Markdown (richly formatted text) and code using C# and other related languages, such as PowerShell, F#, and SQL (for databases).

However, Polyglot Notebooks do have some limitations:

They cannot be used to create websites, services, and apps.They cannot read input from the user, for example, you cannot use ReadLine or ReadKey.They cannot have arguments passed to them.They do not allow you to define your own namespaces.They do not have any debugging tools (but these will come).

Using Visual Studio 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 Visual Studio 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.

Visual Studio 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 Visual Studio Code means a developer can use a cross-platform code editor to develop cross-platform apps.

Visual Studio Code has strong support for web development, although it currently has weak support for mobile and desktop development.

Visual Studio Code is supported on ARM processors so that you can develop on Apple Silicon computers and Raspberry Pi.

Visual Studio Code is by far the most popular integrated development environment, with over 70% of professional developers selecting it in the Stack Overflow 2021 survey.

Using GitHub Codespaces for development in the cloud

GitHub Codespaces is a fully configured development environment based on Visual Studio Code that can be spun up in an environment hosted in the cloud and accessed through any web browser. It supports Git repos, extensions, and a built-in command-line interface so you can edit, run, and test from any device.

Using Visual Studio for Mac for general development

Microsoft Visual Studio 2022 for Mac can create most types of applications, including console apps, websites, web services, desktop, and mobile apps.

To compile apps for Apple operating systems like iOS to run on devices like the iPhone and iPad, you must have Xcode, which only runs on macOS.

Using Visual Studio for Windows for general development

Microsoft Visual Studio 2022 for Windows can create most types of applications, including console apps, websites, web services, desktop, and mobile apps. Although you can use Visual Studio 2022 for Windows with its Xamarin extensions to write a cross-platform mobile app, you still need macOS and Xcode to compile it.

It only runs on Windows, version 7 SP1 or later. You must run it on Windows 10 or Windows 11 to create Universal Windows Platform (UWP) apps that are installed from the Microsoft Store and run in a sandbox to protect your computer.

What I used

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

HP Spectre (Intel) laptopApple Silicon Mac mini (M1) desktopRaspberry Pi 400 (ARM v8) desktop

And I used the following software:

Visual Studio Code on:macOS on an Apple Silicon Mac mini (M1) desktopWindows 11 on an HP Spectre (Intel) laptopUbuntu 64 on a Raspberry Pi 400Visual Studio 2022 for Windows on:Windows 11 on an HP Spectre (Intel) laptopVisual Studio 2022 for Mac on: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 in platforms deepens your understanding of development challenges, although any one of the above combinations is enough to learn the fundamentals of C# and .NET and how to build practical apps and websites.

You can learn how to write code with C# and .NET using a Raspberry Pi 400 with Ubuntu Desktop 64-bit by reading an extra article that I wrote at the following link: https://github.com/markjprice/cs11dotnet7/tree/main/docs/raspberry-pi-ubuntu64.

Deploying cross-platform

Your choice of