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 Microsoft Visual Studio 2017


We will now recreate a similar application using Visual Studio 2017. If you have chosen to use Visual Studio Code, I still recommend that you review these instructions and screenshots because Visual Studio Code has similar, although not as extensive, features.

I have been training students to use Visual Studio for over a decade, and I am always surprised at how many programmers fail to use the tool to their advantage.

Over the next few pages, I will walk you through typing a line of code. It may seem redundant, but you will benefit from seeing what help and information Visual Studio provides as you enter your code. If you want to become a fast and accurate coder, letting Visual Studio write most of your code for you is a huge benefit!

Writing code using Microsoft Visual Studio 2017

Start Visual Studio 2017.

Navigate to File | New | Project... or press Ctrl + Shift + N.

From the Installed | Templates list on the left, expand Visual C#, and choose .NET Core. In the list at the center, choose Console App (.NET Core). Enter the name Ch01_WelcomeDotNetCore, set the location to C:\Code, enter Chapter01 as the solution name, and click on OK or press Enter, as shown in the following screenshot:

Note

Ignore the target set to .NET Framework 4.6.2. That drop-down list box does not affect .NET Core projects!

Coding with Visual Studio's editor

In the code editor, delete the statement on line 9 that says, Console.WriteLine("Hello World!");

Inside the Main method, type the letters sy, as shown in the following screenshot, and note the IntelliSense menu that appears:

IntelliSense shows a filtered list of keywords, namespaces, and types that contain the letters sy and highlights the one that starts with sy, which happens to be the namespace that we want---System.

Type a dot (also known as decimal point or full stop).

IntelliSense automatically completes the word System for you, enters the dot, and displays a list of types, such as AggregateException and Action, in the System namespace, as shown in the following screenshot:

Type the letters con, IntelliSense shows a list of matching types and namespaces, as shown in the following screenshot:

If the one you want is not selected, you can press the up and down arrows on your keyboard to highlight it. For now, Console is already selected, so just type a dot.

IntelliSense shows a list of the members of the Console class, as shown in the following screenshot:

Note

Members include properties (attributes of an object, such as BackgroundColor), methods (actions the object can perform, such as Beep), events, and other related things.

Type the letters wr. IntelliSense shows two matching members containing these letters, as shown in the following screenshot:

Use the down arrow to highlight WriteLine and then type an open parenthesis (.

IntelliSense autocompletes WriteLine and enters a pair of parentheses.

You will also see a tooltip telling you that the WriteLine method has 18 variations, as shown in the following screenshot:

Type a double quote ("). IntelliSense enters a pair of double quotes for you and leaves the keyboard cursor in between them.

Type the text Welcome, .NET Core!, as shown in the following screenshot:

The red squiggle at the end of the line indicates an error because every C# statement must end in a semicolon. Move the cursor to the end of the line and type a semicolon to fix the error.

Compiling code using Visual Studio 2017

From the Debug menu, choose Start Without Debugging or press Ctrl + F5.

Visual Studio's status bar tells us that Build started..., then Build succeeded, and then your console application runs in a command prompt window, as shown in the following screenshot:

To save space in this book and to make the output clearer, I will usually not include screenshots of output from console applications as I did in the previous screenshot. Instead, I will show the output like this:

Welcome, .NET Core!

Fixing mistakes with the error list

Let's make two deliberate errors:

  • Change the M of the Main method to the lowercase letter m.

  • Delete the e at the end of the method name, WriteLine.

From the Debug menu, choose Start Without Debugging or press Ctrl + F5.

After a few seconds, the status bar tells us that Build failed and an error message appears, as shown in the following screenshot:

Click No.

The Error List becomes active, as shown in the following screenshot. You can also view the Error List by pressing Ctrl + W, E:

The list can be filtered to show Errors, Warnings, and Messages by clicking on the toggle buttons in the toolbar at the top of the Error List.

If an error shows a file and a line number, for example File: Program.cs and Line: 9, then you can double-click on the error to jump to that line causing the problem.

If it's a more general error, such as the missing Main method, the compiler can't tell you a useful line number. You might want a method named main as well as a method named Main (remember that C# is case sensitive, so you're allowed to do that). However, Visual Studio can also analyze your code and provide messages with suggestions for improvements, such as telling you that method names should begin with an uppercase character.

As shown in the preceding screenshot, fix the two errors, and rerun the application to ensure that it works before you continue. Note that the Error List updates to show no errors.

Adding existing projects to Visual Studio 2017

Earlier, you created a project using the dotnet CLI tool. Now that you have a solution in Visual Studio 2017, you might want to add the earlier project to the solution.

Navigate to File | Add | Existing Project..., browse to the folder C:\Code\Chapter01\Ch01_HelloCS, and select the file Ch01_HelloCS.csproj.

To be able to run this project, in the Solution Explorer, right-click Solution 'Chapter01' (2 projects), and choose Properties or press Alt + Enter.

For the Startup Project, click Current selection, and click OK.

In Solution Explorer, click on any file inside the Ch01_HelloCS project, and then press Ctrl + F5, or navigate to Debug | Start Without Debugging.

Autoformatting code

Code is easier to read and understand if it is consistently indented and spaced out.

If your code can compile, then Visual Studio 2017 can automatically format it, nicely spaced and indented for you.

In Solution Explorer, double-click the file named MyApp.cs, as shown in the following screenshot:

Navigate to Build | Build Ch01_HelloCS, or press Shift + F6 and wait for your code to build, and then navigate to Edit | Advanced | Format Document, or press Ctrl + E, D. Your code will be autoformatted, as shown in the following screenshot:

Note

In Visual Studio Code, either right-click and choose Format Document, or press Alt + Shift + F.

Experimenting with C# Interactive

Although Visual Studio has always had an Immediate window with limited read-eval-print loop (REPL) support, Visual Studio 2017 includes an enhanced window with full IntelliSense and color syntax code named C# Interactive.

In Visual Studio 2017, from the View menu, choose Other Windows, and then C# Interactive.

We will write some interactive code to download the About page from Microsoft's public website.

Note

This is just an example. You don't need to understand the code yet!

At the C# Interactive prompt, we will enter commands to do the following:

  • Reference the System.Net.Http assembly

  • Import the System.Net.Http namespace

  • Declare and instantiate an HTTP client variable

  • Set the client's base address to Microsoft's website

  • Asynchronously wait for a response to a GET request for the About page

  • Read the status code returned by the web server

  • Read the content type header

  • Read the contents of the HTML page as a string

Type each of the following commands after the > prompt and then press Enter:

> #r "System.Net.Http"
> using System.Net.Http;
> var client = new HttpClient();
> client.BaseAddress = new Uri("http://www.microsoft.com/");
> var response = await client.GetAsync("about");
> response.StatusCode
OK
> response.Content.Headers.GetValues("Content-Type")
string[1] { "text/html" }
> await response.Content.ReadAsStringAsync()
"<!DOCTYPE html ><html 
xmlns:mscom="http://schemas.microsoft.com/CMSvNext" 
xmlns:md="http://schemas.microsoft.com/mscom-data" lang="en" 
xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="X-UA-
Compatible" content="IE=edge" /><meta charset="utf-8" /><meta 
name="viewport" content="width=device-width, initial-scale=1.0" 
/><link rel="shortcut icon" 
href="//www.microsoft.com/favicon.ico?v2" /><script 
type="text/javascript" 
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-
1.7.2.min.js">\r\n // Third party scripts and code linked to 
or referenced from this website are licensed to you by the parties 
that own such code, not by Microsoft. See ASP.NET Ajax CDN Terms of 
Use - http://www.asp.net/ajaxlibrary/CDN.ashx.\r\n 
</script><script type="text/javascript" 
language="javascript">/*<![CDATA[*/if($(document).bind("mobileinit
",function(){$.mobile.autoInitializePage=!1}),navigator.userAgent.ma
tch(/IEMobile\\/10\\.0/)){var 
msViewportStyle=document.createElement("style ...

The following screenshot shows what Visual Studio 2017 should look like after you've entered the above commands into the C# Interactive window:

Note

Roslyn is the name of the C# compiler. Roslyn version 1.0 was for C# 6. Roslyn version 2.0 is for C# 7.

Other useful windows

Visual Studio 2017 has lots of other useful windows, including the following:

  • The Solution Explorer window for managing projects and files

  • The Team Explorer window for source code management tools

  • The Server Explorer window for managing database connections and resources to manage in Microsoft Azure

If you can't see a window you need, go to the View menu to make it reappear or learn its keyboard shortcut, some of which are shown in the following screenshot:

Note

If your keyboard shortcuts are different from the ones in the preceding screenshot, it is because you picked a different set when you installed Visual Studio. You can reset your keyboard shortcuts to match the ones used in this book by clicking on the Tools menu, then clicking on Import and Export Settings..., choosing Reset all settings, and then choosing to reset to the Visual C# settings collection.