Pro C# 9 with .NET 5: Foundational Principles and Practices in Programming. 10 Ed

Pro C# 9 with .NET 5: Foundational Principles and Practices in Programming. 10 Ed

Pro C# 9 with .NET 5: Foundational Principles and Practices in Programming. 10 Ed
Автор: Japikse Philip
Дата выхода: 2021
Издательство: Apress Media, LLC.
Количество страниц: 1383
Размер файла: 9.5 MB
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы

Table of Contents....5

About the Authors....45

About the Technical Reviewers....46

Acknowledgments....47

Introduction....48

Part I: Introducing C# and .NET 5....56

Chapter 1: Introducing C# and .NET (Core) 5....57

Exploring Some Key Benefits of the .NET Core Platform....58

Understanding the .NET Core Support Lifecycle....58

Previewing the Building Blocks of the .NET Core Platform (.NET Runtime, CTS, and CLS)....59

The Role of the Base Class Libraries....60

The Role of .NET Standard....60

What C# Brings to the Table....60

Major Features in Prior Releases....61

New Features in C# 9....64

Managed vs. Unmanaged Code....64

Using Additional .NET Core–Aware Programming Languages....64

Getting an Overview of .NET Assemblies....65

The Role of the Common Intermediate Language....65

Benefits of CIL....68

Compiling CIL to Platform-Specific Instructions....69

Precompiling CIL to Platform-Specific Instructions....69

The Role of .NET Core Type Metadata....69

The Role of the Assembly Manifest....70

Understanding the Common Type System....71

CTS Class Types....71

CTS Interface Types....72

CTS Structure Types....72

CTS Enumeration Types....73

CTS Delegate Types....73

CTS Type Members....73

Intrinsic CTS Data Types....74

Understanding the Common Language Specification....75

Ensuring CLS Compliance....76

Understanding the .NET Core Runtime....76

Distinguishing Between Assembly, Namespace, and Type....77

Accessing a Namespace Programmatically....78

Referencing External Assemblies....79

Exploring an Assembly Using ildasm.exe....79

Summary....80

Chapter 2: Building C# Applications....81

Installing .NET 5....81

Understanding the .NET 5 Version Numbering Scheme....81

Confirming the .NET 5 Install....82

Using an Earlier Version of the .NET (Core) SDK....83

Building .NET Core Applications with Visual Studio....83

Installing Visual Studio 2019 (Windows)....83

Taking Visual Studio 2019 for a Test-Drive....85

Using the New Project Dialog and C# Code Editor....85

Changing the Target .NET Core Framework....87

Using C# 9 Features....88

Running and Debugging Your Project....89

Using Solution Explorer....90

Using the Visual Class Designer....91

Building .NET Core Applications with Visual Studio Code....95

Taking Visual Studio Code for a Test-Drive....95

Creating Solutions and Projects....96

Exploring the Visual Studio Code Workspace....96

Restoring Packages, Building and Running Programs....97

Debugging Your Project....98

Finding the .NET Core and C# Documentation....99

Summary....99

Part II: Core C# Programming....100

Chapter 3: Core C# Programming Constructs, Part 1....101

Breaking Down a Simple C# Program....101

Using Variations of the Main() Method (Updated 7.1)....103

Using Top-Level Statements (New 9.0)....104

Specifying an Application Error Code (Updated 9.0)....105

Processing Command-Line Arguments (Updated 9.0)....107

Specifying Command-Line Arguments with Visual Studio....109

An Interesting Aside: Some Additional Members of the System.Environment Class....110

Using the System.Console Class....111

Performing Basic Input and Output (I/O) with the Console Class....112

Formatting Console Output....113

Formatting Numerical Data....114

Formatting Numerical Data Beyond Console Applications....115

Working with System Data Types and Corresponding C# Keywords....115

Understanding Variable Declaration and Initialization....117

The default Literal (New 7.1)....118

Using Intrinsic Data Types and the new Operator (Updated 9.0)....119

Understanding the Data Type Class Hierarchy....119

Understanding the Members of Numerical Data Types....121

Understanding the Members of System.Boolean....122

Understanding the Members of System.Char....122

Parsing Values from String Data....123

Using TryParse to Parse Values from String Data....123

Using System.DateTime and System.TimeSpan....124

Working with the System.Numerics Namespace....124

Using Digit Separators (New 7.0)....126

Using Binary Literals (New 7.0/7.2)....126

Working with String Data....127

Performing Basic String Manipulation....127

Performing String Concatenation....128

Using Escape Characters....129

Performing String Interpolation....130

Defining Verbatim Strings (Updated 8.0)....131

Working with Strings and Equality....131

Modifying String Comparison Behavior....132

Strings Are Immutable....133

Using the System.Text.StringBuilder Type....135

Narrowing and Widening Data Type Conversions....136

Using the checked Keyword....138

Setting Project-wide Overflow Checking....140

Setting Project-wide Overflow Checking (Visual Studio)....140

Using the unchecked Keyword....141

Understanding Implicitly Typed Local Variables....141

Declaring Numerics Implicitly....143

Understanding Restrictions on Implicitly Typed Variables....143

Implicit Typed Data Is Strongly Typed Data....144

Understanding the Usefulness of Implicitly Typed Local Variables....145

Working with C# Iteration Constructs....146

Using the for Loop....146

Using the foreach Loop....147

Using Implicit Typing Within foreach Constructs....147

Using the while and do/while Looping Constructs....148

A Quick Discussion About Scope....148

Working with Decision Constructs and the Relational/Equality Operators....149

Using the if/else Statement....149

Using Equality and Relational Operators....150

Using if/else with Pattern Matching (New 7.0)....151

Making Pattern Matching Improvements (New 9.0)....151

Using the Conditional Operator (Updated 7.2, 9.0)....152

Using Logical Operators....154

Using the switch Statement....154

Performing switch Statement Pattern Matching (New 7.0, Updated 9.0)....157

Using switch Expressions (New 8.0)....160

Summary....161

Chapter 4: Core C# Programming Constructs, Part 2....162

Understanding C# Arrays....162

Looking at the C# Array Initialization Syntax....163

Understanding Implicitly Typed Local Arrays....164

Defining an Array of Objects....165

Working with Multidimensional Arrays....165

Using Arrays As Arguments or Return Values....167

Using the System.Array Base Class....168

Using Indices and Ranges (New 8.0)....169

Understanding Methods....171

Understanding Expression-Bodied Members....172

Understanding Local Functions (New 7.0, Updated 9.0)....172

Understanding Static Local Functions (New 8.0)....173

Understanding Method Parameters....174

Understanding Method Parameter Modifiers....174

Understanding the Default Parameter-Passing Behavior....175

The Default Behavior for Value Types....175

The Default Behavior for Reference Types....176

Using the out Modifier (Updated 7.0)....176

Discarding out Parameters (New 7.0)....178

The out Modifier in Constructors and Initializers (New 7.3)....178

Using the ref Modifier....178

Using the in Modifier (New 7.2)....179

Using the params Modifier....180

Defining Optional Parameters....181

Using Named Arguments (Updated 7.2)....182

Understanding Method Overloading....184

Understanding the enum Type....186

Controlling the Underlying Storage for an enum....188

Declaring enum Variables....188

Using the System.Enum Type....189

Dynamically Discovering an enum’s Name-Value Pairs....190

Using Enums, Flags, and Bitwise Operations....191

Understanding the Structure (aka Value Type)....193

Creating Structure Variables....195

Using Read-Only Structs (New 7.2)....196

Using Read-Only Members (New 8.0)....196

Using ref Structs (New 7.2)....197

Using Disposable ref Structs (New 8.0)....198

Understanding Value Types and Reference Types....198

Using Value Types, Reference Types, and the Assignment Operator....199

Using Value Types Containing Reference Types....201

Passing Reference Types by Value....203

Passing Reference Types by Reference....204

