Cover....1
FM....2
Copyright....3
Table of Contents....4
Preface....20
Chapter 1: Hello C#....68
Introduction....69
Running and Developing C# with the .NET CLI....69
Creating Programs with the CLI and VS Code....71
Basic Anatomy of a C# Program....72
Exercise 1.01: Creating a Console App that Says "Hello World"....72
Top-Level Statements....73
Declaring Variables....74
Declaring Variables Explicitly....75
Declaring Variables Implicitly....76
Explicit versus Implicit Declaration....76
Exercise 1.02: Assigning Variables to User Inputs....77
Data Types....78
Strings....78
Exercise 1.03: Checking String Immutability....79
Comparing Strings....80
Numeric Types....81
Exercise 1.04: Using the Basic Arithmetic Operators....82
Classes....83
Dates....86
Exercise 1.05: Using Date Arithmetic.....87
Formatting Dates....89
Logical Operators and Boolean Expressions....89
Using if-else Statements....91
Exercise 1.06: Branching with if-else....91
The Ternary Operator....94
Reference and Value Types....94
Exercise 1.07: Grasping Value and Reference Equality ....97
Default Value Types....100
Enhancing Decision Making with the switch Statement....100
Exercise 1.08: Using switch to Order Food....101
Iteration Statements....104
while....104
Exercise 1.09: Checking Whether a Number is Prime with a while Loop....105
Jump Statements....106
do-while....109
Arrays....109
for Loops....110
Exercise 1.10: Ordering an Array Using Bubble Sort....111
foreach Statements....113
File Handling....114
FileAccess....115
FileMode....115
Exercise 1.11: Reading Content from Text Files....116
Disposable Objects....117
Exercise 1.12: Writing to a Text File....118
Exceptions....120
Exercise 1.13: Handling Invalid User Inputs with try/catch....120
Activity 1.01: Creating a Guessing Game....124
Summary....125
Chapter 2: Building Quality Object-Oriented Code....128
Introduction....129
Classes and Objects....129
Constructors....130
Fields and Class Members....131
Exercise 2.01: Creating Classes and Objects....132
Reference Types....134
Properties....138
Object Initialization....142
Comparing Functions and Methods....143
An Effective Class....144
Exercise 2.02: Comparing the Area Occupied by Different Shapes....146
The Four Pillars of OOP....151
Encapsulation....151
Inheritance....152
Polymorphism....159
What is the Benefit of Polymorphism?....161
Abstraction....164
Interfaces....168
Exercise 2.03: Covering Floor in the Backyard....172
SOLID Principles in OOP....175
Single Responsibility Principle....176
Open-Closed Principle....180
Liskov Substitution....181
Interface Segregation....182
Dependency Inversion....185
How C# Helps with Object-Oriented Design....188
Static....189
Sealed....191
Partial....191
Virtual....192
Internal....193
Conditional Operators....193
Ternary Operators....194
Overloading Operators....196
Nullable Primitive Types....198
Generics....199
Enum....203
Extension Methods....203
Struct....204
Record....207
Init-Only Setters....211
ValueTuple and Deconstruction....211
Exercise 2.04: Creating a Composable Temperature Unit Converter....213
Activity 2.01: Merging Two Circles....220
Summary....222
Chapter 3: Delegates, Events, and Lambdas....224
Introduction....225
Delegates....226
Defining a Custom Delegate....232
Exercise 3.01: Defining and Invoking Custom Delegates....233
The Inbuilt Action and Func Delegates....238
Assigning Delegates....241
Invoking a Delegate....243
Exercise 3.02: Assigning and Invoking Delegates....244
Multicast Delegates....250
Exercise 3.03: Invoking a Multicast Delegate....252
Multicasting with a Func Delegate....258
What Happens When Things Go Wrong?....260
Exercise 3.04: Ensuring All Target Methods Are Invoked in a Multicast Delegate....261
Events....266
Defining an Event....266
Exercise 3.05: Publishing and Subscribing to Events....271
Events or Delegates?....275
Static Events Can Cause Memory Leaks....276
Lambda Expressions....277
Exercise 3.06: Using a Statement Lambda to Reverse Words in a Sentence....281
Captures and Closures....283
Activity 3.01: Creating a Web File Downloader....287
Summary....290
Chapter 4: Data Structures and LINQ....292
Introduction....293
Data Structures....293
Lists....297
Exercise 4.01: Maintaining Order within a List....305
Queues....310
Stacks....312
HashSets....317
Dictionaries....319
Exercise 4.02: Using a Dictionary to Count the Words in a Sentence....324
LINQ....328
Query Operators....329
Query Expressions....330
Deferred Execution....330
Standard Query Operators....331
Projection Operations....331
Select....331
Anonymous Types....332
SelectMany....335
Filtering Operations....337
Sorting Operations....343
OrderBy and OrderByDescending....343
ThenBy and ThenByDescending....345
Exercise 4.03: Filtering a List of Countries by Continent and Sorting by Area....348
Partitioning Operations....350
Grouping Operations....353
Exercise 4.04: Finding the Most Commonly Used Words in a Book....355
Aggregation Operations....361
Quantifier Operations....364
Join Operations....368
Using a let Clause in Query Expressions....371
Activity 4.01: Treasury Flight Data Analysis....372
Summary....378
Chapter 5: Concurrency: Multithreading Parallel and Async Code....380
Introduction....381
Running Asynchronous Code Using Tasks....384
Creating a New Task....384
Using Task.Factory.StartNew....389
Using Task.Run....390
Exercise 5.01: Using Tasks to Perform Multiple Slow-Running Calculations....393
Coordinating Tasks....396
Waiting for Tasks to Complete....397
Exercise 5.02: Waiting for Multiple Tasks to Complete Within a Time Period....399
Continuation Tasks....403
Using Task.WhenAll and Task.WhenAny with Multiple Tasks....406
Exercise 5.03: Waiting for All Tasks to Complete....407
Asynchronous Programming....415
Async Lambda Expressions....422
Canceling Tasks....425
Exercise 5.04: Canceling Long-Running Tasks....427
Exception Handling in Async/Await Code....436
Exercise 5.05: Handling Async Exceptions....439
The AggregateException Class....443
IAsyncEnumerable Streams....448
Parallel Programming....451
Data Parallelism....452
Task Parallelism....452
The Parallel Class....453
Parallel.For and Parallel.ForEach....455
Activity 5.01: Creating Images from a Fibonacci Sequence....468
Summary....474
Chapter 6: Entity Framework with SQL Server....476
Introduction....477
Creating a Demo Database Before You Start....478
Modeling Databases Using EF....479
Connection String and Security....481
Which One to Choose—EF or EF Core?....484
Model....485
DbContext and DbSet....488
AdventureWorks Database....492
Exercise 6.01: Reading Stock Locations from AdventureWorks Database....492
Querying a Database—LINQ to SQL....495
Query Syntax....497
The Rest of CRUD....499
Exercise 6.02: Updating Products and Manufacturers Table....503
Database First....507
Revisiting DbContext....509
Generating DbContext from an Existing Database....511
Code First and Migrations....512
Exercise 6.03: Managing Product Price Changes....516
Pitfalls of EF....520
Examples Setup....521
Multiple Adds....523
Equals over ==....524
Using IEnumerable over IQueryable....525
Lazy over Eager Loading....526
Read-Only Queries....527
Summary of Results....527
Tools to Help You Spot Problems Early On....528
Working with a Database in Enterprise....529
Repository Pattern....529
Exercise 6.04: Creating a Generic Repository....532
Testing Data Persistence Logic Locally....536
In-Memory Database Provider....536
SQLite Database Provider....538
A Few Words on Repository....540
Query and Command Handlers Patterns....541
Separating the Database Model from the Business Logic (Domain) Model....544
Activity 6.01: Tracking System for Trucks Dispatched....545
Summary....547
Chapter 7: Creating Modern Web Applications with ASP.NET....550
Introduction....551
Anatomy of an ASP.NET Web App....551
Program.cs and the WebApplication....553
Middlewares....554
Logging....555
Dependency Injection....557
Exercise 7.01: Creating Custom Logging Middleware....558
Dependency Lifetimes....563
Razor Pages....565
Basic Razor Syntax....565
File Structure....566
Exercise 7.02: Creating a Kanban Board with Razor....568
PageModel....571
The Life Cycle with Page Handlers....572
Rendering Reusable Static Code with Tag Helpers....573
Exercise 7.03: Creating Reusable Components with Tag Helpers....574
Model Binding....579
Exercise 7.04: Creating a New Page to Submit Tasks....579
Validation....586
Dynamic Behavior with Partial Pages....587
Exercise 7.05: Refactoring a Tag Helper to a Partial Page with Custom Logic....588
Activity 7.01: Creating a Page to Edit an Existing Task....590
View Components....591
Exercise 7.06: Creating a View Component to Display Task Statistics....593
Activity 7.02: Writing a View Component to Display Task Log....597
Summary....599
Chapter 8: Creating and Using Web API Clients....602
Introduction....603
Browser....604
Web API....606
RESTful API....606
Postman....607
Client....609
Octokit....609
API Key....611
Azure Text Analytics....611
Exercise 8.01: Performing Sentimental Text Analysis on Any Text....616
Your Own Client....621
HttpClient....621
HttpClient and IDisposable....625
OAuth....626
Real-life Analogy....626
API Analogy....626
OAuth App for GitHub....626
Authorization Header....632
Basic Authentication....634
API Key and Personal Access Token....635
Third-Party Authentication—OAuth2....637
Request Idempotency....643
PUT, PATCH, or POST....643
Exercise 8.02: HttpClient Calling a Star Wars Web API....643
Activity 8.01: Reusing HttpClient for the Rapid Creation of API Clients....648
RestSharp....650
Activity 8.02: The Countries API Using RestSharp to List all Countries....652
Refit....653
Activity 8.03: The Countries API Using Refit to List all Countries....654
Other Ways of Making HTTP Requests....655
Exercise 8.03: A Strongly Typed HTTP Client for Testing Payments in a PayPal Sandbox....656
Activity 8.04: Using an Azure Blob Storage Client to Upload and Download Files....667
Summary....670
Chapter 9: Creating API Services....672
Introduction....673
ASP.NET Core Web API....673
Creating a New Project....673
Web API Project Structure....675
An In-Depth Look at WeatherForecastController....675
Responding with Different Status Codes....677
Exercise 9.01: .NET Core Current Time Service....681
Bootstrapping a Web API....682
Dependency Injection....682
Program.cs and Minimal API....682
The Inner Workings of the AddLogging Method....685
The Lifetime of an Injected Component....685
DI Examples within a Service....686
Singleton....690
Scoped....691
Transient....691
TryAdd....692
Manual Injection Using an IoC Container....693
Exercise 9.02: Displaying Current Time in a Country API Time Zone....695
OpenAPI and Swagger....697
Using Swagger Swashbuckle....697
Error Handling....709
Request Validation....710
Configuration....713
Development Environments and Configuration....714
Bootstrapping....716
Calling Another API....721
RapidAPI....721
Service Client....728
DTO and Mapping Using AutoMapper....730
HttpClient DI....732
Exercise 9.03: Performing File Operations by Calling Azure Blob Storage....734
Securing a Web API....745
Azure Active Directory....745
JWT....746
OpenID Connect....746
Application Registration....747
Implementing Web API Security....750
Token Generator App....751
Configuring Swagger Auth....757
Troubleshooting Token Validation Errors....760
Service-Oriented Architecture....761
Microservice Architecture....762
Activity 9.01: Implementing the File Upload Service Using Microservice Architecture....762
Azure Functions....765
Summary....770
Index....774
C# is a powerful, versatile language that can unlock a variety of career paths. But, as with any programming language, learning C# can be a challenging process. With a wide range of different resources available, it's difficult to know where to start.
That's where The C# Workshop comes in. Written and reviewed by industry experts, it provides a fast-paced, supportive learning experience that will quickly get you writing C# code and building applications. Unlike other software development books that focus on dry, technical explanations of the underlying theory, this Workshop cuts through the noise and uses engaging examples to help you understand how each concept is applied in the real world.
As you work through the book, you'll tackle realistic exercises that simulate the type of problems that software developers work on every day. These mini-projects include building a random-number guessing game, using the publisher-subscriber model to design a web file downloader, creating a to-do list using Razor Pages, generating images from the Fibonacci sequence using async/await tasks, and developing a temperature unit conversion app which you will then deploy to a production server.
By the end of this book, you'll have the knowledge, skills, and confidence to advance your career and tackle your own ambitious projects with C#.
This book is for aspiring C# developers. It is recommended that you already have a basic understanding of core programming concepts before you start. Prior experience of another programming language would be beneficial, though it is not absolutely necessary.