Book Image

C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition

Book Image

C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition

Overview of this book

If you want to build powerful cross-platform applications with C# 7 and .NET Core, then this book is for you. First, we’ll run you through the basics of C#, as well as object-oriented programming, before taking a quick tour through the latest features of C# 7 such as tuples, pattern matching, out variables, and so on. After quickly taking you through C# and how .NET works, we’ll dive into the .NET Standard 1.6 class libraries, covering topics such as performance, monitoring, debugging, serialization and encryption. The final section will demonstrate the major types of application that you can build and deploy cross-device and cross-platform. In this section, we’ll cover Universal Windows Platform (UWP) apps, web applications, mobile apps, and web services. Lastly, we’ll look at how you can package and deploy your applications so that they can be hosted on all of today’s most popular platforms, including Linux and Docker. By the end of the book, you’ll be armed with all the knowledge you need to build modern, cross-platform applications using C# and .NET Core.
Table of Contents (24 chapters)
C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Writing and compiling code using the .NET Core CLI tool


When you install Visual Studio 2017, or the .NET Core SDK, a Command Line Interface (CLI) tool named dotnet is installed as well as the .NET Core runtime.

dotnet has the following commands that all work on the project in the current folder:

  • dotnet new console: creates a new console application project

  • dotnet new classlib: creates a new assembly library project

  • dotnet new web: creates a new empty ASP.NET Core project

  • dotnet new mvc: creates a new ASP.NET Core MVC project

  • dotnet new webapi: creates a new ASP.NET Core Web API project

  • dotnet restore: downloads dependencies for the project

  • dotnet build: compiles the project

  • dotnet test: runs unit tests on the project

  • dotnet run: runs the project

  • dotnet migrate: migrates a .NET Core project created with the preview CLI tools to the current CLI tool MS Build format

  • dotnet pack: creates a NuGet package for the project

  • dotnet publish: compiles and publishes the project, either with dependencies or as a self-contained application

Note

You will learn how to build, package, publish, and deploy your .NET Core applications and assemblies in Chapter 16, Packaging and Deploying Your Code Cross-Platform.

Before we use CLI tools such as dotnet, we need to write some code!

Writing code using a simple text editor

If you are using Windows, start Notepad.

If you are using macOS, launch TextEdit. From the TextEdit menu, choose Preferences, clear the Smart quotes check box, and then close the dialog. From the Format menu, choose Make Plain Text.

Or run your favorite plain text editor.

Enter the following code:

    class MyApp { static void Main() {  
    System.Console.WriteLine("Hello, C#!"); } } 

Note

C# is case sensitive, meaning that you must type uppercase and lowercase characters exactly as shown in the preceding code. C# is not whitespace sensitive, meaning that it does not care if you use tabs, spaces, and carriage-returns to layout your code however you like.

You can type the code all in one line or spread it out over multiple lines and indent your lines. For example, the following code would also compile and have the same output:

    class  
          MyApp      { 
     static                   void  
    Main          (){System.       Console. 
        WriteLine(       "Hello, C#!");         }       } 

Of course, it's best to write your code in a way that other programmers, and yourself months or years later, can clearly read!

If you are using Windows Notepad

In Notepad, from the File menu, choose Save As....

In the dialog box, change to drive C: (or any drive which you want to use to save your projects), click on the New folder button, and name the folder Code. Open the Code folder, and click the New folder button, and name the folder Chapter01. Open the Chapter01 folder, and click the New folder button, and name the folder Ch01_HelloCS. Open the Ch01_HelloCS folder.

In the Save as type field, select All Files from the drop-down list to avoid appending the .txt file extension, and enter the file name as MyApp.cs, as shown in the following screenshot:

Your code in Notepad should look something like the following screenshot:

If you are using macOS TextEdit

In TextEdit, from the File menu, choose Save..., or press Cmd + S .