Final Details Regarding Value Types and Reference Types....205

Understanding C# Nullable Types....206

Using Nullable Value Types....207

Using Nullable Reference Types (New 8.0)....208

Opting in for Nullable Reference Types....208

Nullable Reference Types in Action....209

Migration Considerations....210

Operating on Nullable Types....210

The Null-Coalescing Operator....210

The Null-Coalescing Assignment Operator (New 8.0)....211

The Null Conditional Operator....211

Understanding Tuples (New/Updated 7.0)....212

Getting Started with Tuples....213

Using Inferred Variable Names (Updated 7.1)....214

Understanding Tuple Equality/Inequality (New 7.3)....214

Understanding Tuples as Method Return Values....215

Understanding Discards with Tuples....215

Understanding Tuple Pattern Matching switch Expressions (New 8.0)....216

Deconstructing Tuples....216

Deconstructing Tuples with Positional Pattern Matching (New 8.0)....217

Summary....218

Part III: Object Oriented Programming with C#....219

Chapter 5: Understanding Encapsulation....220

Introducing the C# Class Type....220

Allocating Objects with the new Keyword....222

Understanding Constructors....223

Understanding the Role of the Default Constructor....223

Defining Custom Constructors....224

Constructors As Expression-Bodied Members (New 7.0)....225

Constructors with out Parameters (New 7.3)....225

Understanding the Default Constructor Revisited....226

Understanding the Role of the this Keyword....227

Chaining Constructor Calls Using this....228

Observing Constructor Flow....231

Revisiting Optional Arguments....232

Understanding the static Keyword....233

Defining Static Field Data....234

Defining Static Methods....236

Defining Static Constructors....237

Defining Static Classes....239

Importing Static Members via the C# using Keyword....240

Defining the Pillars of OOP....241

Understanding the Role of Encapsulation....241

Understanding the Role of Inheritance....242

Understanding the Role of Polymorphism....243

Understanding C# Access Modifiers (Updated 7.2)....245

Using the Default Access Modifiers....245

Using Access Modifiers and Nested Types....246

Understanding the First Pillar: C#’s Encapsulation Services....246

Encapsulation Using Traditional Accessors and Mutators....247

Encapsulation Using Properties....250

Properties As Expression-Bodied Members (New 7.0)....253

Using Properties Within a Class Definition....253

Properties Read-Only Properties....254

Properties Write-Only Properties....255

Mixing Private and Public Get/Set Methods on Properties....255

Revisiting the static Keyword: Defining Static Properties....256

Pattern Matching with Property Patterns (New 8.0)....256

Understanding Automatic Properties....258

Interacting with Automatic Properties....259

Properties Automatic Properties and Default Values....260

Initializing Automatic Properties....262

Understanding Object Initialization....262

Looking at the Object Initialization Syntax....263

Using init-Only Setters (New 9.0)....264

Calling Custom Constructors with Initialization Syntax....265

Initializing Data with Initialization Syntax....266

Working with Constant and Read-Only Field Data....267

Understanding Constant Field Data....268

Understanding Read-Only Fields....269

Understanding Static Read-Only Fields....270

Understanding Partial Classes....270

Using Records (New 9.0)....271

Understanding Equality with Record Types....274

Summary....276

Chapter 6: Understanding Inheritance and Polymorphism....277

Understanding the Basic Mechanics of Inheritance....277

Specifying the Parent Class of an Existing Class....278

Regarding Multiple Base Classes....280

Using the sealed Keyword....280

Revisiting Visual Studio Class Diagrams....281

Understanding the Second Pillar of OOP: The Details of Inheritance....283

Calling Base Class Constructors with the base Keyword....284

Keeping Family Secrets: The protected Keyword....286

Adding a sealed Class....287

Understanding Inheritance with Record Types (New 9.0)....288

Equality with Inherited Record Types....290

Programming for Containment/Delegation....291

Understanding Nested Type Definitions....292

Understanding the Third Pillar of OOP: C#’s Polymorphic Support....294

Using the virtual and override Keywords....295

Overriding Virtual Members with Visual Studio/Visual Studio Code....297

Sealing Virtual Members....297

Understanding Abstract Classes....298

Understanding the Polymorphic Interface....300

Understanding Member Shadowing....303

Understanding Base Class/Derived Class Casting Rules....305

Using the C# as Keyword....307

Using the C# is Keyword (Updated 7.0, 9.0)....308

Discards with the is Keyword (New 7.0)....309

Revisiting Pattern Matching (New 7.0)....310

Discards with switch Statements (New 7.0)....311

Understanding the Super Parent Class: System.Object....311

Overriding System.Object.ToString()....314

Overriding System.Object.Equals()....314

Overriding System.Object.GetHashCode()....315

Testing Your Modified Person Class....316

Using the Static Members of System.Object....317

Summary....318

Chapter 7: Understanding Structured Exception Handling....319

Ode to Errors, Bugs, and Exceptions....319

The Role of .NET Exception Handling....320

The Building Blocks of .NET Exception Handling....321

The System.Exception Base Class....321

The Simplest Possible Example....322

Throwing a General Exception....325

Catching Exceptions....326

Throw As Expression (New 7.0)....328

Configuring the State of an Exception....328

The TargetSite Property....328

The StackTrace Property....329

The HelpLink Property....329

The Data Property....330

System-Level Exceptions (System.SystemException)....332

Application-Level Exceptions (System.ApplicationException)....333

Building Custom Exceptions, Take 1....333

Building Custom Exceptions, Take 2....335

Building Custom Exceptions, Take 3....336

Processing Multiple Exceptions....337

General catch Statements....340

Rethrowing Exceptions....340

Inner Exceptions....341

The finally Block....342

Exception Filters....342

Debugging Unhandled Exceptions Using Visual Studio....343

Summary....344

Chapter 8: Working with Interfaces....345

Understanding Interface Types....345

Interface Types vs. Abstract Base Classes....346

Defining Custom Interfaces....349

Implementing an Interface....350

Invoking Interface Members at the Object Level....352

Obtaining Interface References: The as Keyword....353

Obtaining Interface References: The is Keyword (Updated 7.0)....354

Default Implementations (New 8.0)....354

Static Constructors and Members (New 8.0)....356

Interfaces as Parameters....356

Interfaces as Return Values....358

Arrays of Interface Types....359

Implementing Interfaces Using Automatically....360

Explicit Interface Implementation....362

Designing Interface Hierarchies....365

Interface Hierarchies with Default Implementations (New 8.0)....366

Multiple Inheritance with Interface Types....368

The IEnumerable and IEnumerator Interfaces....370

Building Iterator Methods with the yield Keyword....373

Guard Clauses with Local Functions (New 7.0)....374

Building a Named Iterator....375

The ICloneable Interface....377

A More Elaborate Cloning Example....379

The IComparable Interface....382

Specifying Multiple Sort Orders with IComparer....385

Custom Properties and Custom Sort Types....386

Summary....387

Chapter 9: Understanding Object Lifetime....388

Classes, Objects, and References....388

The Basics of Object Lifetime....390

The CIL of new....390

Setting Object References to null....392

Determining If an Object Is Live....392

Understanding Object Generations....394

Ephemeral Generations and Segments....395

Garbage Collection Types....396

Background Garbage Collection....396

The System.GC Type....396

Forcing a Garbage Collection....398

Building Finalizable Objects....401

Overriding System.Object.Finalize()....402

Detailing the Finalization Process....404

Building Disposable Objects....404

Reusing the C# using Keyword....406

Using Declarations (New 8.0)....408

Building Finalizable and Disposable Types....409

A Formalized Disposal Pattern....409

Understanding Lazy Object Instantiation....411

Customizing the Creation of the Lazy Data....414

Summary....415

Part IV: Advanced C# Programming....416

Chapter 10: Collections and Generics....417

The Motivation for Collection Classes....417

