C# is a powerful and versatile Object-Oriented Programming (OOP) language that can unlock a variety of career paths. But, as with any programming language, learning C# can be challenging. 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 learn how each concept is applied in the real world.
As you work through the book, you'll tackle realistic exercises that simulate the types of problems 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 that you will then deploy to a production server.
By the end of this book, you'll have the knowledge, skills, and confidence required to advance your career and tackle your ambitious projects with C#.
This book is for aspiring C# developers. It is recommended that you have a basic knowledge of core programming concepts before you start. Prior experience with another programming language would be beneficial, though it is not absolutely necessary.
Jason Hales has been developing low-latency, real-time applications using various Microsoft technologies since the first release of C# in 2001. He is a keen advocate of design patterns, OO principles, and test-driven practices. When he's not dabbling with code, he likes to spend time with his wife, Ann, and their three daughters in Cambridgeshire, UK.
Almantas Karpavicius is a lead software engineer working in the information and technology company, TransUnion. He has been a professional programmer for over five years. On top of his full-time programming career, Almantas has spent three years teaching programming for free in his free time on Twitch.tv. He is a founder of a C# programming community called C# Inn that boasts over 7000 members and the creator of two free C# boot camps in which he has helped hundreds of people get a start in their careers. He has taken interviews with programming celebrities, such as Jon Skeet, Robert C. Martin (Uncle Bob), Mark Seemann, and was also a part-time Java teacher for a time. Almantas likes talking about software design, clean code, and architecture. He is also interested in Agile (Scrum, in particular) and is a big fan of automated tests, especially those done using BDD. He also holds a two-year Microsoft MVP (https://packt.link/2qUJp).
Mateus Viegas has been working in Software Engineering and Architecture for over a decade, dedicating the last few years to Leadership and Management roles. His main interests in technology are C#, Distributed Systems, and Product Development. A lover of the outdoors, when not working he likes to spend his time either exploring nature with his family, taking photographs, or running.
Chapter 1, Hello C#, introduces the fundamental concepts of the language, such as variables, constants, loops, and arithmetic and logical operators.
Chapter 2, Building Quality Object-Oriented Code, covers the basics of Object-oriented programming and its four pillars, before introducing the five main principles of clean coding—SOLID. This chapter also covers the latest features in the C# language.
Chapter 3, Delegates, Events, and Lambdas, introduces delegates and events, which form the core mechanism for communicating between objects, and lambda syntax, which offers a way to clearly express the intent of code.
Chapter 4, Data Structures and LINQ, covers the common collection classes that are used to store multiple values and the integrated language LINQ which is designed for querying collections in memory.
Chapter 5, Concurrency: Multithreading Parallel and Async Code, provides an introduction to writing efficient code that is high performing across different scenarios and how to avoid common pitfalls and mistakes.
Chapter 6, Entity Framework with SQL Server, introduces database design and storage using SQL and C# and provides an in-depth look at object-relational mapping using Entity Framework. The chapter also teaches common design patterns for working with databases.
Note
For those who are interested in learning the basics of databases and how to work with PostgreSQL, a reference chapter has been included in the GitHub repository of this book. You can access it at https://packt.link/oLQsL.
Chapter 7, Creating Modern Web Applications with ASP.NET, looks at how to write simple ASP.NET applications and how to use approaches such as server-side rendering and single-page applications to create web applications.
Chapter 8, Creating and Using Web API Clients, introduces APIs and teaches you how to access and consume Web APIs from ASP.NET code.
Chapter 9, Creating API Services, continues with the topic of APIs and teaches you how to create your API services for consumption, and how to secure it. The chapter also introduces you to the concept of microservices.
Note
There are also two bonus chapters (Chapter 10, Automated Testing, and Chapter 11, Production-Ready C#: From Development to Deployment) which you can find at https://packt.link/44j2X and https://packt.link/39qQA, respectively.
You can also find solutions for all activities in this Workshop online at https://packt.link/qclbF.
This book has some conventions set to arrange content efficiently. Read about them in the next section.
In the book, a block of code is set as follows:
using System;
namespace Exercise1_01
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
In cases where inputting and executing some code gives an immediate output, this is shown as follows:
dotnet run
Hello World!
Good morning Mars!
Definitions, new terms, and important words are shown like this:
Multithreading is a form of concurrency whereby multiple threads are used to perform operations.
Language commands within the body of the chapter are indicated in the following manner:
Here, the simplest Task constructor is passed an Action lambda statement, which is the actual target code that you want to execute. The target code writes the message Inside taskA to the console.
Essential information is indicated in the following way:
Note
The term Factory is often used in software development to represent methods that help create objects.
Long code snippets are truncated and the corresponding names of the code files on GitHub are placed at the top of the truncated code. Permalinks to the entire code are placed below the code snippet, as follows:
HashSetExamples.cs
using System;
using System.Collections.Generic;
namespace Chapter04.Examples
{
}
You can find the complete code here: http://packt.link/ZdNbS.
Before you dive into the power of the C# language, you will need to install the .NET runtime and the C# development and debugging tools.
You can either install the full Visual Studio Integrated Development Environment (IDE), which offers a fully featured code editor (this is a costly license) or you can install Visual Studio Code (VS Code), Microsoft's lightweight cross-platform editor. The C# Workshop targets the VS Code editor as this does not require a license fee and works seamlessly across multiple platforms.
Visit the VS Code site at https://code.visualstudio.com and download it for Windows, macOS, or Linux, following the installation instructions for your preferred platform.
Note
It is better to check the Create a Desktop Icon checkbox for ease of use.
VS Code is free and open source. It supports multiple languages and needs to be configured for the C# language. Once VS Code is installed, you will need to add the C# for Visual Studio Code (powered by OmniSharp) extension to support C#. This can be found at https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp. To install the C# extension, follow the per-platform instructions:
Note
If you do not want to directly install the C# extension from the website, install it from VS code itself.
You will see that the C# extension gets successfully installed on VS Code. You have now installed VS Code on your system.
The next section will cover how VS Code can be used as you move between the book chapters.
To change the default project to build (whether it is an activity, exercise, or demo), you will need to point to these exercise files:
There are two different patterns of exercise that you should be aware of. Some exercises have a project of their own. Others have a different main method. The main method of a single project per exercise can be configured like this (in this example for Chapter 3, Delegates, Events, and Lambdas, you are configuring Exercise02 to be the build and launch points):
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/Exercises/ /Exercise02/bin/Debug/net6.0/Exercise02.exe",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"console": "internalConsole"
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Chapter05.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
]
}
One project for each exercise (for example, Chapter05 Exercise02) can be configured like this:
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/net6.0/Chapter05.exe",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"console": "internalConsole"
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Chapter05.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary",
"-p:StartupObject=Chapter05.Exercises.Exercise02.Program",
],
"problemMatcher": "$msCompile"
},
]
}
Now that you are aware of launch.json and tasks.json, you can proceed to the next section which details the installation of the .NET developer platform.
The .NET developer platform can be downloaded from https://dotnet.microsoft.com/download. There are variants for Windows, macOS, and Docker on Linux. The C# Workshop book uses .NET 6.0.
Follow the steps to install the .NET 6.0 platform on Windows:
Note
The screen shown in Figure 0.2 may change depending on the latest release from Microsoft.
Follow the steps to install the .NET 6.0 platform on macOS:
After the download is complete, open the installer file. You should have a screen similar to Figure 0.3:
The following screen will confirm the amount of space that will be required for the installation:
You will see a progress bar moving on the next screen:
Soon after the installation is finalized, you'll have a success screen (Figure 0.6):
dotnet –list-sdks
This will check the version of .NET installed on your machine. Figure 0.7 shows the output where your installed SDKs will be listed:
With these steps, you can install the .NET 6.0 SDK on your machine and check the installed version.
Note
Net 6.0 installation steps for Linux are not included as they are like Windows and macOS.
Before proceeding further, it is important to know about .NET 6.0 features.
With .NET 6.0 installed on your system, the next step is to configure projects using CLI.
Once you have installed .NET, the CLI can be used to create and configure projects for use with VS Code. To launch the .NET CLI, run the following at the command prompt:
dotnet
If .NET is installed correctly, you will see the following message on your screen:
Usage: dotnet [options]
Usage: dotnet [path-to-application]
Once you have the CLI installed to configure projects with VS Code, you need to know about the powerful open source object-relational database system that uses and extends the SQL language that is, PostgreSQL.
Note
You will first go through the instructions to install PostgreSQL for Windows followed by macOS, and then by Linux.
PostgreSQL has been used in Chapter 6, Entity Framework with SQL Server. Before you proceed with that chapter, you must install PostgreSQL on your system using the following steps:
Note
The screen shown in Figure 0.8 may change depending upon the latest release from the vendor.
The Stack Builder is used to download and install additional tools. The default installation contains all tools needed for the exercises and activities.
Note
It is better to type a password that you can easily memorize as it will be used to manage all your other credentials.
PostgreSQL server password is the password you will use when connecting to the PostgreSQL server and using the postgres user.
In order to explore the pgAdmin dashboard, move to the Exploring pgAdmin Dashboard section.
Install PostgreSQL on your macOS using the following steps:
Note
The following screenshots were taken for version 14.4 on macOS Monterey (version 12.2).
Make sure to note down the password safely for logging in to the PostgreSQL database.
Set the port number where you want to run the PostgreSQL server. Here the default Port number is set as 5432:
Finally, click on the Next button to start the installation process of the PostgreSQL database server on your system:
This completes the installation of PostgreSQL for the macOS. The next section will familiarize you with the PostgreSQL interface.
Once you have installed PostgreSQL in Windows and macOS, follow these steps to grasp the interface better:
This will open a Create – Database window.
A database with the name TestDatabase is now displayed within the dashboard:
Now your database is ready to be used for Windows and Mac environments.
In this example, you are using Ubuntu 20.04 for installation. Perform the following steps to do so:
$ sudo apt update
$ sudo apt install postgresql postgresql-contrib
Note
To install only PostgreSQL (not recommended without additional packages), use the command $ sudo apt install postgresql and then press Enter.
This installation process creates a user account called postgres that has the default Postgres role.
There are two ways to start the PostgreSQL CLI using the postgres user account:
Option 1 is as follows:
$ sudo -i -u postgres
$ psql
Note
Sometimes, while executing the preceding command, a psql error may be displayed as could not connect to server: No such file or directory. This is because of a port issue on your system. Due to this port blockage, the PostgreSQL application may not work. You can try the command again after some time.
$ q
Option 2 is as follows:
$ sudo -u postgres psql
$ q
$ sudo -u postgres psql
$ conninfo
$ q
Using this command, you can ensure that you are connected to the postgres database as the postgres user via port 5432. If you don't want to use the default user, postgres, you can create a new user for you.
$ sudo -u postgres createuser –interactive
The preceding command will ask the user to add the name of the role and its type.
Prompt:
Enter the name of the role to add: testUser
Shall the new role be a superuser? (y/n) y
This will create a new user with the name testUser.
$ sudo -u postgres createdb testdb
$ sudo -u testUser psql -d testdb
$ conninfo
$ q
Using this command, you can ensure that you are connected to the testdb database as the testUser user via port 5432.
With these steps, you have completed the PostgreSQL installation for Ubuntu.
Download the code from GitHub at https://packt.link/sezEm. Refer to these files for the complete code.
The high-quality color images used in this book can be found at https://packt.link/5XYmX.
If you have any issues or questions about installation, please email us at [email protected].