In the dialog box, change to your user folder (mine is named markjprice) or any directory in which you want to use to save your projects, click on the New Folder button, and name the folder Code. Open the Code folder, and click the New Folder button, and name the folder Chapter01. Open the Chapter01 folder, and click the New Folder button, and name the folder Ch01_HelloCS. Open the Ch01_HelloCS folder.

In the Plain Text Encoding field, select Unicode (UTF-8) from the drop-down list, uncheck the box for If no extension is provided, use ".txt" to avoid appending the .txt file extension, enter the filename as MyApp.cs, and click on Save, as shown in the following screenshot:

Compiling code using the .NET Core CLI tool

If you are using Windows, start Command Prompt.

If you are using macOS, launch Terminal.

At the prompt, enter the following command:

dotnet

You should see the following output describing the dotnet CLI tool:

Note

The output from the dotnet command-line tool will be identical on Windows, macOS, and Linux.

Enter the following commands at the prompt to:

  • Change to the folder for the project

  • Create a new console application in the directory

  • List the files that the dotnet command-line tool created

If you are using Windows, in Command Prompt, enter:

cd C:\Code\Chapter01\Ch01_HelloCS
dotnet new console
dir

If you are using macOS, in Terminal, enter:

cd Code/Chapter01/Ch01_HelloCS
dotnet new console
ls

Note

The first time that you execute a dotnet new command, your local package cache must be populated. This should only take a few moments.

You should see that the dotnet tool has created two new files for you:

  • Program.cs: source code for a simple console application

  • Ch01_HelloCS.csproj: a project file that lists dependencies and project-related configuration

For this example, we must delete the file named Program.cs since we have already created our own class called Program in the file named MyApp.cs.

If you are using Windows, in Command Prompt:

del Program.cs

If you are using macOS, in Terminal:

rm Program.cs

Note

In all future examples, we will use the Program.cs file generated by the tool rather than manually create our own.

Restoring packages and running the application

At the prompt, enter the following commands:

dotnet restore
dotnet run

After a few seconds, all the packages needed by our code will be downloaded, the source code will be compiled, and your application will run, as shown in the following output on macOS:

Your source code, the file MyApp.cs, has been compiled into an assembly named Ch01_HelloCS.dll in the subfolder bin/Debug/netcoreapp1.1. For now, this assembly can only be executed by the dotnet run command. In Chapter 16Packaging and Deploying Your Code Cross-Platform, you will learn how to package and publish assemblies for use on any operating system that supports .NET Core.

Fixing compiler errors

If the compiler displays errors, read them carefully, and fix them in your text editor. Save your changes and try again.

Note

At the prompt, you can press the up and down arrows on your keyboard to cycle through previous commands you have entered.

A typical error might be using the wrong case, a missing semicolon at the end of a line, or a mismatched pair of curly braces. For example, if you mistyped a lowercase m for the Main method, you would see the following error message:

error CS5001: Program does not contain a static 'Main' method
suitable for an entry point

Understanding Intermediate Language

The C# compiler (named Roslyn) used by the dotnet CLI tool converts your C# source code into intermediate language (IL) code and stores the IL in an assembly (a DLL or EXE file).

IL code statements are like assembly language instructions, but they are executed by .NET Core's virtual machine, known as the CoreCLR.

At runtime, the CoreCLR loads the IL code from the assembly, JIT (just-in-time) compiles it into native CPU instructions, and then it is executed by the CPU on your machine.

The benefit of this two-step compilation process is that Microsoft can create CLRs for Linux and macOS as well as for Windows. The same IL code runs everywhere because of the second compilation process that generates code for the native operating system and CPU instruction set.

Regardless of which language the source is written in, for example, C# or F#, all .NET applications use IL code for their instructions stored in an assembly. Microsoft and others provide disassembler tools that can open an assembly and reveal this IL code.

Note

Actually, not all .NET applications use IL code! Some use .NET Native's compiler to generate native code instead of IL code, improving performance and reducing memory footprint, but at the cost of portability.