Book Image

C# 7.1 and .NET Core 2.0 ??? Modern Cross-Platform Development - Third Edition

By : Mark J. Price
Book Image

C# 7.1 and .NET Core 2.0 ??? Modern Cross-Platform Development - Third Edition

By: Mark J. Price

Overview of this book

C# 7.1 and .NET Core 2.0 – Modern Cross-Platform Development, Third Edition, is a practical guide to creating powerful cross-platform applications with C# 7.1 and .NET Core 2.0. It gives readers of any experience level a solid foundation in C# and .NET. The first part of the book runs you through the basics of C#, as well as debugging functions and object-oriented programming, before taking a quick tour through the latest features of C# 7.1 such as default literals, tuples, inferred tuple names, pattern matching, out variables, and more. After quickly taking you through C# and how .NET works, this book dives into the .NET Standard 2.0 class libraries, covering topics such as packaging and deploying your own libraries, and using common libraries for working with collections, performance, monitoring, serialization, files, databases, and encryption. The final section of the book demonstrates the major types of application that you can build and deploy cross-device and cross-platform. In this section, you'll learn about websites, web applications, web services, Universal Windows Platform (UWP) apps, and mobile apps. 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.
Table of Contents (31 chapters)
Title Page
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface
2
Part 1 – C# 7.1
8
Part 2 – .NET Core 2.0 and .NET Standard 2.0
16
Part 3 – App Models
22
Summary
Index

Writing and compiling code using Visual Studio 2017


We will now create a similar application using Visual Studio 2017. If you have chosen to use Visual Studio for Mac or Visual Studio Code, I still recommend that you review these instructions and screenshots because Visual Studio for Mac and Visual Studio Code have 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 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 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.7.1. That drop-down list box does not affect .NET Core projects!

In the code editor, delete the statement on line 9 that says the following: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:

We want Console. Press the down arrow on your keyboard to highlight it. When Console is selected, 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 wl. IntelliSense shows two matching members containing these letters in title case, WindowLeft and WriteLine, 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

Navigate to Debug | 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

Navigate to Debug | Start Without Debugging or press Ctrl + F5.

After a few seconds, the status bar tells us that Build failed and an error message appears. Click on No.

Error List becomes active, as shown in the following screenshot:

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

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 highlight suggestions with three small grey dots under a potential problem. When you click on the dotted statement, a light bulb appears, and if you click on it, it provides suggestions for improvements, such as telling you that method names should begin with an uppercase character, as shown in the following screenshot:

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 window 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 C:\Code\Chapter01\HelloCS folder, and select the HelloCS.csproj file.

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

For the Startup Project option, click on Current selection, and then click on OK.

In Solution Explorer, click on any file inside the 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 on the file named MyApp.cs, as shown in the following screenshot:

Navigate to Build | Build HelloCS or press Shift + F6, 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:

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, navigate to View | Other Windows | 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">rn // 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.rn 
</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 preceding 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 was for C# 7. Roslyn 2.3 and later is for C# 7.1.

Other useful windows

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

  • Solution Explorer for managing projects and files
  • Team Explorer for source code management tools
  • Server Explorer 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, few of such shortcuts 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.