The System.Collections Namespace....419

An Illustrative Example: Working with the ArrayList....420

A Survey of System.Collections.Specialized Namespace....420

The Problems of Nongeneric Collections....421

The Issue of Performance....422

The Issue of Type Safety....425

A First Look at Generic CollectionsT....429

The Role of Generic Type Parameters....430

Specifying Type Parameters for Generic Classes/Structures....431

Specifying Type Parameters for Generic Members....432

Specifying Type Parameters for Generic Interfaces....433

The System.Collections.Generic Namespace....434

Understanding Collection Initialization Syntax....435

Working with the List Class....437

Working with the Stack Class....439

Working with the Queue Class....440

Working with the SortedSet Class....441

Working with the Dictionary Class....443

The System.Collections.ObjectModel Namespace....444

Working with ObservableCollection....444

Creating Custom Generic Methods....446

Inference of Type Parameters....448

Creating Custom Generic Structures and Classes....449

Default Value Expressions with Generics....450

Default Literal Expressions (New 7.1)....451

Pattern Matching with Generics (New 7.1)....452

Constraining Type Parameters....452

Examples of Using the where Keyword....453

The Lack of Operator Constraints....454

Summary....455

Chapter 11: Advanced C# Language Features....456

Understanding Indexer Methods....456

Indexing Data Using String Values....458

Overloading Indexer Methods....460

Indexers with Multiple Dimensions....460

Indexer Definitions on Interface Types....461

Understanding Operator Overloading....462

Overloading Binary Operators....463

What of the += and –= Operators?....465

Overloading Unary Operators....465

Overloading Equality Operators....466

Overloading Comparison Operators....467

Final Thoughts Regarding Operator Overloading....468

Understanding Custom Type Conversions....468

Recall: Numerical Conversions....468

Recall: Conversions Among Related Class Types....469

Creating Custom Conversion Routines....470

Additional Explicit Conversions for the Square Type....472

Defining Implicit Conversion Routines....473

Understanding Extension Methods....474

Defining Extension Methods....475

Invoking Extension Methods....476

Importing Extension Methods....477

Extending Types Implementing Specific Interfaces....477

Extension Method GetEnumerator Support (New 9.0)....479

Understanding Anonymous Types....481

Defining an Anonymous Type....481

The Internal Representation of Anonymous Types....482

The Implementation of ToString() and GetHashCode()....484

The Semantics of Equality for Anonymous Types....484

Anonymous Types Containing Anonymous Types....486

Working with Pointer Types....487

The unsafe Keyword....488

Working with the * and & Operators....490

An Unsafe (and Safe) Swap Function....491

Field Access via Pointers (the -> Operator)....492

The stackalloc Keyword....493

Pinning a Type via the fixed Keyword....493

The sizeof Keyword....494

Summary....495

Chapter 12: Delegates, Events, and Lambda Expressions....496

Understanding the Delegate Type....497

Defining a Delegate Type in C#....497

The System.MulticastDelegate and System.Delegate Base Classes....499

The Simplest Possible Delegate Example....501

Investigating a Delegate Object....503

Sending Object State Notifications Using Delegates....504

Enabling Multicasting....507

Removing Targets from a Delegate’s Invocation List....509

Method Group Conversion Syntax....510

Understanding Generic Delegates....511

The Generic Action<> and Func<> Delegates....512

Understanding C# Events....514

The C# event Keyword....516

Events Under the Hood....517

Listening to Incoming Events....518

Simplifying Event Registration Using Visual Studio....519

Creating Custom Event Arguments....521

The Generic EventHandler Delegate....523

Understanding C# Anonymous Methods....523

Accessing Local Variables....525

Using static with Anonymous Methods (New 9.0)....526

Discards with Anonymous Methods (New 9.0)....527

Understanding Lambda Expressions....527

Dissecting a Lambda Expression....530

Processing Arguments Within Multiple Statements....531

Lambda Expressions with Multiple (or Zero) Parameters....532

Using static with Lambda Expressions (New 9.0)....533

Discards with Lambda Expressions (New 9.0)....534

Retrofitting the CarEvents Example Using Lambda Expressions....534

Lambdas and Expression-Bodied Members (Updated 7.0)....535

Summary....536

Chapter 13: LINQ to Objects....537

LINQ-Specific Programming Constructs....537

Implicit Typing of Local Variables....538

Object and Collection Initialization Syntax....539

Lambda Expressions....539

Extension Methods....540

Anonymous Types....541

Understanding the Role of LINQ....541

LINQ Expressions Are Strongly Typed....542

The Core LINQ Assemblies....542

Applying LINQ Queries to Primitive Arrays....542

Once Again, Using Extension Methods....544

Once Again, Without LINQ....545

Reflecting Over a LINQ Result Set....545

LINQ and Implicitly Typed Local Variables....547

LINQ and Extension Methods....548

The Role of Deferred Execution....549

The Role of Immediate Execution....550

Returning the Result of a LINQ Query....552

Returning LINQ Results via Immediate Execution....553

Applying LINQ Queries to Collection Objects....554

Accessing Contained Subobjects....554

Applying LINQ Queries to Nongeneric Collections....555

Filtering Data Using OfType()....556

Investigating the C# LINQ Query Operators....557

Basic Selection Syntax....558

Obtaining Subsets of Data....559

Projecting New Data Types....560

Projecting to Different Data Types....561

Obtaining Counts Using Enumerable....562

Reversing Result Sets....562

Sorting Expressions....562

LINQ As a Better Venn Diagramming Tool....563

Removing Duplicates....565

LINQ Aggregation Operations....565

The Internal Representation of LINQ Query Statements....566

Building Query Expressions with Query Operators (Revisited)....567

Building Query Expressions Using the Enumerable Type and Lambda Expressions....567

Building Query Expressions Using the Enumerable Type and Anonymous Methods....569

Building Query Expressions Using the Enumerable Type and Raw Delegates....569

Summary....571

Chapter 14: Processes, AppDomains, and Load Contexts....572

The Role of a Windows Process....572

The Role of Threads....573

Interacting with Processes Using .NET Core....574

Enumerating Running Processes....576

Investigating a Specific Process....577

Investigating a Process’s Thread Set....578

Investigating a Process’s Module Set....579

Starting and Stopping Processes Programmatically....581

Controlling Process Startup Using the ProcessStartInfo Class....582

Leveraging OS Verbs with ProcessStartInfo....583

Understanding .NET Application Domains....584

The System.AppDomain Class....585

Interacting with the Default Application Domain....585

Enumerating Loaded Assemblies....586

Assembly Isolation with Application Load Contexts....587

Summarizing Processes, AppDomains, and Load Contexts....590

Summary....591

Chapter 15: Multithreaded, Parallel, and Async Programming....592

The Process/AppDomain/Context/Thread Relationship....592

The Problem of Concurrency....593

The Role of Thread Synchronization....594

The System.Threading Namespace....594

The System.Threading.Thread Class....595

Obtaining Statistics About the Current Thread of Execution....596

The Name Property....597

The Priority Property....597

Manually Creating Secondary Threads....598

Working with the ThreadStart Delegate....598

Working with the ParameterizedThreadStart Delegate....600

The AutoResetEvent Class....601

Foreground Threads and Background Threads....602

The Issue of Concurrency....603

Synchronization Using the C# lock Keyword....605

Synchronization Using the System.Threading.Monitor Type....607

Synchronization Using the System.Threading.Interlocked Type....608

Programming with Timer Callbacks....609

Using a Stand-Alone Discard (New 7.0)....610

Understanding the ThreadPool....611

Parallel Programming Using the Task Parallel Library....612

The System.Threading.Tasks Namespace....612

The Role of the Parallel Class....612

Data Parallelism with the Parallel Class....613

Accessing UI Elements on Secondary Threads....617

The Task Class....618

Handling Cancellation Request....618

Task Parallelism Using the Parallel Class....620

Parallel LINQ Queries (PLINQ)....623

Opting in to a PLINQ Query....624

Cancelling a PLINQ Query....624

Async Calls with the async/await....625

A First Look at the C# async and await Keywords (Updated 7.1, 9.0)....625

SynchronizationContext and async/await....627

The Role of ConfigureAwait....628

Naming Conventions for Asynchronous Methods....628

Void Async Methods....629

Awaitable Void Async Methods....629

“Fire-and-Forget” Void Async Methods....629

Async Methods with Multiple Awaits....630

Calling Async Methods from Non-async Methods....631

Await in catch and finally Blocks....632

Generalized Async Return Types (New 7.0)....632

Local Functions (New 7.0)....633

Cancelling async/await Operations....634

Asynchronous Streams (New 8.0)....636

Wrapping Up async and await....637

Summary....637

Part V: Programming with .NET Core Assemblies....638

Chapter 16: Building and Configuring Class Libraries....639

Defining Custom Namespaces....639

Resolving Name Clashes with Fully Qualified Names....641

Resolving Name Clashes with Aliases....642

Creating Nested Namespaces....643

Change the Root Namespace of Visual Studio....644

The Role of .NET Core Assemblies....645

Assemblies Promote Code Reuse....645

Assemblies Establish a Type Boundary....646

Assemblies Are Versionable Units....646

Assemblies Are Self-Describing....646

Understanding the Format of a .NET Core Assembly....646

Installing the C++ Profiling Tools....647

The Operating System (Windows) File Header....648

The CLR File Header....648

CIL Code, Type Metadata, and the Assembly Manifest....649

Optional Assembly Resources....650

Class Libraries vs. Console Applications....650

.NET Standard vs. .NET Core Class Libraries....650

Configuring Applications....651

Building and Consuming a .NET Core Class Library....652

Exploring the Manifest....655

Exploring the CIL....657

Exploring the Type Metadata....657

Building a C# Client Application....658

Building a Visual Basic Client Application....660

Cross-Language Inheritance in Action....660

Exposing internal Types to Other Assemblies....661

Using an Assembly Attribute....661

Using the Project File....662

NuGet and .NET Core....662

Packaging Assemblies with NuGet....662

Referencing NuGet Packages....664

Publishing Console Applications (Updated .NET 5)....665

Publishing Framework-Dependent Applications....665

Publishing Self-Contained Applications....666

Publishing Self-Contained Applications as a Single File....666

How .NET Core Locates Assemblies....667

Summary....668

Chapter 17: Type Reflection, Late Binding, and Attribute-Based Programming....669

The Necessity of Type Metadata....669

Viewing (Partial) Metadata for the EngineStateEnum Enumeration....670

Viewing (Partial) Metadata for the Car Type....671

Examining a TypeRef....672

Documenting the Defining Assembly....673

Documenting Referenced Assemblies....673

Documenting String Literals....674

Understanding Reflection....674

The System.Type Class....675

Obtaining a Type Reference Using System.Object.GetType()....676

Obtaining a Type Reference Using typeof()....676

Obtaining a Type Reference Using System.Type.GetType()....677

Building a Custom Metadata Viewer....677

Reflecting on Methods....678

Reflecting on Fields and Properties....678

Reflecting on Implemented Interfaces....679

Displaying Various Odds and Ends....679

Adding the Top-Level Statements....680

Reflecting on Static Types....681

Reflecting on Generic Types....682

Reflecting on Method Parameters and Return Values....682

Dynamically Loading Assemblies....683

Reflecting on Framework Assemblies....685

Understanding Late Binding....687

The System.Activator Class....687

Invoking Methods with No Parameters....689

Invoking Methods with Parameters....689

Understanding the Role of .NET Attributes....690

Attribute Consumers....691

Applying Attributes in C#....691

C# Attribute Shorthand Notation....692

Specifying Constructor Parameters for Attributes....693

The Obsolete Attribute in Action....693

Building Custom Attributes....694

Applying Custom Attributes....695

Named Property Syntax....696

Restricting Attribute Usage....696

Assembly-Level Attributes....697

Using the Project File for Assembly Attributes....698

Reflecting on Attributes Using Early Binding....699

Reflecting on Attributes Using Late Binding....700

Putting Reflection, Late Binding, and Custom Attributes in Perspective....701

Building an Extendable Application....702

Building the Multiproject ExtendableApp Solution....703

Creating the Solution and Projects with the CLI....703

Adding PostBuild Events into the Project Files....703

Creating the Solution and Projects with Visual Studio....703

Setting Project Build Dependencies....705

Adding PostBuild Events....705

Building CommonSnappableTypes.dll....706

Building the C# Snap-In....706

Building the Visual Basic Snap-In....707

Adding the Code for the ExtendableApp....707

Summary....709

Chapter 18: Dynamic Types and the Dynamic Language Runtime....710

The Role of the C# dynamic Keyword....710

Calling Members on Dynamically Declared Data....712

The Scope of the dynamic Keyword....714

Limitations of the dynamic Keyword....714

Practical Uses of the dynamic Keyword....715

The Role of the Dynamic Language Runtime....715

The Role of Expression Trees....716

Dynamic Runtime Lookup of Expression Trees....716

Simplifying Late-Bound Calls Using Dynamic Types....717

Leveraging the dynamic Keyword to Pass Arguments....718

Simplifying COM Interoperability Using Dynamic Data (Windows Only)....720

The Role of Primary Interop Assemblies....721

Embedding Interop Metadata....721

Common COM Interop Pain Points....723

COM Interop Using C# Dynamic Data....723

Summary....726

Chapter 19: Understanding CIL and the Role of Dynamic Assemblies....727

Motivations for Learning the Grammar of CIL....727

Examining CIL Directives, Attributes, and Opcodes....728

The Role of CIL Directives....729

The Role of CIL Attributes....729

The Role of CIL Opcodes....729

The CIL Opcode/CIL Mnemonic Distinction....730

Pushing and Popping: The Stack-Based Nature of CIL....731

Understanding Round-Trip Engineering....732

The Role of CIL Code Labels....735

Interacting with CIL: Modifying an *.il File....735

Compiling CIL Code....736

Understanding CIL Directives and Attributes....737

Specifying Externally Referenced Assemblies in CIL....737

Defining the Current Assembly in CIL....737

Defining Namespaces in CIL....738

Defining Class Types in CIL....739

Defining and Implementing Interfaces in CIL....740

Defining Structures in CIL....741

Defining Enums in CIL....741

Defining Generics in CIL....741

Compiling the CILTypes.il File....742

.NET Base Class Library, C#, and CIL Data Type Mappings....742

Defining Type Members in CIL....743

Defining Field Data in CIL....743

Defining Type Constructors in CIL....744

Defining Properties in CIL....745

Defining Member Parameters....745

Examining CIL Opcodes....746

The .maxstack Directive....748

Declaring Local Variables in CIL....748

Mapping Parameters to Local Variables in CIL....749

The Hidden this Reference....750

Representing Iteration Constructs in CIL....751

The Final Word on CIL....751

Understanding Dynamic Assemblies....752

Exploring the System.Reflection.Emit Namespace....752

The Role of the System.Reflection.Emit.ILGenerator....753

Emitting a Dynamic Assembly....754

Emitting the Assembly and Module Set....756

The Role of the ModuleBuilder Type....757

Emitting the HelloClass Type and the String Member Variable....758

Emitting the Constructors....758

Emitting the SayHello() Method....759

Using the Dynamically Generated Assembly....759

Summary....760

Part VI: File Handling, Object Serialization, and Data Access....761

Chapter 20: File I/O and Object Serialization....762

Exploring the System.IO Namespace....762

The Directory(Info) and File(Info) Types....763

The Abstract FileSystemInfo Base Class....764

Working with the DirectoryInfo Type....764

Enumerating Files with the DirectoryInfo Type....766

Creating Subdirectories with the DirectoryInfo Type....767

Working with the Directory Type....768

Working with the DriveInfo Class Type....769

Working with the FileInfo Class....770

The FileInfo.Create() Method....771

The FileInfo.Open() Method....772

The FileInfo.OpenRead() and FileInfo.OpenWrite() Methods....773

The FileInfo.OpenText() Method....774

The FileInfo.CreateText() and FileInfo.AppendText() Methods....774

Working with the File Type....775

Additional File-centric Members....775

The Abstract Stream Class....776

Working with FileStreams....777

Working with StreamWriters and StreamReaders....779

Writing to a Text File....779

Reading from a Text File....780

Directly Creating StreamWriter/StreamReader Types....781

Working with StringWriters and StringReaders....782

Working with BinaryWriters and BinaryReaders....783

Watching Files Programmatically....785

Understanding Object Serialization....787

The Role of Object Graphs....787

Creating the Samples Types and Top-Level Statements....788

Serializing and Deserialization with the XmlSerializer....791

Controlling the Generated XML Data....791

Serializing Objects Using the XmlSerializer....792

Serializing Collections of Objects....793

Deserializing Objects and Collections of Objects....794

Serializing and Deserialization with System.Text.Json....794

Controlling the Generated JSON Data....794

Serializing Objects Using the JsonSerializer....795

Including Fields....795

Pretty-Print JSON....797

PascalCase or camelCase JSON....797

Number Handling with JsonSerializer....799

Potential Performance Issues using JsonSerializerOption....800

Web Defaults for JsonSerializer....800

Serializing Collections of Objects....800

Deserializing Objects and Collections of Objects....801

Summary....801

Chapter 21: Data Access with ADO.NET....802

ADO.NET vs. ADO....802

Understanding ADO.NET Data Providers....803

ADO.NET Data Providers....804

The Types of the System.Data Namespace....805

The Role of the IDbConnection Interface....806

The Role of the IDbTransaction Interface....806

The Role of the IDbCommand Interface....806

The Role of the IDbDataParameter and IDataParameter Interfaces....807

The Role of the IDbDataAdapter and IDataAdapter Interfaces....808

The Role of the IDataReader and IDataRecord Interfaces....808

Abstracting Data Providers Using Interfaces....809

Setting Up SQL Server and Azure Data Studio....812

Installing SQL Server....812

Installing SQL Server in a Docker Container....812

Pulling the Image and Running SQL Server 2019....813

Installing SQL Server 2019....814

Installing a SQL Server IDE....814

Connecting to SQL Server....814

Connecting to SQL Server in a Docker Container....815

Connecting to SQL Server LocalDb....817

Connecting to Any Other SQL Server Instance....818

Restoring the AutoLot Database Backup....818

Copying the Backup File to Your Container....818

Restoring the Database with SSMS....818

Restoring the Database to SQL Server (Docker)....819

Restoring the Database to SQL Server (Windows)....819

Restoring the Database with Azure Data Studio....820

Creating the AutoLot Database....821

Creating the Database....822

Creating the Tables....822

Creating the Inventory Table....822

Creating the Makes Table....822

Creating the Customers Table....823

Creating the Orders Table....823

Creating the CreditRisks Table....824

Creating the Table Relationships....824

Creating the Inventory to Makes Relationship....824

Creating the Inventory to Orders Relationship....824

Creating the Orders to Customers Relationship....825

Creating the Customers to CreditRisks Relationship....825

Creating the GetPetName() Stored Procedure....826

Adding Test Records....826

Makes Table Records....826

Inventory Table Records....827

Adding Test Records to the Customers Table....827

Adding Test Records to the Orders Table....827

Adding Test Records to the CreditRisks Table....828

The ADO.NET Data Provider Factory Model....828

A Complete Data Provider Factory Example....829

A Potential Drawback with the Data Provider Factory Model....833

Diving Deeper into Connections, Commands, and DataReaders....834

Working with Connection Objects....835

Working with ConnectionStringBuilder Objects....837

Working with Command Objects....837

Working with Data Readers....838

Obtaining Multiple Result Sets Using a Data Reader....840

Working with Create, Update, and Delete Queries....840

Create the Car and CarViewModel Classes....841

Adding the InventoryDal Class....842

Adding Constructors....842

Opening and Closing the Connection....842

Adding IDisposable....843

Adding the Selection Methods....843

Inserting a New Car....845

Create the Strongly Type InsertCar() Method....846

Adding the Deletion Logic....846

Adding the Update Logic....847

Working with Parameterized Command Objects....847

Specifying Parameters Using the DbParameter Type....847

Update the GetCar Method....848

Update the DeleteCar Method....849

Update the UpdateCarPetName Method....849

Update the InsertAuto Method....850

Executing a Stored Procedure....851

Creating a Console-Based Client Application....852

Understanding Database Transactions....853

Key Members of an ADO.NET Transaction Object....854

Adding a Transaction Method to InventoryDal....855

Testing Your Database Transaction....857

Executing Bulk Copies with ADO.NET....858

Exploring the SqlBulkCopy Class....858

Creating a Custom Data Reader....858

Executing the Bulk Copy....862

Testing the Bulk Copy....863

Summary....864

Part VII: Entity Framework Core....865

Chapter 22: Introducing Entity Framework Core....866

Object-Relational Mappers....867

Understanding the Role of the Entity Framework Core....867

The Building Blocks of the Entity Framework....868

The DbContext Class....868

Creating a Derived DbContext....870

Configuring the DbContext....870

The Design-Time DbContext Factory....870

OnModelCreating....871

Saving Changes....871

Transaction and Save Point Support....872

Transactions and Execution Strategies....872

Saving/Saved Changes Events....873

The DbSet Class....873

Query Types....874

Flexible Query/Table Mapping....875

The ChangeTracker....875

ChangeTracker Events....876

Resetting DbContext State....876

Entities....876

Mapping Properties to Columns....877

Mapping Classes to Tables....877

Table-per-Hierarchy Mapping (TPH)....877

Table-per-Type Mapping (TPT)....878

Navigation Properties and Foreign Keys....880

Missing Foreign Key Properties....880

One-to-Many Relationships....881

One-to-One Relationships....882

Many-to-Many Relationships (New EF Core 5)....884

Cascade Behavior....886

Optional Relationships....887

Required Relationships....887

Entity Conventions....888

Mapping Properties to Columns....888

Entity Framework Data Annotations....889

Annotations and Navigation Properties....891

The Fluent API....891

Class and Property Mapping....891

Default Values....892

Computed Columns....894

One-to-Many Relationships....894

One-to-One Relationships....895

Many-to-Many Relationships....895

Conventions, Annotations, and the Fluent API, Oh My!....896

Query Execution....896

Mixed Client-Server Evaluation....897

Tracking vs. NoTracking Queries....897

Notable EF Core Features....897

Handling Database-Generated Values....898

Concurrency Checking....898

Connection Resiliency....900

Related Data....900

Eager Loading....901

Filtered Include....901

Eager Loading with Split Queries....902

Explicit Loading....902

Lazy Loading....903

Global Query Filters....903

Global Query Filters on Navigation Properties....904

Explicit Loading with Global Query Filters....904

Raw SQL Queries with LINQ....905

Batching of Statements....906

Owned Entity Types....907

Database Function Mapping....909

The EF Core Global Tool CLI Commands....909

The Migrations Commands....911

The Add Command....911

Excluding Tables from Migrations....913

The Remove Command....913

The List Command....913

The Script Command....914

The Database Commands....914

The Drop Command....914

The Database Update Command....915

The DbContext Commands....915

The DbContext Scaffold Command....915

Summary....917

Chapter 23: Build a Data Access Layer with Entity Framework Core....918

Code First or Database First....918

