The

C#

Workshop

The C# Workshop

Copyright © 2022 Packt Publishing

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

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

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

Authors: Jason Hales, Almantas Karpavicius, and Mateus Viegas

Reviewers: Omprakash Pandey and Dara Oladapo

Development Editor: M Keerthi Nair

Acquisitions Editors: Royluis Rodrigues, Kunal Sawant, and Anindya Sil

Production Editor: Shantanu Zagade

Editorial Board: Vijin Boricha, Megan Carlisle, Ketan Giri, Heather Gopsill, Akin Babu Joseph, Bridget Kenningham, Manasa Kumar, Alex Mazonowicz, Monesh Mirpuri, Aaron Nash, Abhishek Rane, Brendan Rodrigues, Ankita Thakur, Nitesh Thakur, and Jonathan Wray

First published: September 2022

Production reference: 2281022

ISBN: 978-1-80056-649-1

Published by Packt Publishing Ltd.

Livery Place, 35 Livery Street

Birmingham B3 2PB, UK

Table of Contents

Preface

1. Hello C#

Introduction

Running and Developing C# with the .NET CLI

Creating Programs with the CLI and VS Code

Basic Anatomy of a C# Program

Exercise 1.01: Creating a Console App that Says "Hello World"

Top-Level Statements

Declaring Variables

Declaring Variables Explicitly

Declaring Variables Implicitly

Explicit versus Implicit Declaration

Exercise 1.02: Assigning Variables to User Inputs

Data Types

Strings

Exercise 1.03: Checking String Immutability

Comparing Strings

Numeric Types

Exercise 1.04: Using the Basic Arithmetic Operators

Classes

Dates

Exercise 1.05: Using Date Arithmetic

Formatting Dates

Logical Operators and Boolean Expressions

Using if-else Statements

Exercise 1.06: Branching with if-else

The Ternary Operator

Reference and Value Types

Exercise 1.07: Grasping Value and Reference Equality

Default Value Types

Enhancing Decision Making with the switch Statement

Exercise 1.08: Using switch to Order Food

Iteration Statements

while

Exercise 1.09: Checking Whether a Number is Prime with a while Loop

Jump Statements

do-while

Arrays

for Loops

Exercise 1.10: Ordering an Array Using Bubble Sort

foreach Statements

File Handling

FileAccess

FileMode

Exercise 1.11: Reading Content from Text Files

Disposable Objects

Exercise 1.12: Writing to a Text File

Exceptions

Exercise 1.13: Handling Invalid User Inputs with try/catch

Activity 1.01: Creating a Guessing Game

Summary

2. Building Quality Object-Oriented Code

Introduction

Classes and Objects

Constructors

Fields and Class Members

Exercise 2.01: Creating Classes and Objects

Reference Types

Properties

Object Initialization

Comparing Functions and Methods

An Effective Class

Exercise 2.02: Comparing the Area Occupied by Different Shapes

The Four Pillars of OOP

Encapsulation

Inheritance

Polymorphism

What is the Benefit of Polymorphism?

Abstraction

Interfaces

Exercise 2.03: Covering Floor in the Backyard

SOLID Principles in OOP

Single Responsibility Principle

Open-Closed Principle

Liskov Substitution

Interface Segregation

Dependency Inversion

How C# Helps with Object-Oriented Design

Static

Sealed

Partial

Virtual

Internal

Conditional Operators

Ternary Operators

Overloading Operators

Nullable Primitive Types

Generics

Enum

Extension Methods

Struct

Record

Init-Only Setters

ValueTuple and Deconstruction

Exercise 2.04: Creating a Composable Temperature Unit Converter

Activity 2.01: Merging Two Circles

Summary

3. Delegates, Events, and Lambdas

Introduction

Delegates

Defining a Custom Delegate

Exercise 3.01: Defining and Invoking Custom Delegates

The Inbuilt Action and Func Delegates

Assigning Delegates

Invoking a Delegate

Exercise 3.02: Assigning and Invoking Delegates

Multicast Delegates

Exercise 3.03: Invoking a Multicast Delegate

Multicasting with a Func Delegate

What Happens When Things Go Wrong?

Exercise 3.04: Ensuring All Target Methods Are Invoked in a Multicast Delegate

Events

Defining an Event

Exercise 3.05: Publishing and Subscribing to Events

Events or Delegates?

Static Events Can Cause Memory Leaks

Lambda Expressions

Exercise 3.06: Using a Statement Lambda to Reverse Words in a Sentence

Captures and Closures

Activity 3.01: Creating a Web File Downloader

Summary

4. Data Structures and LINQ

Introduction

Data Structures

Lists

Exercise 4.01: Maintaining Order within a List

Queues

Stacks

HashSets

Dictionaries

Exercise 4.02: Using a Dictionary to Count the Words in a Sentence

LINQ

Query Operators

Query Expressions

Deferred Execution

Standard Query Operators

Projection Operations

Select

Anonymous Types

SelectMany

Filtering Operations

Sorting Operations

OrderBy and OrderByDescending

ThenBy and ThenByDescending

Exercise 4.03: Filtering a List of Countries by Continent and Sorting by Area

Partitioning Operations

Grouping Operations

Exercise 4.04: Finding the Most Commonly Used Words in a Book

Aggregation Operations

Quantifier Operations

Join Operations

Using a let Clause in Query Expressions

Activity 4.01: Treasury Flight Data Analysis

Summary

5. Concurrency: Multithreading Parallel and Async Code

Introduction

Running Asynchronous Code Using Tasks

