Pro C# 10 with .NET 6: Foundational Principles and Practices in Programming
- Length: 1705 pages
- Edition: 1
- Language: English
- Publisher: Apress
- Publication Date: 2022-08-11
- ISBN-10: 1484278682
- ISBN-13: 9781484278680
- Sales Rank: #317141 (See Top 100 Books)
Welcome to the most comprehensive foundational guide available on the topic of C# coding and .NET. This book goes beyond “do this, to achieve this” to drill down into the core stuff that makes a good developer, great. This expanded 11th edition delivers loads of new content on Entity Framework, Razor Pages, Web APIs and more. You will find the latest C# 10 and .NET 6 features served up with plenty of “behind the curtain” discussion designed to expand developers’ critical thinking skills when it comes to their craft. Coverage of ASP.NET Core, Entity Framework Core, and more sits alongside the latest updates to the new unified .NET platform, from performance improvements to Windows Desktop apps on .NET 6, updates in XAML tooling, and expanded coverage of data files and data handling. Going beyond the latest features in C# 10, all code samples are rewritten for this latest release.
Dive in and discover why this essential classic is a favorite of C# developers worldwide. Gain a solid foundation in object-oriented development techniques, attributes and reflection, generics and collections, and numerous advanced topics not found in other texts (such as CIL opcodes and emitting dynamic assemblies). Pro C# 10 with .NET 6 will build your coding confidence putting C# into practice, and exploring the .NET universe and its vast potential on your own terms.
What You Will Learn
- Explore C# 10 features and updates in records and record structs, global and implicit using directives, file level namespaces, extended property patterns, and more
- Develop applications with C# and modern frameworks for services, web, and smart client applications
- Hit the ground running with ASP.NET Core web applications using MVC and Razor Pages, including view components, custom tag helpers, custom validation, GDPR support, and areas
- Build ASP.NET RESTful services complete with versioning, enhanced swagger, and basic authentication
- Embrace Entity Framework Core for building real-world, data-centric applications, with deeply expanded coverage new to this edition including SQL Server temporal table support
- Dive into Windows Desktop Apps on .NET 6 using Windows Presentation Foundation
- Understand the philosophy behind .NET
- Discover the new features in .NET 6, including single file applications, smaller container images, and more
Who This Book Is For
Developers of any level who want to either learn C# and .NET or want to take their skills to the next level.
“Amazing! Provides easy-to-follow explanations and examples. I remember reading the first version of this book; this is a ‘must-have’ for your collection if you are learning .NET!”
– Rick McGuire, Senior Application Development Manager, Microsoft
“Phil is a journeyman programmer who brings years of experience and a passion for teaching to make this fully revised and modernized ‘classic’ a ‘must-have’. Any developer who wants full-spectrum, up-to-date coverage of both the C# language and how to use it with .NET and ASP.NET Core should get this book.”
– Brian A. Randell, Partner, MCW Technologies and Microsoft MVP
Table of Contents About the Authors About the Technical Reviewers Acknowledgments Introduction Part I: Introducing C# and .NET 6 Chapter 1: Introducing C# and .NET 6 Exploring Some Key Benefits of the .NET Platform Understanding the .NET Support Lifecycle Previewing the Building Blocks of the .NET Platform The Role of the Base Class Libraries The Role of .NET Standard What C# Brings to the Table Major Features in Prior Releases New Features in C# 10 Managed vs. Unmanaged Code Using Additional .NET–Aware Programming Languages Getting an Overview of .NET Assemblies The Role of the Common Intermediate Language Benefits of CIL Compiling CIL to Platform-Specific Instructions Precompiling CIL to Platform-Specific Instructions The Role of .NET Type Metadata The Role of the Assembly Manifest Understanding the Common Type System CTS Class Types CTS Interface Types CTS Structure Types CTS Enumeration Types CTS Delegate Types CTS Type Members Intrinsic CTS Data Types Understanding the Common Language Specification Ensuring CLS Compliance Understanding the .NET Runtime Distinguishing Between Assembly, Namespace, and Type Accessing a Namespace Programmatically Global Using Statements (New 10.0) Implicit Global Using Statements (New 10.0) File Scoped Namespaces (New 10.0) Referencing External Assemblies Exploring an Assembly Using ildasm.exe Summary Chapter 2: Building C# Applications Installing .NET 6 Understanding the .NET Version Numbering Scheme Confirming the .NET 6 Install Checking For Updates Use an Earlier Version of the .NET (Core) SDK Building .NET Core Applications with Visual Studio Installing Visual Studio 2022 (Windows) Taking Visual Studio 2022 for a Test-Drive Using the New Project Dialog and C# Code Editor Changing the Target .NET Core Framework Using C# 10 Features Running and Debugging Your Project Using Solution Explorer Using the Visual Class Diagram Tool Building .NET Core Applications with Visual Studio Code Taking Visual Studio Code for a Test-Drive Creating Solutions and Projects Exploring the Visual Studio Code Workspace Restoring Packages, Building and Running Programs Debugging Your Project Finding the .NET Core and C# Documentation Summary Chapter 3: Core C# Programming Constructs, Part 1 Breaking Down a Simple C# Program (Updated C# 10) Using Variations of the Main() Method (Updated 7.1) Using Top-Level Statements (New 9.0) Specifying an Application Error Code (Updated 9.0) Processing Command-Line Arguments (Updated 9.0) Specifying Command-Line Arguments with Visual Studio 2022 Additional Members of the System.Environment Class (Updated 10.0) Using the System.Console Class Performing Basic Input and Output (I/O) with the Console Class Formatting Console Output Formatting Numerical Data Formatting Numerical Data Beyond Console Applications Working with System Data Types and Corresponding C# Keywords Understanding Variable Declaration and Initialization The default Literal (New 7.1) Using Intrinsic Data Types and the new Operator (Updated 9.0) Understanding the Data Type Class Hierarchy Understanding the Members of Numerical Data Types Understanding the Members of System.Boolean Understanding the Members of System.Char Parsing Values from String Data Using TryParse to Parse Values from String Data Using System.DateTime and System.TimeSpan (Updated 10.0) Working with the System.Numerics Namespace Using Digit Separators (New 7.0) Using Binary Literals (New 7.0/7.2) Working with String Data Performing Basic String Manipulation Performing String Concatenation Using Escape Characters Performing String Interpolation Performance Improvements (Updated 10.0) Defining Verbatim Strings (Updated 8.0) Working with Strings and Equality Modifying String Comparison Behavior Strings Are Immutable Using the System.Text.StringBuilder Type Narrowing and Widening Data Type Conversions Using the checked Keyword Setting Project-wide Overflow Checking (Project File) Setting Project-wide Overflow Checking (Visual Studio) Selecting the Build Configuration Using the unchecked Keyword Understanding Implicitly Typed Local Variables Declaring Numerics Implicitly Understanding Restrictions on Implicitly Typed Variables Implicit Typed Data Is Strongly Typed Data Understanding the Usefulness of Implicitly Typed Local Variables Working with C# Iteration Constructs Using the for Loop Using the foreach Loop Using Implicit Typing Within foreach Constructs Using the while and do/while Looping Constructs A Quick Discussion About Scope Working with Decision Constructs and the Relational/Equality Operators Using the if/else Statement Using Equality and Relational Operators Using if/else with Pattern Matching (New 7.0) Making Pattern Matching Improvements (New 9.0) Using the Conditional Operator (Updated 7.2, 9.0) Using Logical Operators Using the switch Statement Performing switch Statement Pattern Matching (New 7.0, Updated 9.0) Using switch Expressions (New 8.0) Summary Chapter 4: Core C# Programming Constructs, Part 2 Understanding C# Arrays Looking at the C# Array Initialization Syntax Understanding Implicitly Typed Local Arrays Defining an Array of Objects Working with Multidimensional Arrays Using Arrays As Arguments or Return Values Using the System.Array Base Class Using Indices and Ranges (New 8.0, Updated 10.0) Understanding Methods Understanding Expression-Bodied Members Understanding Local Functions (New 7.0, Updated 9.0) Understanding Static Local Functions (New 8.0) Understanding Method Parameters Understanding Method Parameter Modifiers Understanding the Default Parameter-Passing Behavior The Default Behavior for Value Types The Default Behavior for Reference Types Using the out Modifier (Updated 7.0) Discarding out Parameters (New 7.0) The out Modifier in Constructors and Initializers (New 7.3) Using the ref Modifier Using the in Modifier (New 7.2) Using the params Modifier Defining Optional Parameters Using Named Arguments (Updated 7.2) Understanding Method Overloading Checking Parameters for Null (Updated 10.0) Understanding the enum Type Controlling the Underlying Storage for an enum Declaring enum Variables Using the System.Enum Type Dynamically Discovering an enum’s Name-Value Pairs Using Enums, Flags, and Bitwise Operations Understanding the Structure Creating Structure Variables Structure Constructors (Updated 10.0) Using Field Initializers (New 10.0) Using Read-Only Structs (New 7.2) Using Read-Only Members (New 8.0) Using ref Structs (New 7.2) Using Disposable ref Structs (New 8.0) Understanding Value Types and Reference Types Using Value Types, Reference Types, and the Assignment Operator Using Value Types Containing Reference Types Passing Reference Types by Value Passing Reference Types by Reference Final Details Regarding Value Types and Reference Types Understanding C# Nullable Types Using Nullable Value Types Using Nullable Reference Types (New 8.0, Updated 10.0) Opting in for Nullable Reference Types (Updated 10.0) Nullable Reference Types in Action Migration Considerations Change Nullable Warnings to Errors Operating on Nullable Types The Null-Coalescing Operator The Null-Coalescing Assignment Operator (New 8.0) The Null Conditional Operator Understanding Tuples (New/Updated 7.0) Getting Started with Tuples Using Inferred Variable Names (Updated 7.1) Understanding Tuple Equality/Inequality (New 7.3) Understanding Tuples as Method Return Values Understanding Discards with Tuples Understanding Tuple Pattern Matching switch Expressions (New 8.0) Deconstructing Tuples (Updated 10.0) Deconstructing Tuples with Positional Pattern Matching (New 8.0) Summary Chapter 5: Understanding Encapsulation Introducing the C# Class Type Allocating Objects with the new Keyword Understanding Constructors Understanding the Role of the Default Constructor Defining Custom Constructors Constructors As Expression-Bodied Members (New 7.0) Constructors with out Parameters (New 7.3) Understanding the Default Constructor Revisited Understanding the Role of the this Keyword Chaining Constructor Calls Using this Observing Constructor Flow Revisiting Optional Arguments Understanding the static Keyword Defining Static Field Data Defining Static Methods Defining Static Constructors Defining Static Classes Importing Static Members via the C# using Keyword Defining the Pillars of OOP Understanding the Role of Encapsulation Understanding the Role of Inheritance Understanding the Role of Polymorphism Understanding C# Access Modifiers (Updated 7.2) Using the Default Access Modifiers Using Access Modifiers and Nested Types Understanding the First Pillar: C#’s Encapsulation Services Encapsulation Using Traditional Accessors and Mutators Encapsulation Using Properties Properties As Expression-Bodied Members (New 7.0) Using Properties Within a Class Definition Read-Only Properties Write-Only Properties Mixing Private and Public Get/Set Methods on Properties Revisiting the static Keyword: Defining Static Properties Pattern Matching with Property Patterns (New 8.0) Extended Property Patterns (New 10.0) Understanding Automatic Properties Interacting with Automatic Properties Automatic Properties and Default Values Initializing Automatic Properties Understanding Object Initialization Looking at the Object Initialization Syntax Using init-Only Setters (New 9.0) Calling Custom Constructors with Initialization Syntax Initializing Data with Initialization Syntax Working with Constant and Read-Only Field Data Understanding Constant Field Data Constant Interpolated Strings (New 10.0) Understanding Read-Only Fields Understanding Static Read-Only Fields Understanding Partial Classes Records (New 9.0) Immutable Record Types with Standard Property Syntax Immutable Record Types with Positional Syntax Deconstructing Mutable Record Types Mutable Record Types Value Equality with Record Types Copying Record Types Using with Expressions Record Structs (New 10.0) Mutable Record Structs Immutable Record Structs Deconstructing Record Structs Summary Chapter 6: Understanding Inheritance and Polymorphism Understanding the Basic Mechanics of Inheritance Specifying the Parent Class of an Existing Class Regarding Multiple Base Classes Using the sealed Keyword Revisiting Visual Studio Class Diagrams Understanding the Second Pillar of OOP: The Details of Inheritance Calling Base Class Constructors with the base Keyword Keeping Family Secrets: The protected Keyword Adding a sealed Class Understanding Inheritance with Record Types (New 9.0) Inheritance for Record Types with Standard Properties Inheritance for Record Types with Positional Parameters Nondestructive Mutation with Inherited Record Types Equality with Inherited Record Types Deconstructor Behavior with Inherited Record Types Programming for Containment/Delegation Understanding Nested Type Definitions Understanding the Third Pillar of OOP: C#’s Polymorphic Support Using the virtual and override Keywords Overriding Virtual Members with Visual Studio/Visual Studio Code Sealing Virtual Members (Updated 10.0) Understanding Abstract Classes Understanding the Polymorphic Interface Understanding Member Shadowing Understanding Base Class/Derived Class Casting Rules Using the C# as Keyword Using the C# is Keyword (Updated 7.0, 9.0) Discards with the is Keyword (New 7.0) Revisiting Pattern Matching (New 7.0) Discards with switch Statements (New 7.0) Understanding the Super Parent Class: System.Object Overriding System.Object.ToString() Overriding System.Object.Equals() Overriding System.Object.GetHashCode() Testing Your Modified Person Class Using the Static Members of System.Object Summary Chapter 7: Understanding Structured Exception Handling Ode to Errors, Bugs, and Exceptions The Role of .NET Exception Handling The Building Blocks of .NET Exception Handling The System.Exception Base Class The Simplest Possible Example Throwing a General Exception Catching Exceptions Throw As Expression (New 7.0) Configuring the State of an Exception The TargetSite Property The StackTrace Property The HelpLink Property The Data Property System-Level Exceptions (System.SystemException) Application-Level Exceptions (System.ApplicationException) Building Custom Exceptions, Take 1 Building Custom Exceptions, Take 2 Building Custom Exceptions, Take 3 Processing Multiple Exceptions General catch Statements Rethrowing Exceptions Inner Exceptions The finally Block Exception Filters Debugging Unhandled Exceptions Using Visual Studio Summary Chapter 8: Working with Interfaces Understanding Interface Types Interface Types vs. Abstract Base Classes Defining Custom Interfaces Implementing an Interface Invoking Interface Members at the Object Level Obtaining Interface References: The as Keyword Obtaining Interface References: The is Keyword (Updated 7.0) Default Implementations (New 8.0) Static Constructors and Members (New 8.0) Interfaces as Parameters Interfaces as Return Values Arrays of Interface Types Implementing Interfaces Using Visual Studio or Visual Studio Code Explicit Interface Implementation Designing Interface Hierarchies Interface Hierarchies with Default Implementations (New 8.0) Multiple Inheritance with Interface Types The IEnumerable and IEnumerator Interfaces Building Iterator Methods with the yield Keyword Guard Clauses with Local Functions (New 7.0) Building a Named Iterator The ICloneable Interface A More Elaborate Cloning Example The IComparable Interface Specifying Multiple Sort Orders with IComparer Custom Properties and Custom Sort Types Summary Chapter 9: Understanding Object Lifetime Classes, Objects, and References The Basics of Object Lifetime The CIL of new Setting Object References to null Determining If an Object Is Live Understanding Object Generations Ephemeral Generations and Segments Garbage Collection Types Background Garbage Collection The System.GC Type Forcing a Garbage Collection Building Finalizable Objects Overriding System.Object.Finalize() Detailing the Finalization Process Building Disposable Objects Reusing the C# using Keyword Using Declarations (New 8.0) Building Finalizable and Disposable Types A Formalized Disposal Pattern Understanding Lazy Object Instantiation Customizing the Creation of the Lazy Data Chapter 10: Collections and Generics The Motivation for Collection Classes The System.Collections Namespace An Illustrative Example: Working with the ArrayList A Survey of System.Collections.Specialized Namespace The Problems of Nongeneric Collections The Issue of Performance The Issue of Type Safety A First Look at Generic CollectionsT The Role of Generic Type Parameters Specifying Type Parameters for Generic Classes/Structures Specifying Type Parameters for Generic Members Specifying Type Parameters for Generic Interfaces The System.Collections.Generic Namespace Understanding Collection Initialization Syntax Working with the List<T> Class Working with the Stack<T> Class Working with the Queue<T> Class Working with the PriorityQueue<TElement, TPriority> Class (New 10) Working with the SortedSet<T> Class Working with the Dictionary<TKey, TValue> Class The System.Collections.ObjectModel Namespace Working with ObservableCollection<T> Creating Custom Generic Methods Inference of Type Parameters Creating Custom Generic Structures and Classes Default Value Expressions with Generics Default Literal Expressions (New 7.1) Pattern Matching with Generics (New 7.1) Constraining Type Parameters Examples of Using the where Keyword The Lack of Operator Constraints Summary Chapter 11: Advanced C# Language Features Understanding Indexer Methods Indexing Data Using String Values Overloading Indexer Methods Indexers with Multiple Dimensions Indexer Definitions on Interface Types Understanding Operator Overloading Overloading Binary Operators What of the += and –= Operators? Overloading Unary Operators Overloading Equality Operators Overloading Comparison Operators Final Thoughts Regarding Operator Overloading Understanding Custom Type Conversions Recall: Numerical Conversions Recall: Conversions Among Related Class Types Creating Custom Conversion Routines Additional Explicit Conversions for the Square Type Defining Implicit Conversion Routines Understanding Extension Methods Defining Extension Methods Invoking Extension Methods Importing Extension Methods Extending Types Implementing Specific Interfaces Extension Method GetEnumerator Support (New 9.0) Understanding Anonymous Types Defining an Anonymous Type The Internal Representation of Anonymous Types The Implementation of ToString() and GetHashCode() The Semantics of Equality for Anonymous Types Anonymous Types Containing Anonymous Types Working with Pointer Types The unsafe Keyword Working with the * and & Operators An Unsafe (and Safe) Swap Function Field Access via Pointers (the -> Operator) The stackalloc Keyword Pinning a Type via the fixed Keyword The sizeof Keyword Summary Chapter 12: Delegates, Events, and Lambda Expressions Understanding the Delegate Type Defining a Delegate Type in C# The System.MulticastDelegate and System.Delegate Base Classes The Simplest Possible Delegate Example Investigating a Delegate Object Sending Object State Notifications Using Delegates Enabling Multicasting Removing Targets from a Delegate’s Invocation List Method Group Conversion Syntax Understanding Generic Delegates The Generic Action<> and Func<> Delegates Understanding C# Events The C# event Keyword Events Under the Hood Listening to Incoming Events Simplifying Event Registration Using Visual Studio Creating Custom Event Arguments The Generic EventHandler<T> Delegate Understanding C# Anonymous Methods Accessing Local Variables Using static with Anonymous Methods (New 9.0) Discards with Anonymous Methods (New 9.0) Understanding Lambda Expressions Dissecting a Lambda Expression Processing Arguments Within Multiple Statements Lambda Expressions with Multiple (or Zero) Parameters Using static with Lambda Expressions (New 9.0) Discards with Lambda Expressions (New 9.0) Retrofitting the CarEvents Example Using Lambda Expressions Lambdas and Expression-Bodied Members (Updated 7.0) Summary Chapter 13: LINQ to Objects LINQ-Specific Programming Constructs Implicit Typing of Local Variables Object and Collection Initialization Syntax Lambda Expressions Extension Methods Anonymous Types Understanding the Role of LINQ LINQ Expressions Are Strongly Typed The Core LINQ Assemblies Applying LINQ Queries to Primitive Arrays Once Again, Using Extension Methods Once Again, Without LINQ Reflecting Over a LINQ Result Set LINQ and Implicitly Typed Local Variables LINQ and Extension Methods The Role of Deferred Execution DefaultIfEmpty (New 10.0) The Role of Immediate Execution Set Default for [First/Last/Single]OrDefault Methods (New 10) Returning the Result of a LINQ Query Returning LINQ Results via Immediate Execution Applying LINQ Queries to Collection Objects Accessing Contained Subobjects Applying LINQ Queries to Nongeneric Collections Filtering Data Using OfType<T>() Investigating the C# LINQ Query Operators Basic Selection Syntax Obtaining Subsets of Data Paging Data Paging Data with Ranges (New 10.0) Paging Data with Chunks (New 10.0) Projecting New Data Types Projecting to Different Data Types Obtaining Counts Using Enumerable Obtaining Nonenumerated Counts (New 10.0) Reversing Result Sets Sorting Expressions LINQ As a Better Venn Diagramming Tool Venn Diagramming with Selectors (New 10.0) Removing Duplicates Removing Duplicates with Selectors (New 10.0) LINQ Aggregation Operations Aggregation with Selectors (New 10.0) The Internal Representation of LINQ Query Statements Building Query Expressions with Query Operators (Revisited) Building Query Expressions Using the Enumerable Type and Lambda Expressions Building Query Expressions Using the Enumerable Type and Anonymous Methods Building Query Expressions Using the Enumerable Type and Raw Delegates Summary Chapter 14: Processes, AppDomains, and Load Contexts The Role of a Windows Process The Role of Threads Interacting with Processes Using .NET Core Enumerating Running Processes Investigating a Specific Process Investigating a Process’s Thread Set Investigating a Process’s Module Set Starting and Stopping Processes Programmatically Controlling Process Startup Using the ProcessStartInfo Class Leveraging OS Verbs with ProcessStartInfo Understanding .NET Application Domains The System.AppDomain Class Interacting with the Default Application Domain Enumerating Loaded Assemblies Assembly Isolation with Application Load Contexts Summarizing Processes, AppDomains, and Load Contexts Summary Chapter 15: Multithreaded, Parallel, and Async Programming The Process/AppDomain/Context/Thread Relationship The Problem of Concurrency The Role of Thread Synchronization The System.Threading Namespace The System.Threading.Thread Class Obtaining Statistics About the Current Thread of Execution The Name Property The Priority Property Manually Creating Secondary Threads Working with the ThreadStart Delegate Working with the ParameterizedThreadStart Delegate The AutoResetEvent Class Foreground Threads and Background Threads The Issue of Concurrency Synchronization Using the C# lock Keyword Synchronization Using the System.Threading.Monitor Type Synchronization Using the System.Threading.Interlocked Type Programming with Timer Callbacks Using a Stand-Alone Discard (New 7.0) Understanding the ThreadPool Parallel Programming Using the Task Parallel Library The System.Threading.Tasks Namespace The Role of the Parallel Class Data Parallelism with the Parallel Class Accessing UI Elements on Secondary Threads The Task Class Handling Cancellation Request Task Parallelism Using the Parallel Class Parallel LINQ Queries (PLINQ) Opting in to a PLINQ Query Cancelling a PLINQ Query Async Calls Using the async/await Pattern A First Look at the C# async and await Keywords (Updated 7.1, 9.0) SynchronizationContext and async/await The Role of ConfigureAwait Naming Conventions for Asynchronous Methods Async Methods That Don’t Return Data Async Void Methods Async Void Methods Using Task Async Methods with Multiple Awaits Calling Async Methods from Synchronous Methods Await in catch and finally Blocks Generalized Async Return Types (New 7.0) Local Functions with async/await (New 7.0) Cancelling async/await Operations Cancelling async/await operations with WaitAsync() (New 10.0) Cancelling async/await operations in Synchronous Calls Asynchronous Streams (New 8.0) The Parallel.ForEachAsync() Method (New 10.0) Update the Book Reader App with async/await Wrapping Up async and await Summary Chapter 16: Building and Configuring Class Libraries Defining Custom Namespaces (Updated 10.0) Resolving Name Clashes with Fully Qualified Names Resolving Name Clashes with Aliases Creating Nested Namespaces Change the Root Namespace Using Visual Studio 2022 Change the Root Namespace Using the Project File The Role of .NET Assemblies Assemblies Promote Code Reuse Assemblies Establish a Type Boundary Assemblies Are Versionable Units Assemblies Are Self-Describing Understanding the Format of a .NET Assembly Installing the C++ Profiling Tools The Operating System (Windows) File Header The CLR File Header CIL Code, Type Metadata, and the Assembly Manifest Optional Assembly Resources Class Libraries vs. Console Applications .NET Standard vs. .NET (Core) Class Libraries Configuring Applications with Configuration Files Multiple Configuration Files Working with Objects (Updated 10.0) Additional Configuration Options Building and Consuming a .NET Class Library Exploring the Manifest Exploring the CIL Exploring the Type Metadata Building a C# Client Application Building a Visual Basic Client Application Cross-Language Inheritance in Action Exposing internal Types to Other Assemblies Using an Assembly Attribute Using the Project File NuGet and .NET Core Packaging Assemblies with NuGet Referencing NuGet Packages Publishing Console Applications (Updated .NET 5/6) Publishing Framework-Dependent Applications Publishing Self-Contained Applications Publishing Self-Contained Applications as a Single File How .NET Locates Assemblies Summary Chapter 17: Type Reflection, Late Binding, Attribute, and Dynamic Types The Necessity of Type Metadata Viewing (Partial) Metadata for the EngineStateEnum Enumeration Viewing (Partial) Metadata for the Car Type Examining a TypeRef Documenting the Defining Assembly Documenting Referenced Assemblies Documenting String Literals Understanding Reflection The System.Type Class Obtaining a Type Reference Using System.Object.GetType() Obtaining a Type Reference Using typeof() Obtaining a Type Reference Using System.Type.GetType() Building a Custom Metadata Viewer Reflecting on Methods Reflecting on Fields and Properties Reflecting on Implemented Interfaces Displaying Various Odds and Ends Adding the Top-Level Statements Reflecting on Static Types Reflecting on Generic Types Reflecting on Method Parameters and Return Values Dynamically Loading Assemblies Reflecting on Framework Assemblies Understanding Late Binding The System.Activator Class Invoking Methods with No Parameters Invoking Methods with Parameters Understanding the Role of .NET Attributes Attribute Consumers Applying Attributes in C# C# Attribute Shorthand Notation Specifying Constructor Parameters for Attributes The Obsolete Attribute in Action Building Custom Attributes Applying Custom Attributes Named Property Syntax Restricting Attribute Usage Assembly-Level Attributes Using a Separate File for Assembly Attributes Using the Project File for Assembly Attributes Reflecting on Attributes Using Early Binding Reflecting on Attributes Using Late Binding Putting Reflection, Late Binding, and Custom Attributes in Perspective Building an Extendable Application Building the Multiproject ExtendableApp Solution Creating the Solution and Projects with the CLI Adding PostBuild Events into the Project Files Creating the Solution and Projects with Visual Studio Setting Project Build Dependencies Adding PostBuild Events Building CommonSnappableTypes.dll Building the C# Snap-In Building the Visual Basic Snap-In Adding the Code for the ExtendableApp The Role of the C# dynamic Keyword Calling Members on Dynamically Declared Data The Scope of the dynamic Keyword Limitations of the dynamic Keyword Practical Uses of the dynamic Keyword The Role of the Dynamic Language Runtime The Role of Expression Trees Dynamic Runtime Lookup of Expression Trees Simplifying Late-Bound Calls Using Dynamic Types Leveraging the dynamic Keyword to Pass Arguments Summary Chapter 18: Understanding CIL and the Role of Dynamic Assemblies Motivations for Learning the Grammar of CIL Examining CIL Directives, Attributes, and Opcodes The Role of CIL Directives The Role of CIL Attributes The Role of CIL Opcodes The CIL Opcode/CIL Mnemonic Distinction Pushing and Popping: The Stack-Based Nature of CIL Understanding Round-Trip Engineering The Role of CIL Code Labels Interacting with CIL: Modifying an *.il File Compiling CIL Code with ILASM.EXE Compiling CIL Code with Microsoft.NET.Sdk.il Projects Understanding CIL Directives and Attributes Specifying Externally Referenced Assemblies in CIL Defining the Current Assembly in CIL Defining Namespaces in CIL Defining Class Types in CIL Defining and Implementing Interfaces in CIL Defining Structures in CIL Defining Enums in CIL Defining Generics in CIL Compiling the CILTypes.il File .NET Base Class Library, C#, and CIL Data Type Mappings Defining Type Members in CIL Defining Field Data in CIL Defining Type Constructors in CIL Defining Properties in CIL Defining Member Parameters Examining CIL Opcodes The .maxstack Directive Declaring Local Variables in CIL Mapping Parameters to Local Variables in CIL The Hidden this Reference Representing Iteration Constructs in CIL The Final Word on CIL Understanding Dynamic Assemblies Exploring the System.Reflection.Emit Namespace The Role of the System.Reflection.Emit.ILGenerator Emitting a Dynamic Assembly Emitting the Assembly and Module Set The Role of the ModuleBuilder TypeC Emitting the HelloClass Type and the String Member Variable Emitting the Constructors Emitting the SayHello() Method Using the Dynamically Generated Assembly Summary Chapter 19: File I/O and Object Serialization Exploring the System.IO Namespace The Directory(Info) and File(Info) Types The Abstract FileSystemInfo Base Class Working with the DirectoryInfo Type Enumerating Files with the DirectoryInfo Type Creating Subdirectories with the DirectoryInfo Type Working with the Directory Type Working with the DriveInfo Class Type Working with the FileInfo Class The FileInfo.Create() Method The FileInfo.Open() Method The FileInfo.OpenRead() and FileInfo.OpenWrite() Methods The FileInfo.OpenText() Method The FileInfo.CreateText() and FileInfo.AppendText() Methods Working with the File Type Additional File-centric Members The Abstract Stream Class Working with FileStreams Working with StreamWriters and StreamReaders Writing to a Text File Reading from a Text File Directly Creating StreamWriter/StreamReader Types Working with StringWriters and StringReaders Working with BinaryWriters and BinaryReaders Watching Files Programmatically Understanding Object Serialization The Role of Object Graphs Creating the Sample Types and Top-Level Statements Extensible Markup Language (XML) Serializing and Deserializing with the XmlSerializer Controlling the Generated XML Data Serializing Objects Using the XmlSerializer Serializing Collections of Objects Deserializing Objects and Collections of Objects JavaScript Object Notation (JSON) Serialization Serializing and Deserializing with System.Text.Json Controlling the Generated JSON Data Serializing Objects Using the JsonSerializer Including Fields Pretty-Print the JSON PascalCase or camelCase JSON Ignoring Circular References with JsonSerializer (New 10) Number Handling with JsonSerializer JSON Property Ordering (New 10) Support for IAsyncEnumerable (New 10) Streaming Serialization Streaming Deserialization Potential Performance Issues Using JsonSerializerOptions Web Defaults for JsonSerializer General Defaults for JsonSerializer Serializing Collections of Objects Deserializing Objects and Collections of Objects JsonConverters Summary Chapter 20: Data Access with ADO.NET ADO.NET vs. ADO Understanding ADO.NET Data Providers ADO.NET Data Providers The Types of the System.Data Namespace The Role of the IDbConnection Interface The Role of the IDbTransaction Interface The Role of the IDbCommand Interface The Role of the IDbDataParameter and IDataParameter Interfaces The Role of the IDbDataAdapter and IDataAdapter Interfaces The Role of the IDataReader and IDataRecord Interfaces Abstracting Data Providers Using Interfaces Setting Up SQL Server and Azure Data Studio Installing SQL Server Installing SQL Server in a Docker Container Pulling the Image and Running SQL Server 2019 Installing SQL Server 2019 Installing a SQL Server IDE Connecting to SQL Server Connecting to SQL Server in a Docker Container Connecting to SQL Server LocalDb Connecting to Any Other SQL Server Instance Restoring the AutoLot Database Backup Copying the Backup File to Your Container Restoring the Database with SSMS Restoring the Database to SQL Server (Docker) Restoring the Database to SQL Server (Windows) Restoring the Database with Azure Data Studio Creating the AutoLot Database Creating the Database Creating the Tables Creating the Inventory Table Creating the Makes Table Creating the Customers Table Creating the Orders Table Creating the CreditRisks Table Creating the Table Relationships Creating the Inventory to Makes Relationship Creating the Inventory to Orders Relationship Creating the Orders to Customers Relationship Creating the Customers to CreditRisks Relationship Creating the GetPetName() Stored Procedure Adding Test Records Makes Records Inventory Table Records Customer Records Order Records CreditRisk Records The ADO.NET Data Provider Factory Model A Complete Data Provider Factory Example A Potential Drawback with the Data Provider Factory Model Diving Deeper into Connections, Commands, and DataReaders Working with Connection Objects Working with ConnectionStringBuilder Objects Working with Command Objects Working with Data Readers Obtaining Multiple Result Sets Using a Data Reader Working with Create, Update, and Delete Queries Create the Car and CarViewModel Classes Adding the InventoryDal Class Adding Constructors Opening and Closing the Connection Adding IDisposable Adding the Selection Methods Inserting a New Car Create the Strongly Type InsertCar() Method Adding the Deletion Logic Adding the Update Logic Working with Parameterized Command Objects Specifying Parameters Using the DbParameter Type Update the GetCar Method Update the DeleteCar Method Update the UpdateCarPetName Method Update the InsertAuto Method Executing a Stored Procedure Creating a Console-Based Client Application Understanding Database Transactions Key Members of an ADO.NET Transaction Object Adding a Transaction Method to InventoryDal Testing Your Database Transaction Executing Bulk Copies with ADO.NET Exploring the SqlBulkCopy Class Creating a Custom Data Reader Executing the Bulk Copy Testing the Bulk Copy Summary Chapter 21: Introducing Entity Framework Core Object-Relational Mappers Understanding the Role of the Entity Framework Core The Building Blocks of the Entity Framework The DbContext Class Creating a Derived DbContext Configuring the DbContext The Design-Time DbContext Factory OnModelCreating Saving Changes Transaction and Save Point Support Explicit Transactions and Execution Strategies Saving/Saved Changes Events The DbSet<T> Class The ChangeTracker ChangeTracker Events The StateChanged Event The Tracked Event Resetting DbContext State Entities Entity Properties and Database Columns Table Mapping Schemes Table-Per-Hierarchy Mapping Table-per-Type Mapping Navigation Properties and Foreign Keys Missing Foreign Key Properties One-to-Many Relationships One-to-One Relationships Many-to-Many Relationships Many-to-Many Prior to EF Core 5 Cascade Behavior Optional Relationships Required Relationships Entity Conventions Mapping Properties to Columns Overriding EF Core Conventions Entity Framework Data Annotations Annotations and Navigation Properties The Fluent API Class and Property Methods Class and Property Mapping Keys and Indices Field Size and Nullability Default Values RowVersion/Concurrency Tokens SQL Server Sparse Columns Computed Columns Check Constraints One-to-Many Relationships One-to-One Relationships Many-to-Many Relationships Excluding Entities from Migrations Using IEntityTypeConfiguration Classes Conventions, Annotations, and the Fluent API, Oh My! Owned Entity Types Query Types Flexible Query/Table Mapping Query Execution Mixed Client-Server Evaluation Tracking vs. NoTracking Queries Code First vs. Database First The EF Core Global Tool CLI Commands The Migrations Commands The Add Command The Remove Command The List Command The Bundle Command The Script Command The Database Commands The Drop Command The Database Update Command The DbContext Commands The DbContext Scaffold Command The DbContext Optimize Command Summary Chapter 22: Exploring Entity Framework Core Creating Records Entity State Add a Single Record Using Add Add a Single Record Using Attach Add Multiple Records at Once Identity Column Considerations When Adding Records Adding an Object Graph Add Many-to-Many Records Add Sample Records Clear the Sample Data Querying Data Get All Records Filter Records Sort Records Reverse Sort Records Paging Retrieve a Single Record Using First Using Last Using Single Using Find Aggregation Methods Any( ) and All( ) Getting Data from Stored Procedures Querying Related Data Eager Loading Filtered Include Eager Loading with Split Queries Many-to-Many Queries Explicit Loading Lazy Loading Updating Records Entity State Update Tracked Entities Update Nontracked Entities Deleting Records Entity State Delete Tracked Records Delete Nontracked Entities Catch Cascade Delete Failures Notable EF Core Features Global Query Filters Global Query Filters on Navigation Properties Explicit Loading with Global Query Filters Raw SQL Queries with LINQ Projections Handling Database-Generated Values Concurrency Checking Connection Resiliency Database Function Mapping EF.Functions Batching of Statements Value Converters Shadow Properties SQL Server Temporal Table Support Configure Temporal Tables Main Table and History Table Interactions Querying Temporal Tables Clearing Temporal Tables Summary Chapter 23: Build a Data Access Layer with Entity Framework Core Create the AutoLot.Dal and AutoLot.Models Projects Add the Database View Scaffold the DbContext and Entities Examine the Results Switch to Code First Create the DbContext Design-Time Factory Create the Initial Migration Applying the Migration Create the GlobalUsings Files Create Custom Exceptions Finalize the Entities and ViewModel The Entities The BaseEntity Class The Owned Person Entity The Car (Inventory) Entity Update the ApplicationDbContext Class The CarConfiguration Class The Driver Entity Update the ApplicationDbContext Class The DriverConfiguration Class The CarDriver Entity Update the ApplicationDbContext Class The CarDriverConfiguration Class The Radio Entity Update the ApplicationDbContext Class The RadioConfiguration Class The Customer Entity The CustomerConfiguration Class The Make Entity The MakeConfiguration Class The CreditRisk Entity The CreditRiskConfiguration Class The Order Entity The OrderConfiguration Class The SeriLogEntry Entity Update the ApplicationDbContext Class The SerilogEntryConfiguration Class The View Models The CustomerOrderViewModel Add the INonPersisted Interface Update the ApplicationDbContext Class The CustomerOrderViewModelConfiguration Class Update the GlobalUsings.cs Files The TemporalViewModel Update the ApplicationDbContext Add the Mapped Database Functions Handling DbContext and ChangeTracker Events Override the Conventions Override the SaveChanges Method Create the Next Migration and Update the Database Use EF Migrations to Create/Update Database Objects Add the MigrationHelpers Class Create and Update the Migration Apply the Migration Add the Repositories Add the IBaseViewRepo Interface Add the BaseViewRepo Implementation Implement the Read Methods Add the IBaseRepo Interface Add the BaseRepo Implementation Implement the SaveChanges Method Implement the Common Read Methods The Add, Update, and Delete Methods Add the ITemporalTableBaseRepo Interface Add the TemporalTableBaseRepo Implementation Implement the Helper Methods Implement the Temporal Methods Entity-Specific Repo Interfaces The CarDriver Repository Interface The Car Repository Interface The Credit Risk Interface The CustomerOrderViewModel Repository Interface The Customer Repository Interface The Driver Repository Interface The Make Repository Interface The Order Repository Interface The Radio Repository Interface Implement the Entity-Specific Repositories The CarDriver Repository The Car Repository The CreditRisk Repository The CustomerOrderViewModel Repository The Customer Repository The Driver Repository The Make Repository The Order Repository The Radio Repository Update the GlobalUsings.cs Files Programmatic Database and Migration Handling Drop, Create, and Clean the Database Data Initialization Create the Sample Data Load the Sample Data Summary Chapter 24: Test-Driving AutoLot Setting Up the Test-Drives Create the Project Make the AutoLot.Dal Internals Visible to AutoLot.Dal.Tests Add the GlobalUsings File A First Look at xUnit Fact Test Methods Theory Test Methods Executing Tests Configure the Project and DbContext Instances Create the Integration Test Helper Add the BaseTest Class Add the Transacted Test Execution Helpers Add the EnsureAutoLotDatabase Test Fixture Class Add the Integration Test Classes Querying the Database LINQ Queries LINQ Execution Get All Records Filter Records Sort Records Reverse Sort Records Single-Record Queries Using First Using Last Using Single Global Query Filters Disable the Query Filters Query Filters on Navigation Properties Load Related Data Eagerly Splitting Queries on Related Data Filtering Related Data Load Related Data Explicitly Load Related Data Explicitly with Query Filters Temporal Queries SQL Queries with LINQ Aggregate Methods Any() and All() Getting Data from Stored Procedures Creating Records Add a Single Record Add a Single Record Using Attach Add Multiple Records at Once Adding an Object Graph Updating Records Update Tracked Entities Update Nontracked Entities Concurrency Checking When Updating Records Deleting Records Delete Tracked Records Delete Nontracked Entities Catch Cascade Delete Failures Concurrency Checking When Deleting Records Summary Chapter 25: Introducing Windows Presentation Foundation and XAML The Motivation Behind WPF Unifying Diverse APIs Providing a Separation of Concerns via XAML Providing an Optimized Rendering Model Simplifying Complex UI Programming Investigating the WPF Assemblies The Role of the Application Class Constructing an Application Class Enumerating the Windows Collection The Role of the Window Class The Role of System.Windows.Controls.ContentControl The Role of System.Windows.Controls.Control The Role of System.Windows.FrameworkElement The Role of System.Windows.UIElement The Role of System.Windows.Media.Visual The Role of System.Windows.DependencyObject The Role of System.Windows.Threading.DispatcherObject Understanding the Syntax of WPF XAML Introducing Kaxaml XAML XML Namespaces and XAML “Keywords” Controlling Class and Member Variable Visibility XAML Elements, XAML Attributes, and Type Converters Understanding XAML Property-Element Syntax Understanding XAML Attached Properties Understanding XAML Markup Extensions Building WPF Applications Using Visual Studio The WPF Project Templates The Toolbox and XAML Designer/Editor Setting Properties Using the Properties Window Handling Events Using the Properties Window Handling Events in the XAML Editor The Document Outline Window Enable or Disable the XAML Debugger Examining the App.xaml File Mapping the Window XAML Markup to C# Code The Role of BAML Solving the Mystery of Main() Interacting with Application-Level Data Handling the Closing of a Window Object Intercepting Mouse Events Intercepting Keyboard Events Summary Chapter 26: WPF Controls, Layouts, Events, and Data Binding A Survey of the Core WPF Controls The WPF Ink Controls The WPF Document Controls WPF Common Dialog Boxes A Brief Review of the Visual Studio WPF Designer Working with WPF Controls Using Visual Studio Working with the Document Outline Editor Controlling Content Layout Using Panels Positioning Content Within Canvas Panels Positioning Content Within WrapPanel Panels Positioning Content Within StackPanel Panels Positioning Content Within Grid Panels Sizing Grid Columns and Rows Grids with GridSplitter Types Positioning Content Within DockPanel Panels Enabling Scrolling for Panel Types Configuring Panels Using the Visual Studio Designers Building a Window’s Frame Using Nested Panels Building the Menu System Building Menus Visually Building the Toolbar Building the Status Bar Finalizing the UI Design Implementing the MouseEnter/MouseLeave Event Handlers Implementing the Spell-Checking Logic Understanding WPF Commands The Intrinsic Command Objects Connecting Commands to the Command Property Connecting Commands to Arbitrary Actions Working with the Open and Save Commands Understanding Routed Events The Role of Routed Bubbling Events Continuing or Halting Bubbling The Role of Routed Tunneling Events A Deeper Look at WPF APIs and Controls Working with the TabControl Building the Ink API Tab Designing the Toolbar The RadioButton Control Add the Save, Load, and Delete Buttons Add the InkCanvas Control Preview the Window Handling Events for the Ink API Tab Add Controls to the Toolbox The InkCanvas Control The ComboBox Control Saving, Loading, and Clearing InkCanvas Data Introducing the WPF Data-Binding Model Building the Data Binding Tab Establishing Data Bindings The DataContext Property Formatting the Bound Data Data Conversion Using IValueConverter Establishing Data Bindings in Code Building the DataGrid Tab Understanding the Role of Dependency Properties Examining an Existing Dependency Property Important Notes Regarding CLR Property Wrappers Building a Custom Dependency Property Adding a Data Validation Routine Responding to the Property Change Summary Chapter 27: WPF Graphics Rendering Services Understanding WPF’s Graphical Rendering Services WPF Graphical Rendering Options Rendering Graphical Data Using Shapes Adding Rectangles, Ellipses, and Lines to a Canvas Removing Rectangles, Ellipses, and Lines from a Canvas Working with Polylines and Polygons Working with Paths The Path Modeling “Mini-Language” WPF Brushes and Pens Configuring Brushes Using Visual Studio Configuring Brushes in Code Configuring Pens Applying Graphical Transformations A First Look at Transformations Transforming Your Canvas Data Working with the Visual Studio Transform Editor Building the Initial Layout Applying Transformations at Design Time Transforming the Canvas in Code Rendering Graphical Data Using Drawings and Geometries Building a DrawingBrush Using Geometries Painting with the DrawingBrush Containing Drawing Types in a DrawingImage Working with Vector Images Converting a Sample Vector Graphic File into XAML Importing the Graphical Data into a WPF Project Interacting with the Sign Rendering Graphical Data Using the Visual Layer The Visual Base Class and Derived Child Classes A First Look at Using the DrawingVisual Class Rendering Visual Data to a Custom Layout Manager Responding to Hit-Test Operations Summary Chapter 28: WPF Resources, Animations, Styles, and Templates Understanding the WPF Resource System Working with Binary Resources Including Loose Resource Files in a Project Configuring the Loose Resources Programmatically Loading an Image Embedding Application Resources Working with Object (Logical) Resources The Role of the Resources Property Defining Window-wide Resources The {StaticResource} Markup Extension The {DynamicResource} Markup Extension Application-Level Resources Defining Merged Resource Dictionaries Defining a Resource-Only Assembly Understanding WPF’s Animation Services The Role of the Animation Class Types The To, From, and By Properties The Role of the Timeline Base Class Authoring an Animation in C# Code Controlling the Pace of an Animation Reversing and Looping an Animation Authoring Animations in XAML The Role of Storyboards The Role of Event Triggers Animation Using Discrete Key Frames Understanding the Role of WPF Styles Defining and Applying a Style Overriding Style Settings The Effect of TargetType on Styles Subclassing Existing Styles Defining Styles with Triggers Defining Styles with Multiple Triggers Animated Styles Assigning Styles Programmatically Logical Trees, Visual Trees, and Default Templates Programmatically Inspecting a Logical Tree Programmatically Inspecting a Visual Tree Programmatically Inspecting a Control’s Default Template Building a Control Template with the Trigger Framework Templates as Resources Incorporating Visual Cues Using Triggers The Role of the {TemplateBinding} Markup Extension The Role of ContentPresenter Incorporating Templates into Styles Summary Chapter 29: WPF Notifications, Validations, Commands, and MVVM Introducing Model-View-ViewModel The Model The View The View Model Anemic Models or Anemic View Models The WPF Binding Notification System Observable Models and Collections Adding Bindings and Data Programmatically Changing the Vehicle Data Observable Models Using nameof Observable Collections Using the ObservableCollections Class Implementing a Dirty Flag Updating the Source Through UI Interaction Wrapping Up Notifications and Observables WPF Validations Updating the Sample for the Validation Examples The Validation Class Validation Options Notify on Exceptions IDataErrorInfo INotifyDataErrorInfo Implement the Supporting Code Use INotifyDataErrorInfo for Validations Combine IDataErrorInfo with INotifyDataErrorInfo for Validations Show All Errors Move the Support Code to a Base Class Leverage Data Annotations with WPF Add Data Annotations to the Model Check for Data Annotation–Based Validation Errors Customizing the ErrorTemplate Wrapping Up Validations Creating Custom Commands Implementing the ICommand Interface Adding the ChangeColorCommand Attaching the Command to the CommandManager Updating MainWindow.xaml.cs Updating MainWindow.xaml Testing the Application Creating the CommandBase Class Adding the AddCarCommand Class Updating MainWindow.xaml.cs Updating MainWindow.xaml Updating ChangeColorCommand RelayCommands Creating the Base RelayCommand Creating RelayCommand<T> Updating MainWindow.xaml.cs Adding and Implementing the Delete Car Button Wrapping Up Commands Migrate Code and Data to a View Model Moving the MainWindow.xaml.cs Code Updating the MainWindow Code and Markup Updating the Control Markup Wrapping Up View Models Updating AutoLot.Dal for MVVM Summary Chapter 30: Introducing ASP.NET Core A Quick Look Back at ASP.NET MVC Introducing the MVC Pattern The Model The View The Controller ASP.NET Core and the MVC Pattern ASP.NET Core and .NET Core One Framework, Many Uses Create and Configure the Solution and Projects Using Visual Studio 2022 Create the Solution and Projects Add in AutoLot.Models and AutoLot.Dal Add the Project References Add the NuGet Packages Using the Command Line Update the Entity Framework Core Package Reference Disable Nullable Reference Types For All Projects Create a GlobalUsing.cs Class in Each Project Running ASP.NET Core Applications Using Visual Studio Using Visual Studio Code Using the Command Line or Terminal Window Changing Code While Debugging Debugging ASP.NET Core Applications Attaching with Visual Studio Attaching with Visual Studio Code Update the AutoLot.Api and AutoLot.Web Kestrel Ports ASP.NET Core Concepts from MVC/Web API Convention over Configuration Naming Conventions Controllers and Actions (MVC Based Web Apps and RESTful Services) The Controller Class The ControllerBase Class Actions Antiforgery Tokens Opting In (MVC Style Web Apps) Opting Out (Razor Page Web Apps) Directory Structure Conventions The Controllers Folder The Views Folder The Shared Folder The Pages Folder The Shared Folder The Areas Folder The wwwroot Folder Routing URL Patterns and Route Tokens Handling Duplicate C# Method Signatures Custom Route Tokens Route Token Constraints Conventional Routing (MVC Style Web Apps) Area Routes Named Routes Attribute Routing (MVC Style Web Apps and RESTful Services) Razor Page Routing Routing and HTTP Verbs HTTP Verbs in MVC Styled Web Application Attribute Routing HTTP Verbs in RESTful Service Routing HTTP Verbs in Razor Page Routing Redirecting Using Routing Model Binding The ModelState Dictionary Adding Custom Errors to the ModelState Dictionary Clearing the ModelState Dictionary Implicit Model Binding Explicit Model Binding Property Model Binding Handling Property Name Prefixes Preventing Over Posting Controlling Model Binding Sources in ASP.NET Core Model Validation Explicit Model Validation Filters Authorization Filters Resource Filters Action Filters Page Filters Exception Filters Result Filters Summary Chapter 31: Diving Into ASP.NET Core What’s New in ASP.NET Core Razor Pages The Razor Page File The PageModel Class Page Handler Methods Environmental Awareness Determining the Runtime Environment The WebAppBuilder and WebApp The Program.cs File with RESTful Services The Program.cs File with MVC Style Applications The Program.cs File with Razor Page Based Applications Application Configuration Built-in Dependency Injection Adding Web App Support To The Dependency Injection Container Adding Derived DbContext Classes into the DI Container Adding Custom Services To The Dependency Injection Container Dependency Hierarchies Injecting Dependencies Getting Dependencies in Program.cs Build the Shared Data Services The Interfaces The AutoLot.Dal Direct Implementation The API Initial Implementation Adding the Data Services to the DI Container The Options Pattern in ASP.NET Core Using the Options Pattern The HTTP Client Factory Basic Usage Named Clients Typed Clients The AutoLot API Service Wrapper Update the Application Configuration Create the ApiServiceSettings Class Register the ApiServiceSettings Class The API Service Wrapper Base Class and Interface The IApiServiceWrapperBase Interface The ApiServiceWrapperBase Class Configuring the HttpClient in the Constructor The Internal Support Methods The Post and Put Helper Methods The HTTP Delete Helper Method Call The HTTP Get Calls The HTTP Post Call The HTTP Put Call The HTTP Delete Call The Entity Specific Interfaces The Entity Specific Classes Complete the API Data Services Complete the ApiDataServiceBase Class Complete the Entity Specific Classes Deploying ASP.NET Core Applications Lightweight and Modular HTTP Request Pipeline Logging Add Logging with Serilog The Logging Settings The Logging Configuration The AutoLot Logging Framework The IAppLogging Interface The AppLogging Class Final Configuration Add Logging to the Data Services Update the Base Classes Update the Entity Specific Data Services Classes Test-Drive the Logging Framework String Utilities Summary Chapter 32: RESTful Services with ASP.NET Core Introducing ASP.NET Core RESTful Services Controller Actions with RESTful Services Formatted JSON Response Results Configuring JSON Handling The ApiController Attribute Attribute Routing Requirement Automatic 400 Responses Binding Source Parameter Inference Problem Details for Error Status Codes Reset the Settings API Versioning Microsoft’s REST API Guidelines Add Versioning NuGet Packages The ApiVersion Class Add API Version Support Update the Top Level Statements API Versions and Naming Convention Updates The API Version Attributes Version Interleaving Controller Splitting Query String Version Requests and Routing Attribute Precedence Getting the API Version in Requests Route Updates for URL Segment Versioning URL Segment Versioning and Version Status Values Deprecating Versions Unsupported Version Requests Add the API Version Explorer Update the Swagger/OpenAPI Settings Add the XML Documentation File The Application’s Swagger Settings The SwaggerDefaultValues Operation Filter The ConfigureSwaggerOptions Class Update the SwaggerGen() Call Update the UseSwaggerUI() Call View the Results in the Swagger UI Additional Documentation Options for API Endpoints Building The BaseCrudController The Constructor The Get Methods The UpdateOne Method The AddOne Method The DeleteOne Method The CarsController The Remaining Controllers Exception Filters Create the CustomExceptionFilter Apply the Filter Test the Exception Filter Add Cross-Origin Requests Support Create a CORS Policy Add the CORS Policy to the HTTP Pipeline Handling Basic Authentication Add and Configure the Security Information Build the Basic Authentication Handler Register the Basic Authentication Handler and Secure the Controllers Summary Chapter 33: Web Applications with MVC Introducing the “V” in ASP.NET Core ViewResults and Action Methods The Razor View Engine and Razor Syntax Views The Views Directory The Shared Directory The DisplayTemplates Folder The DateTime Display Template The Car Display Template The Car with Color Display Template The EditorTemplates Folder The Car Edit Template View CSS Isolation Layouts Specifying the Layout for a View Partial Views Split the Layout into Partials Create the Partials The Head Partial The Menu Partial The JavaScript Files Partial Sending Data to Views Strongly Typed Views and View Models ViewBag, ViewData, and TempData Injecting Data Managing Client-Side Libraries Install Library Manager As a .NET Global Tool Add Client-Side Libraries to AutoLot.Mvc Add the libman.json File Visual Studio Command Line Update the libman.json File Update the JavaScript and CSS References Bundling and Minification Bundling Minification The WebOptimizer Solution Add and Configure WebOptimizer Update _ViewImports.cshtml The Controllers The HomeController The BaseCrudController The IndexAsync Method The DetailsAsync Method The CreateAsync Action Methods The Get Method The Post Method The EditAsync Action Methods The Get Method The Post Method The DeleteAsync Action Methods The Delete Get Method The Delete Post Method Using a BindProperty The CarsController Areas Area Routing The MakesController Area Controller _ViewImports and _ViewStart Tag Helpers Enabling Tag Helpers The Form Tag Helper The Cars Create Form The Form Action Button/Image Tag Helper The Anchor Tag Helper The Input Tag Helper The TextArea Tag Helper The Select Tag Helper The Validation Tag Helpers The Environment Tag Helper The Link Tag Helper The Script Tag Helper The Image Tag Helper Custom Tag Helpers Set the Foundation Update Program.cs Create the Base Class The Item Details Tag Helper The Item Delete Tag Helper The Item Edit Tag Helper The Item Create Tag Helper The Item List Tag Helper Making Custom Tag Helpers Visible HTML Helpers The DisplayFor HTML Helper The DisplayForModel HTML Helper The EditorFor and EditorForModel HTML Helpers The Car Views The Car List Partial View The Index View The ByMake View The Details View The Create View The Edit View The Delete View View Components The Server-Side Code Build the Partial View Invoking View Components Updating the Menu Custom Validation Attributes Set the Stage The ViewModel The View The Validation Action Methods The Validation Menu Item Server-Side Validation The MustBeGreaterThanZero Validation Attribute The MustNotBeGreaterThan Validation Attribute Client-Side Validation Client-Side Error Formatting The MustBeGreaterThanZero Validation Attribute The MustNotBeGreaterThan Validation Attribute Update the Validation Scripts Partial General Data Protection Regulation Support Add Cookie Policy Support The Cookie Support Partial View Menu Support to Accept/Withdraw Cookie Policy Consent Finish the Admin Area Run AutoLot.Mvc and AutoLot.Api Together Using Visual Studio Using the Command Line Summary Chapter 34: Web Applications using Razor Pages Anatomy of a Razor Page Razor Page PageModel Classes and Page Handler Methods Razor Page Views Razor Views The _ViewStart and _ViewImports Views The Shared Directory The DisplayTemplates Folder The DateTime Display Template The Car Display Template The Car with Color Display Template The EditorTemplates Folder The Car Edit Template View CSS Isolation Layouts Injecting Data Partial Views Create the Partials Sending Data to Partials ViewBag, ViewData, and TempData Add Client-Side Libraries to AutoLot.Web Add the libman.json File Visual Studio Command Line Update the libman.json File Update the JavaScript and CSS References Add and Configure WebOptimizer Tag Helpers Enabling Tag Helpers The Form Tag Helper The Form Action Button/Image Tag Helper The Anchor Tag Helper Custom Tag Helpers Update Program.cs Create the Base Class The Item Details Tag Helper The Item Delete Tag Helper The Item Edit Tag Helper The Item Create Tag Helper The Item List Tag Helper Making Custom Tag Helpers Visible The Cars Razor Pages The BasePageModel Class The Index Razor Page The Car List Partial View The Index Razor Page View The Details Razor Page The Details Razor Page View The Create Razor Page The Create Razor Page View The Edit Razor Page The Edit Razor Page View The Delete Razor Page The Delete Razor Page View View Components Build the Partial View Areas Area Routing with Razor Pages _ViewImports and _ViewStart The Makes Razor Pages The Make DisplayTemplate The Make EditorTemplate The Index Razor Page The Index Razor Page View The Details Razor Page The Details Razor Page View The Create Razor Page The Create Razor Page View The Edit Razor Page The Edit Razor Page View The Delete Razor Page The Delete Razor Page View Add the Area Menu Item Custom Validation Attributes General Data Protection Regulation Support The Cookie Support Partial View Menu Support to Accept/Withdraw Cookie Policy Consent Summary Index
Donate to keep this site alive
How to download source code?
1. Go to: https://github.com/Apress
2. In the Find a repository… box, search the book title: Pro C# 10 with .NET 6: Foundational Principles and Practices in Programming
, sometime you may not get the results, please search the main title.
3. Click the book title in the search results.
3. Click Code to download.
1. Disable the AdBlock plugin. Otherwise, you may not get any links.
2. Solve the CAPTCHA.
3. Click download link.
4. Lead to download server to download.