Create the AutoLot.Dal and AutoLot.Models Projects....919

Scaffold the DbContext and Entities....920

Switch to Code First....920

Create the DbContext Design-Time Factory....921

Create the Initial Migration....921

Applying the Migration....922

Update the Model....923

The Entities....923

The BaseEntity Class....923

The Owned Person Entity....923

The Car (Inventory) Entity....924

The Customer Entity....927

The Make Entity....928

The CreditRisk Entity....929

The Order Entity....929

The SeriLogEntry Entity....930

The ApplicationDbContext....932

Update the Fluent API Code....932

The SeriLog Entity....932

The CreditRisk Entity....933

The Customer Entity....933

The Make Entity....934

The Order Entity....934

The Car Entity....934

Custom Exceptions....935

Override the SaveChanges Method....936

Handling DbContext and ChangeTracker Events....937

Create the Migration and Update the Database....938

Add the Database View and Stored Procedure....939

Add the MigrationHelpers Class....939

Update and Apply the Migration....940

Add the ViewModel....941

Add the ViewModel....941

Add the ViewModel to the ApplicationDbContext....942

Adding Repositories....942

Adding the IRepo Base Interface....943

Adding the BaseRepo....943

Implement the SaveChanges Method....945

Implement the Common Read Methods....945

The Add, Update, and Delete Methods....946

Entity-Specific Repo Interfaces....947

The Car Repository Interface....947

The Credit Risk Interface....948

The Customer Repository Interface....948

The Make Repository Interface....948

The Order Repository Interface....948

Implement the Entity-Specific Repositories....949

The Car Repository....949

The CreditRisk Repository....951

The Customer Repository....951

The Make Repository....952

The Order Repository....953

Programmatic Database and Migration Handling....954

Drop, Create, and Clean the Database....954

Data Initialization....956

Create the Sample Data....956

Load the Sample Data....957

Setting Up the Test-Drives....959

Create the Project....959

Configure the Project....960

Create the Test Helper....960

Add the BaseTest Class....961

Add the Transacted Test Execution Helpers....962

Add the EnsureAutoLotDatabase Test Fixture Class....963

Add the Integration Test Classes....964

Fact and Theory Test Methods....966

Executing the Tests....967

Querying the Database....967

Entity State....967

LINQ Queries....967

LINQ Execution....968

Get All Records....968

Filter Records....969

Sort Records....972

Reverse Sort Records....973

Retrieve a Single Record....973

Using First....974

Using Last....976

Using Single....976

Global Query Filters....978

Disable the Query Filters....978

Query Filters on Navigation Properties....979

Load Related Data Eagerly....979

Splitting Queries on Related Data....981

Filtering Related Data....982

Load Related Data Explicitly....983

Load Related Data Explicitly with Query Filters....985

SQL Queries with LINQ....986

Aggregate Methods....987

Any() and All()....988

Getting Data from Stored Procedures....989

Creating Records....990

Entity State....991

Add a Single Record....991

Add a Single Record Using Attach....992

Add Multiple Records at Once....992

Identity Column Considerations When Adding Records....993

Adding an Object Graph....993

Updating Records....994

Entity State....995

Update Tracked Entities....995

Update Nontracked Entities....996

Concurrency Checking....997

Deleting Records....998

Entity State....998

Delete Tracked Records....998

Delete Nontracked Entities....999

Catch Cascade Delete Failures....999

Concurrency Checking....1000

Summary....1000

Part VIII: Windows Client Development....1001

Chapter 24: Introducing Windows Presentation Foundation and XAML....1002

The Motivation Behind WPF....1002

Unifying Diverse APIs....1003

Providing a Separation of Concerns via XAML....1003

Providing an Optimized Rendering Model....1004

Simplifying Complex UI Programming....1004

Investigating the WPF Assemblies....1005

The Role of the Application Class....1006

Constructing an Application Class....1007

Enumerating the Windows Collection....1008

The Role of the Window Class....1008

The Role of System.Windows.Controls.ContentControl....1009

The Role of System.Windows.Controls.Control....1010

The Role of System.Windows.FrameworkElement....1010

The Role of System.Windows.UIElement....1011

The Role of System.Windows.Media.Visual....1012

The Role of System.Windows.DependencyObject....1012

The Role of System.Windows.Threading.DispatcherObject....1012

Understanding the Syntax of WPF XAML....1012

Introducing Kaxaml....1012

XAML XML Namespaces and XAML “Keywords”....1014

Controlling Class and Member Variable Visibility....1017

XAML Elements, XAML Attributes, and Type Converters....1017

Understanding XAML Property-Element Syntax....1018

Understanding XAML Attached Properties....1019

Understanding XAML Markup Extensions....1020

Building WPF Applications Using Visual Studio....1022

The WPF Project Templates....1023

The Toolbox and XAML Designer/Editor....1023

Setting Properties Using the Properties Window....1024

Handling Events Using the Properties Window....1026

Handling Events in the XAML Editor....1027

The Document Outline Window....1028

Enable or Disable the XAML Debugger....1029

Examining the App.xaml File....1030

Mapping the Window XAML Markup to C# Code....1031

The Role of BAML....1033

Solving the Mystery of Main()....1033

Interacting with Application-Level Data....1034

Handling the Closing of a Window Object....1035

Intercepting Mouse Events....1036

Intercepting Keyboard Events....1037

Summary....1038

Chapter 25: WPF Controls, Layouts, Events, and Data Binding....1039

A Survey of the Core WPF Controls....1039

The WPF Ink Controls....1040

The WPF Document Controls....1040

WPF Common Dialog Boxes....1041

A Brief Review of the Visual Studio WPF Designer....1041

Working with WPF Controls Using Visual Studio....1041

Working with the Document Outline Editor....1042

Controlling Content Layout Using Panels....1043

Positioning Content Within Canvas Panels....1044

Positioning Content Within WrapPanel Panels....1046

Positioning Content Within StackPanel Panels....1047

Positioning Content Within Grid Panels....1049

Sizing Grid Columns and Rows....1050

Grids with GridSplitter Types....1051

Positioning Content Within DockPanel Panels....1052

Enabling Scrolling for Panel Types....1052

Configuring Panels Using the Visual Studio Designers....1053

Building a Window’s Frame Using Nested Panels....1057

Building the Menu System....1058

Building Menus Visually....1059

Building the Toolbar....1059

Building the Status Bar....1060

Finalizing the UI Design....1060

Implementing the MouseEnter/MouseLeave Event Handlers....1061

Implementing the Spell-Checking Logic....1062

Understanding WPF Commands....1062

The Intrinsic Command Objects....1063

Connecting Commands to the Command Property....1064

Connecting Commands to Arbitrary Actions....1064

Working with the Open and Save Commands....1065

Understanding Routed Events....1067

The Role of Routed Bubbling Events....1069

Continuing or Halting Bubbling....1070

The Role of Routed Tunneling Events....1070

A Deeper Look at WPF APIs and Controls....1072

Working with the TabControl....1072

Building the Ink API Tab....1073

Designing the Toolbar....1073

The RadioButton Control....1074

Add the Save, Load, and Delete Buttons....1074

Add the InkCanvas Control....1075

Preview the Window....1075

Handling Events for the Ink API Tab....1075

Add Controls to the Toolbox....1076

The InkCanvas Control....1077

The ComboBox Control....1079

Saving, Loading, and Clearing InkCanvas Data....1081

Introducing the WPF Data-Binding Model....1082

Building the Data Binding Tab....1082

Establishing Data Bindings....1083

The DataContext Property....1083

Formatting the Bound Data....1084

Data Conversion Using IValueConverter....1084

Establishing Data Bindings in Code....1086

Building the DataGrid Tab....1087

Understanding the Role of Dependency Properties....1089

Examining an Existing Dependency Property....1091

Important Notes Regarding CLR Property Wrappers....1093

Building a Custom Dependency Property....1094