Creating a New Task

Using Task.Factory.StartNew

Using Task.Run

Exercise 5.01: Using Tasks to Perform Multiple Slow-Running Calculations

Coordinating Tasks

Waiting for Tasks to Complete

Exercise 5.02: Waiting for Multiple Tasks to Complete Within a Time Period

Continuation Tasks

Using Task.WhenAll and Task.WhenAny with Multiple Tasks

Exercise 5.03: Waiting for All Tasks to Complete

Asynchronous Programming

Async Lambda Expressions

Canceling Tasks

Exercise 5.04: Canceling Long-Running Tasks

Exception Handling in Async/Await Code

Exercise 5.05: Handling Async Exceptions

The AggregateException Class

IAsyncEnumerable Streams

Parallel Programming

Data Parallelism

Task Parallelism

The Parallel Class

Parallel.For and Parallel.ForEach

Activity 5.01: Creating Images from a Fibonacci Sequence

Summary

6. Entity Framework with SQL Server

Introduction

Creating a Demo Database Before You Start

Modeling Databases Using EF

Connection String and Security

Which One to Choose—EF or EF Core?

Model

DbContext and DbSet

AdventureWorks Database

Exercise 6.01: Reading Stock Locations from AdventureWorks Database

Querying a Database—LINQ to SQL

Query Syntax

The Rest of CRUD

Exercise 6.02: Updating Products and Manufacturers Table

Database First

Revisiting DbContext

Generating DbContext from an Existing Database

Code First and Migrations

Exercise 6.03: Managing Product Price Changes

Pitfalls of EF

Examples Setup

Multiple Adds

Equals over ==

Using IEnumerable over IQueryable

Lazy over Eager Loading

Read-Only Queries

Summary of Results

Tools to Help You Spot Problems Early On

Working with a Database in Enterprise

Repository Pattern

Exercise 6.04: Creating a Generic Repository

Testing Data Persistence Logic Locally

In-Memory Database Provider

SQLite Database Provider

A Few Words on Repository

Query and Command Handlers Patterns

Separating the Database Model from the Business Logic (Domain) Model

Activity 6.01: Tracking System for Trucks Dispatched

Summary

7. Creating Modern Web Applications with ASP.NET

Introduction

Anatomy of an ASP.NET Web App

Program.cs and the WebApplication

Middlewares

Logging

Dependency Injection

Exercise 7.01: Creating Custom Logging Middleware

Dependency Lifetimes

Razor Pages

Basic Razor Syntax

File Structure

Exercise 7.02: Creating a Kanban Board with Razor

PageModel

The Life Cycle with Page Handlers

Rendering Reusable Static Code with Tag Helpers

Exercise 7.03: Creating Reusable Components with Tag Helpers

Model Binding

Exercise 7.04: Creating a New Page to Submit Tasks

Validation

Dynamic Behavior with Partial Pages

Exercise 7.05: Refactoring a Tag Helper to a Partial Page with Custom Logic

Activity 7.01: Creating a Page to Edit an Existing Task

View Components

Exercise 7.06: Creating a View Component to Display Task Statistics

Activity 7.02: Writing a View Component to Display Task Log

Summary

8. Creating and Using Web API Clients

Introduction

Browser

Web API

RESTful API

Postman

Client

Octokit

API Key

Azure Text Analytics

Exercise 8.01: Performing Sentimental Text Analysis on Any Text

Your Own Client

HttpClient

HttpClient and IDisposable

OAuth

Real-life Analogy

API Analogy

OAuth App for GitHub

Authorization Header

Basic Authentication

API Key and Personal Access Token

Third-Party Authentication—OAuth2

Request Idempotency

PUT, PATCH, or POST

Exercise 8.02: HttpClient Calling a Star Wars Web API

Activity 8.01: Reusing HttpClient for the Rapid Creation of API Clients

RestSharp

Activity 8.02: The Countries API Using RestSharp to List all Countries

Refit

Activity 8.03: The Countries API Using Refit to List all Countries

Other Ways of Making HTTP Requests

Exercise 8.03: A Strongly Typed HTTP Client for Testing Payments in a PayPal Sandbox

Activity 8.04: Using an Azure Blob Storage Client to Upload and Download Files

Summary

9. Creating API Services

Introduction

ASP.NET Core Web API

Creating a New Project

Web API Project Structure

An In-Depth Look at WeatherForecastController

Responding with Different Status Codes

Exercise 9.01: .NET Core Current Time Service

Bootstrapping a Web API

Dependency Injection

Program.cs and Minimal API

The Inner Workings of the AddLogging Method

The Lifetime of an Injected Component

DI Examples within a Service

Singleton

Scoped

Transient

TryAdd

Manual Injection Using an IoC Container

Exercise 9.02: Displaying Current Time in a Country API Time Zone

OpenAPI and Swagger

Using Swagger Swashbuckle

Error Handling

Request Validation

Configuration

Development Environments and Configuration

Bootstrapping

Calling Another API

RapidAPI

Service Client

DTO and Mapping Using AutoMapper

HttpClient DI

Exercise 9.03: Performing File Operations by Calling Azure Blob Storage

Securing a Web API

Azure Active Directory

JWT

OpenID Connect

Application Registration

Implementing Web API Security

Token Generator App

Configuring Swagger Auth

Troubleshooting Token Validation Errors

Service-Oriented Architecture

Microservice Architecture

Activity 9.01: Implementing the File Upload Service Using Microservice Architecture

Azure Functions

Summary

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset