The C# Workshop

Book description

Build your understanding and confidence with this hands-on guide to programming with C# 10 and .NET 6

Key Features

  • Gain a solid foundation in C# and focus on coding real-world applications
  • Learn how to write clean, effective code and think like a C# developer
  • Build your experience and confidence with hands-on exercises and activities

Book Description

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#.

What you will learn

  • Understand the fundamentals of programming with C# 10 and .NET 6
  • Build your familiarity with .NET CLI and Visual Studio Code
  • Master the fundamentals of object-oriented programming (OOP)
  • Understand and implement concurrency to write more efficient code
  • Create a database and handle data using C#, SQL, and Entity Framework
  • Build web applications using the ASP.NET framework
  • Run automated unit tests with NUnit to validate your code
  • Use principles including SOLID, KISS, ACID, DRY, and design patterns

Who this book is for

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.

Table of contents

  1. The C# Workshop
  2. Preface
    1. About the Book
      1. Audience
    2. About the Authors
    3. About the Chapters
      1. Conventions
        1. Block of Code
        2. Emphasis
        3. Technical Terms
        4. Added Information
        5. Truncation
      2. Before You Begin
    4. Installing VS Code
      1. Moving Between Chapters in VS Code
      2. Installing the .NET Developer Platform
      3. The .NET 6.0 Features Found in Windows, macOS, and Linux
        1. Windows
        2. macOS
        3. Linux
        4. Docker
    5. .NET Command-Line Interface (CLI)
      1. PostgreSQL Installation for Windows
      2. PostgreSQL Installation for macOS
        1. Exploring pgAdmin Dashboard
      3. PostgreSQL Installation on Ubuntu
        1. Accessing the postgres User Account with the postgres Role
        2. Verifying the postgres User Account as a postgres User Role
        3. Accessing a New User and Database
    6. Downloading the Code
  3. 1. Hello C#
    1. Introduction
    2. Running and Developing C# with the .NET CLI
      1. Creating Programs with the CLI and VS Code
      2. Basic Anatomy of a C# Program
      3. Exercise 1.01: Creating a Console App that Says "Hello World"
        1. Top-Level Statements
      4. Declaring Variables
        1. Declaring Variables Explicitly
        2. Declaring Variables Implicitly
        3. Explicit versus Implicit Declaration
      5. Exercise 1.02: Assigning Variables to User Inputs
    3. Data Types
      1. Strings
      2. Exercise 1.03: Checking String Immutability
      3. Comparing Strings
      4. Numeric Types
      5. Exercise 1.04: Using the Basic Arithmetic Operators
    4. Classes
    5. Dates
      1. Exercise 1.05: Using Date Arithmetic
      2. Formatting Dates
    6. Logical Operators and Boolean Expressions
      1. Using if-else Statements
      2. Exercise 1.06: Branching with if-else
      3. The Ternary Operator
      4. Reference and Value Types
      5. Exercise 1.07: Grasping Value and Reference Equality
        1. Default Value Types
      6. Enhancing Decision Making with the switch Statement
      7. Exercise 1.08: Using switch to Order Food
      8. Iteration Statements
        1. while
      9. Exercise 1.09: Checking Whether a Number is Prime with a while Loop
        1. Jump Statements
        2. do-while
        3. Arrays
        4. for Loops
      10. Exercise 1.10: Ordering an Array Using Bubble Sort
        1. foreach Statements
      11. File Handling
        1. FileAccess
        2. FileMode
      12. Exercise 1.11: Reading Content from Text Files
        1. Disposable Objects
      13. Exercise 1.12: Writing to a Text File
      14. Exceptions
      15. Exercise 1.13: Handling Invalid User Inputs with try/catch
      16. Activity 1.01: Creating a Guessing Game
    7. Summary
  4. 2. Building Quality Object-Oriented Code
    1. Introduction
    2. Classes and Objects
    3. Constructors
      1. Fields and Class Members
      2. Exercise 2.01: Creating Classes and Objects
    4. Reference Types
      1. Properties
      2. Object Initialization
      3. Comparing Functions and Methods
      4. An Effective Class
      5. Exercise 2.02: Comparing the Area Occupied by Different Shapes
    5. The Four Pillars of OOP
      1. Encapsulation
      2. Inheritance
      3. Polymorphism
        1. What is the Benefit of Polymorphism?
      4. Abstraction
      5. Interfaces
      6. Exercise 2.03: Covering Floor in the Backyard
    6. SOLID Principles in OOP
      1. Single Responsibility Principle
      2. Open-Closed Principle
      3. Liskov Substitution
      4. Interface Segregation
      5. Dependency Inversion
    7. How C# Helps with Object-Oriented Design
      1. Static
      2. Sealed
      3. Partial
      4. Virtual
      5. Internal
    8. Conditional Operators
      1. Ternary Operators
      2. Overloading Operators
      3. Nullable Primitive Types
      4. Generics
      5. Enum
      6. Extension Methods
    9. Struct
      1. Record
      2. Init-Only Setters
      3. ValueTuple and Deconstruction
      4. Exercise 2.04: Creating a Composable Temperature Unit Converter
      5. Activity 2.01: Merging Two Circles
    10. Summary
  5. 3. Delegates, Events, and Lambdas
    1. Introduction
    2. Delegates
      1. Defining a Custom Delegate
      2. Exercise 3.01: Defining and Invoking Custom Delegates
      3. The Inbuilt Action and Func Delegates
      4. Assigning Delegates
      5. Invoking a Delegate
      6. Exercise 3.02: Assigning and Invoking Delegates
      7. Multicast Delegates
      8. Exercise 3.03: Invoking a Multicast Delegate
        1. Multicasting with a Func Delegate
        2. What Happens When Things Go Wrong?
      9. Exercise 3.04: Ensuring All Target Methods Are Invoked in a Multicast Delegate
      10. Events
      11. Defining an Event
      12. Exercise 3.05: Publishing and Subscribing to Events
    3. Events or Delegates?
      1. Static Events Can Cause Memory Leaks
    4. Lambda Expressions
      1. Exercise 3.06: Using a Statement Lambda to Reverse Words in a Sentence
      2. Captures and Closures
      3. Activity 3.01: Creating a Web File Downloader
    5. Summary
  6. 4. Data Structures and LINQ
    1. Introduction
    2. Data Structures
      1. Lists
      2. Exercise 4.01: Maintaining Order within a List
      3. Queues
      4. Stacks
      5. HashSets
      6. Dictionaries
      7. Exercise 4.02: Using a Dictionary to Count the Words in a Sentence
    3. LINQ
      1. Query Operators
      2. Query Expressions
      3. Deferred Execution
      4. Standard Query Operators
        1. Projection Operations
        2. Select
        3. Anonymous Types
        4. SelectMany
      5. Filtering Operations
      6. Sorting Operations
        1. OrderBy and OrderByDescending
        2. ThenBy and ThenByDescending
      7. Exercise 4.03: Filtering a List of Countries by Continent and Sorting by Area
      8. Partitioning Operations
      9. Grouping Operations
      10. Exercise 4.04: Finding the Most Commonly Used Words in a Book
      11. Aggregation Operations
      12. Quantifier Operations
      13. Join Operations
      14. Using a let Clause in Query Expressions
      15. Activity 4.01: Treasury Flight Data Analysis
    4. Summary
  7. 5. Concurrency: Multithreading Parallel and Async Code
    1. Introduction
    2. Running Asynchronous Code Using Tasks
      1. Creating a New Task
        1. Using Task.Factory.StartNew
        2. Using Task.Run
      2. Exercise 5.01: Using Tasks to Perform Multiple Slow-Running Calculations
      3. Coordinating Tasks
        1. Waiting for Tasks to Complete
      4. Exercise 5.02: Waiting for Multiple Tasks to Complete Within a Time Period
      5. Continuation Tasks
        1. Using Task.WhenAll and Task.WhenAny with Multiple Tasks
      6. Exercise 5.03: Waiting for All Tasks to Complete
    3. Asynchronous Programming
      1. Async Lambda Expressions
      2. Canceling Tasks
      3. Exercise 5.04: Canceling Long-Running Tasks
      4. Exception Handling in Async/Await Code
      5. Exercise 5.05: Handling Async Exceptions
      6. The AggregateException Class
      7. IAsyncEnumerable Streams
      8. Parallel Programming
        1. Data Parallelism
        2. Task Parallelism
        3. The Parallel Class
        4. Parallel.For and Parallel.ForEach
      9. Activity 5.01: Creating Images from a Fibonacci Sequence
    4. Summary
  8. 6. Entity Framework with SQL Server
    1. Introduction
    2. Creating a Demo Database Before You Start
      1. Modeling Databases Using EF
        1. Connection String and Security
        2. Which One to Choose—EF or EF Core?
        3. Model
      2. DbContext and DbSet
        1. AdventureWorks Database
      3. Exercise 6.01: Reading Stock Locations from AdventureWorks Database
    3. Querying a Database—LINQ to SQL
      1. Query Syntax
      2. The Rest of CRUD
      3. Exercise 6.02: Updating Products and Manufacturers Table
      4. Database First
        1. Revisiting DbContext
        2. Generating DbContext from an Existing Database
        3. Code First and Migrations
      5. Exercise 6.03: Managing Product Price Changes
    4. Pitfalls of EF
      1. Examples Setup
      2. Multiple Adds
      3. Equals over ==
      4. Using IEnumerable over IQueryable
      5. Lazy over Eager Loading
        1. Read-Only Queries
      6. Summary of Results
      7. Tools to Help You Spot Problems Early On
    5. Working with a Database in Enterprise
      1. Repository Pattern
      2. Exercise 6.04: Creating a Generic Repository
      3. Testing Data Persistence Logic Locally
        1. In-Memory Database Provider
        2. SQLite Database Provider
      4. A Few Words on Repository
        1. Query and Command Handlers Patterns
        2. Separating the Database Model from the Business Logic (Domain) Model
      5. Activity 6.01: Tracking System for Trucks Dispatched
    6. Summary
  9. 7. Creating Modern Web Applications with ASP.NET
    1. Introduction
    2. Anatomy of an ASP.NET Web App
      1. Program.cs and the WebApplication
      2. Middlewares
      3. Logging
      4. Dependency Injection
      5. Exercise 7.01: Creating Custom Logging Middleware
      6. Dependency Lifetimes
      7. Razor Pages
        1. Basic Razor Syntax
        2. File Structure
      8. Exercise 7.02: Creating a Kanban Board with Razor
      9. PageModel
        1. The Life Cycle with Page Handlers
        2. Rendering Reusable Static Code with Tag Helpers
      10. Exercise 7.03: Creating Reusable Components with Tag Helpers
      11. Model Binding
      12. Exercise 7.04: Creating a New Page to Submit Tasks
      13. Validation
      14. Dynamic Behavior with Partial Pages
      15. Exercise 7.05: Refactoring a Tag Helper to a Partial Page with Custom Logic
      16. Activity 7.01: Creating a Page to Edit an Existing Task
    3. View Components
      1. Exercise 7.06: Creating a View Component to Display Task Statistics
      2. Activity 7.02: Writing a View Component to Display Task Log
    4. Summary
  10. 8. Creating and Using Web API Clients
    1. Introduction
    2. Browser
    3. Web API
      1. RESTful API
      2. Postman
      3. Client
      4. Octokit
      5. API Key
      6. Azure Text Analytics
      7. Exercise 8.01: Performing Sentimental Text Analysis on Any Text
    4. Your Own Client
      1. HttpClient
        1. HttpClient and IDisposable
      2. OAuth
        1. Real-life Analogy
        2. API Analogy
      3. OAuth App for GitHub
      4. Authorization Header
      5. Basic Authentication
        1. API Key and Personal Access Token
      6. Third-Party Authentication—OAuth2
      7. Request Idempotency
        1. PUT, PATCH, or POST
      8. Exercise 8.02: HttpClient Calling a Star Wars Web API
      9. Activity 8.01: Reusing HttpClient for the Rapid Creation of API Clients
    5. RestSharp
      1. Activity 8.02: The Countries API Using RestSharp to List all Countries
    6. Refit
      1. Activity 8.03: The Countries API Using Refit to List all Countries
    7. Other Ways of Making HTTP Requests
      1. Exercise 8.03: A Strongly Typed HTTP Client for Testing Payments in a PayPal Sandbox
      2. Activity 8.04: Using an Azure Blob Storage Client to Upload and Download Files
    8. Summary
  11. 9. Creating API Services
    1. Introduction
    2. ASP.NET Core Web API
      1. Creating a New Project
        1. Web API Project Structure
        2. An In-Depth Look at WeatherForecastController
        3. Responding with Different Status Codes
      2. Exercise 9.01: .NET Core Current Time Service
      3. Bootstrapping a Web API
        1. Dependency Injection
        2. Program.cs and Minimal API
      4. The Inner Workings of the AddLogging Method
        1. The Lifetime of an Injected Component
      5. DI Examples within a Service
      6. Singleton
      7. Scoped
      8. Transient
        1. TryAdd
        2. Manual Injection Using an IoC Container
      9. Exercise 9.02: Displaying Current Time in a Country API Time Zone
      10. OpenAPI and Swagger
        1. Using Swagger Swashbuckle
      11. Error Handling
      12. Request Validation
      13. Configuration
        1. Development Environments and Configuration
      14. Bootstrapping
      15. Calling Another API
        1. RapidAPI
        2. Service Client
        3. DTO and Mapping Using AutoMapper
        4. HttpClient DI
      16. Exercise 9.03: Performing File Operations by Calling Azure Blob Storage
      17. Securing a Web API
        1. Azure Active Directory
        2. JWT
        3. OpenID Connect
      18. Application Registration
      19. Implementing Web API Security
        1. Token Generator App
        2. Configuring Swagger Auth
        3. Troubleshooting Token Validation Errors
      20. Service-Oriented Architecture
        1. Microservice Architecture
      21. Activity 9.01: Implementing the File Upload Service Using Microservice Architecture
      22. Azure Functions
    3. Summary
      1. Hey!

Product information

  • Title: The C# Workshop
  • Author(s): Jason Hales, Almantas Karpavicius, Mateus Viegas
  • Release date: September 2022
  • Publisher(s): Packt Publishing
  • ISBN: 9781800566491