Adding a Data Validation Routine....1097

Responding to the Property Change....1097

Summary....1098

Chapter 26: WPF Graphics Rendering Services....1099

Understanding WPF’s Graphical Rendering Services....1099

WPF Graphical Rendering Options....1100

Rendering Graphical Data Using Shapes....1101

Adding Rectangles, Ellipses, and Lines to a Canvas....1102

Removing Rectangles, Ellipses, and Lines from a Canvas....1105

Working with Polylines and Polygons....1106

Working with Paths....1106

The Path Modeling “Mini-Language”....1108

WPF Brushes and Pens....1109

Configuring Brushes Using Visual Studio....1110

Configuring Brushes in Code....1113

Configuring Pens....1114

Applying Graphical Transformations....1115

A First Look at Transformations....1116

Transforming Your Canvas Data....1117

Working with the Visual Studio Transform Editor....1119

Building the Initial Layout....1119

Applying Transformations at Design Time....1121

Transforming the Canvas in Code....1122

Rendering Graphical Data Using Drawings and Geometries....1123

Building a DrawingBrush Using Geometries....1123

Painting with the DrawingBrush....1124

Containing Drawing Types in a DrawingImage....1125

Working with Vector Images....1126

Converting a Sample Vector Graphic File into XAML....1126

Importing the Graphical Data into a WPF Project....1127

Interacting with the Sign....1128

Rendering Graphical Data Using the Visual Layer....1128

The Visual Base Class and Derived Child Classes....1128

A First Look at Using the DrawingVisual Class....1129

Rendering Visual Data to a Custom Layout Manager....1131

Responding to Hit-Test Operations....1133

Summary....1135

Chapter 27: WPF Resources, Animations, Styles, and Templates....1136

Understanding the WPF Resource System....1136

Working with Binary Resources....1137

Including Loose Resource Files in a Project....1138

Configuring the Loose Resources....1138

Programmatically Loading an Image....1139

Embedding Application Resources....1140

Working with Object (Logical) Resources....1141

The Role of the Resources Property....1141

Defining Window-wide Resources....1141

The {StaticResource} Markup Extension....1145

The {DynamicResource} Markup Extension....1145

Application-Level Resources....1146

Defining Merged Resource Dictionaries....1147

Defining a Resource-Only Assembly....1148

Understanding WPF’s Animation Services....1149

The Role of the Animation Class Types....1149

The To, From, and By Properties....1150

The Role of the Timeline Base Class....1150

Authoring an Animation in C# Code....1151

Controlling the Pace of an Animation....1152

Reversing and Looping an Animation....1153

Authoring Animations in XAML....1154

The Role of Storyboards....1155

The Role of Event Triggers....1155

Animation Using Discrete Key Frames....1156

Understanding the Role of WPF Styles....1157

Defining and Applying a Style....1157

Overriding Style Settings....1158

The Effect of TargetType on Styles....1158

Subclassing Existing Styles....1160

Defining Styles with Triggers....1161

Defining Styles with Multiple Triggers....1161

Animated Styles....1162

Assigning Styles Programmatically....1162

Logical Trees, Visual Trees, and Default Templates....1164

Programmatically Inspecting a Logical Tree....1165

Programmatically Inspecting a Visual Tree....1166

Programmatically Inspecting a Control’s Default Template....1168

Building a Control Template with the Trigger Framework....1170

Templates as Resources....1171

Incorporating Visual Cues Using Triggers....1172

The Role of the {TemplateBinding} Markup Extension....1173

The Role of ContentPresenter....1174

Incorporating Templates into Styles....1174

Summary....1175

Chapter 28: WPF Notifications, Validations, Commands, and MVVM....1176

Introducing Model-View-ViewModel....1176

The Model....1176

The View....1177

The View Model....1177

Anemic Models or Anemic View Models....1177

The WPF Binding Notification System....1178

Observable Models and Collections....1178

Adding Bindings and Data....1180

Programmatically Changing the Vehicle Data....1180

Observable Models....1181

Using nameof....1183

Observable Collections....1183

Using the ObservableCollections Class....1183

Implementing a Dirty Flag....1183

Updating the Source Through UI Interaction....1185

Wrapping Up Notifications and Observables....1185

WPF Validations....1185

Updating the Sample for the Validation Examples....1186

The Validation Class....1186

Validation Options....1186

Notify on Exceptions....1186

IDataErrorInfo....1187

INotifyDataErrorInfo....1190

Implement the Supporting Code....1190

Use INotifyDataErrorInfo for Validations....1192

Combine IDataErrorInfo with INotifyDataErrorInfo for Validations....1193

Show All Errors....1194

Move the Support Code to a Base Class....1195

Leverage Data Annotations with WPF....1196

Add Data Annotations to the Model....1196

Check for Data Annotation–Based Validation Errors....1196

Customizing the ErrorTemplate....1198

Wrapping Up Validations....1200

Creating Custom Commands....1200

Implementing the ICommand Interface....1201

Adding the ChangeColorCommand....1201

Attaching the Command to the CommandManager....1202

Updating MainWindow.xaml.cs....1202

Updating MainWindow.xaml....1202

Testing the Application....1203

Creating the CommandBase Class....1203

Adding the AddCarCommand Class....1204

Updating MainWindow.xaml.cs....1205

Updating MainWindow.xaml....1205

Updating ChangeColorCommand....1205

RelayCommands....1205

Creating the Base RelayCommand....1206

Creating RelayCommand....1206

Updating MainWindow.xaml.cs....1207

Adding and Implementing the Delete Car Button....1207

Wrapping Up Commands....1208

Migrate Code and Data to a View Model....1208

Moving the MainWindow.xaml.cs Code....1208

Updating the MainWindow Code and Markup....1209

Updating the Control Markup....1209

Wrapping Up View Models....1210

Updating AutoLot.Dal for MVVM....1210

Summary....1210

Part IX: ASP.NET Core....1211

Chapter 29: Introducing ASP.NET Core....1212

A Quick Look Back....1212

Introducing the MVC Pattern....1212

The Model....1212

The View....1213

The Controller....1213

ASP.NET Core and the MVC Pattern....1213

ASP.NET Core and .NET Core....1213

One Framework, Many Uses....1213

ASP.NET Core Features from MVC/Web API....1214

Convention over Configuration....1214

Naming Conventions....1214

Directory Structure....1215

The Controllers Folder....1215

The Views Folder....1215

The Shared Folder....1215

The wwwroot Folder (New in ASP. NET Core)....1215

Controllers and Actions....1215

The Controller Class....1215

The ControllerBase Class....1216

Actions....1217

Model Binding....1217

The ModelState Dictionary....1218

Adding Custom Errors to the ModelState Dictionary....1218

Implicit Model Binding....1218

Explicit Model Binding....1219

The Bind Attribute....1219

Controlling Model Binding Sources in ASP.NET Core....1220

Model Validation....1221

Routing....1222

URL Patterns and Route Tokens....1222

Routing and ASP.NET Core RESTful Services....1222

Conventional Routing....1222

Named Routes....1223

Attribute Routing....1223

Named Routes....1225

Routing and HTTP Verbs....1225

HTTP Verbs in Web Application (MVC) Routing....1225

API Service Routing....1226

Redirecting Using Routing....1228

Filters....1228

Authorization Filters....1228

Resource Filters....1228

Action Filters....1228

Exception Filters....1229

Result Filters....1229

What’s New in ASP.NET Core....1229

Built-in Dependency Injection....1229

Environmental Awareness....1230

Determining the Runtime Environment....1230

Application Configuration....1231

Retrieving Settings....1232

Deploying ASP.NET Core Applications....1232

Lightweight and Modular HTTP Request Pipeline....1232

Create and Configure the Solution....1233

Using Visual Studio....1233

Create the Solution and Projects....1233

Add in AutoLot.Models and AutoLot.Dal....1234

Add the Project References....1235

Add the NuGet Packages....1235

Using the Command Line....1236

Running ASP.NET Core Applications....1237

Configuring the Launch Settings....1238

Using Visual Studio....1239

Using the Command Line or Visual Studio Code Terminal Window....1239

Changing Code While Debugging....1239

Using Visual Studio Code (VS Code)....1240

Changing Code While Debugging....1240

Debugging ASP.NET Core Applications....1240

Attaching with Visual Studio....1240

Attaching with Visual Studio Code....1241

Update the AutoLot.Api Ports....1241

Create and Configure the WebHost....1241

The Program.cs File....1242

The Startup.cs File....1242

Available Services for Startup....1242

The Constructor....1243

The ConfigureServices Method....1243

AutoLot.Api....1244

Add the Connection String to the App Settings....1245

AutoLot.Mvc....1245

Add the Connection String to the App Settings....1246

The Configure Method....1246

AutoLot.Api....1247

AutoLot.Mvc....1248

Logging....1250

The IAppLogging Interface....1252

The AppLogging Class....1253

Logging Configuration....1256

App Settings Updates....1258

Program.cs Updates....1259

Startup.cs Updates....1260

Controller Updates....1260

Test-Drive the Logging Framework....1261

Summary....1265

Chapter 30: RESTful Services with ASP.NET Core....1266

Introducing ASP.NET Core RESTful Services....1266

Controller Actions with RESTful Services....1267

Formatted JSON Response Results....1267

The ApiController Attribute....1270

Attribute Routing Requirement....1270

Automatic 400 Responses....1270

Binding Source Parameter Inference....1271

Problem Details for Error Status Codes....1271

Update the Swagger/OpenAPI Settings....1272

Update the Swagger Calls in the Startup Class....1272

Add the XML Documentation File....1274

Add XML Comments to SwaggerGen....1276

Additional Documentation Options for API Endpoints....1277

Building API Action Methods....1279

The Constructor....1280

The Get Methods....1281

The UpdateOne Method....1282

The AddOne Method....1283

The DeleteOne Method....1284

The CarsController....1285

The Remaining Controllers....1286

Exception Filters....1288

Create the CustomExceptionFilter....1289

Add Filters to the Processing Pipeline....1290

Test the Exception Filter....1291

Add Cross-Origin Requests Support....1291

Create a CORS Policy....1291

Add the CORS Policy to the HTTP Pipeline Handling....1292

Summary....1292

Chapter 31: MVC Applications with ASP.NET Core....1293

Introducing the “V” in ASP.NET Core....1293

ViewResults and Action Methods....1293

The Razor View Engine and Razor Syntax....1296

Views....1299

The Views Directory....1299

The Shared Directory....1300

The DisplayTemplates Folder....1300

The DateTime Display Template....1300

The Car Display Template....1301

The Car with Color Display Template....1302

The EditorTemplates Folder....1302

The Car Edit Template....1302

Layouts....1303

Specifying the Default Layout for Views....1304

Partial Views....1304

Update the Layout and Partials....1304

Create the Partials....1304

The Head Partial....1304

The Menu Partial....1305

The JavaScript Files Partial....1305

Sending Data to Views....1306

Strongly Typed Views and View Models....1306

ViewBag, ViewData, and TempData....1306

Tag Helpers....1307

Enabling Tag Helpers....1310

The Form Tag Helper....1311

The Cars Create Form....1311

The Form Action Tag Helper....1312

The Anchor Tag Helper....1312

The Input Tag Helper....1313

The TextArea Tag Helper....1314

The Select Tag Helper....1314

The Validation Tag Helpers....1315

The Environment Tag Helper....1316

The Link Tag Helper....1316

The Script Tag Helper....1317

The Image Tag Helper....1318

Custom Tag Helpers....1318

Set the Foundation....1318

Update Startup.cs....1318

Create the String Extension Method....1319

Create the Base Class....1319

The Item Details Tag Helper....1320

The Item Delete Tag Helper....1321

The Item Edit Tag Helper....1322

The Item Create Tag Helper....1322

The Item List Tag Helper....1323

Making Custom Tag Helpers Visible....1324

HTML Helpers....1324

The DisplayFor HTML Helper....1324

The DisplayForModel HTML Helper....1325

The EditorFor and EditorForModel HTML Helpers....1325

Managing Client-Side Libraries....1325

Install Library Manager As a .NET Core Global Tool....1325

Add Client-Side Libraries to AutoLot.Mvc....1325

Add the libman.json File....1326

Visual Studio....1326

Command Line....1326

Update the libman.json File....1326

Update the JavaScript and CSS References....1328

Finish the CarsController and Cars Views....1329

The CarsController....1329

The Car List Partial View....1330

The Index View....1332

The ByMake View....1333

The Details View....1334

The Create View....1335

The Create Action Methods....1336

The GetMakes Helper Method....1336

The Create Get Method....1336

The Create Post Method....1337

The Edit View....1337

The Edit Action Methods....1338

The Edit Get Method....1338

The Edit Post Method....1339

The Delete View....1340

The Delete Action Methods....1340

The Delete Get Method....1340

The Delete Post Method....1341

View Components....1341

The Server-Side Code....1342

Build the Partial View....1343

Invoking View Components....1344

Invoking View Components As Custom Tag Helpers....1344

Updating the Menu....1344

Bundling and Minification....1345

Bundling....1345

Minification....1345

The WebOptimizer Solution....1345

Update Startup.cs....1346

Update _ViewImports.cshtml....1346

The Options Pattern in ASP.NET Core....1347

Add the Dealer Information....1347

Create the Service Wrapper....1349

Update the Application Configuration....1349

Create the ServiceSettings Class....1350

The API Service Wrapper....1350

The IApiServiceWrapper Interface....1350

The ApiServiceWrapper Class....1351

The Internal Support Methods....1351

The Post and Put Helper Methods....1351

The HTTP Delete Helper Method Call....1352

The HTTP Get Calls....1352

The HTTP Post Call....1353

The HTTP Put Call....1353

The HTTP Delete Call....1354

Configure the Services....1354

Build the API CarsController....1355

The GetMakes Helper Method....1356

The GetOne Car Method....1356

The Public Action Methods....1356

Update the View Component....1358

Run AutoLot.Mvc and AutoLot.Api Together....1359

Using Visual Studio....1359

Using the Command Line....1360

Summary....1360

Index....1361

Technology authors write for a demanding group of people (for the best of possible reasons). You know that building software solutions using any platform or language can be extremely complicated, and it varies depending on your department, company, client base, and the subject matter.Perhaps you work in the electronic publishing industry, develop systems for the state or local government, or work at NASA or a branch of the military. Collectively, we have experience in a variety of industries, including children's educational software (Oregon Trail/Amazon Trail), enterprise systems, medical, and financial industries. The chances are high that the code you write in your place of employment is different from the code we have written over the years.Therefore, in this book, we deliberately chose to avoid creating examples that tie the code to a specific industry or programming language. Given this, we will explain C#, object-oriented programming (OOP), and the .NET framework.Runtime and the .NET Core Base Class Libraries using Industry-Agnostic ExamplesRather than having every example fill a grid with data or calculate payroll, we focus on subjects we can all relate to, such as automobiles. We also include some geometric structures and employee payroll systems for good measure. That's where you come in!Our goal is to explain the C# programming language and core aspects of the .NET 5 platform as best as possible. We will also equip you with the tools and strategies needed to continue your studies after this book.Your job is to apply this information to your programming assignments. Your projects may not revolve around cars with friendly names like Zippy the BMW or Yugo named Clunker. But that's what applied knowledge is about!Rest assured, once you have understood the topics and concepts covered in this text, you will be well-equipped to create .NET 5 solutions that are tailored to your specific programming environment. 


Похожее:

Список отзывов:

Нет отзывов к книге.