C# 6 and .NET Core 1.0: Modern Cross-Platform Development

4.2 (23 reviews total)
By Mark J. Price
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Hello, C#! Welcome, .NET Core!

About this book

With the release of .NET Core 1.0, you can now create applications for Mac OS X and Linux, as well as Windows, using the development tools you know and love. C# 6 and .NET Core 1.0 has been divided into three high-impact sections to help start putting these new features to work.

First, we'll run you through the basics of C#, as well as object-orient programming, before taking a quick tour through the latest features of C# 6 such as string interpolation for easier variable value output, exception filtering, and how to perform static class imports. We'll also cover both the full-feature, mature .NET Framework and the new, cross-platform .NET Core.

After quickly taking you through C# and how .NET works, we'll dive into the internals of the .NET class libraries, covering topics such as performance, monitoring, debugging, internationalization, serialization, and encryption. We'll look at Entity Framework Core 1.0 and how to develop Code-First entity data models, as well as how to use LINQ to query and manipulate that data.

The final section will demonstrate the major types of applications that you can build and deploy cross-device and cross-platform. In this section, we'll cover Universal Windows Platform (UWP) apps, web applications, and web services. Lastly, we'll help you build a complete application that 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.

Publication date:
March 2016
Publisher
Packt
Pages
550
ISBN
9781785285691

 

Chapter 1. Hello, C#! Welcome, .NET Core!

This chapter is about setting up your development environment, understanding the similarities and differences between .NET Core, .NET Framework, and .NET Native, and using various tools to create the simplest application possible with C#.

Most people learn complex topics by imitation and repetition rather than reading a detailed explanation of theory. So, I will not explain every keyword and step. The idea is to get you to write some code, build an application, and see it run. You don't need to know the details of how it all works yet.

In the words of Samuel Johnson, author of the English dictionary of 1755, I have likely committed "a few wild blunders, and risible absurdities, from which no work of such multiplicity is free." I take sole responsibility for these and hope you appreciate the challenge of my attempt to "lash the wind" by writing this book about .NET Core 1.0 during its rocky birth in the early months of 2016.

This chapter covers the following topics:

  • Setting up your development environment

  • Understanding the .NET Framework, .NET Core, and .NET Native

  • Writing and compiling code by using the Developer Command Prompt

  • Writing and compiling code by using Microsoft Visual Studio 2015

  • Targeting the .NET Core

  • Managing source code with GitHub

 

Setting up your development environment


Before you start programming, you will need to set up your Interactive Development Environment (IDE) that includes a code editor for C#. The best IDE to choose is Microsoft Visual Studio 2015, but it only runs on the Windows operating system.

Using alternative C# IDEs

There are alternative IDEs for C#, for example, MonoDevelop, JetBrains Project Rider, and Microsoft Visual Studio Code. They each have versions available for Windows, Linux, and Mac OS X, allowing you to write code on one operating system and deploy to the same, or a different, one:

Cloud9 is a web browser-based IDE, so it's even more cross-platform than the others. here is the link:

https://c9.io/web/sign-up/free

In Chapter 15, Taking C# Cross-Platform, I will show you how to use Visual Studio Code running on Mac OS X to create an ASP.NET Core 1.0 web application that can be deployed to Windows, Mac OS X, or Linux operating systems, or to Docker containers.

Tip

Linux and Docker are popular server host platforms because they are relatively lightweight and more cost-effectively scalable when compared to operating system platforms that are designed for end users, such as Windows and Mac OS X.

Using Visual Studio 2015 on Windows 10

You can use Windows 7 or later to complete most of the chapters in this book, but you will have a better experience if you use Windows 10.

Tip

If you don't have Windows, I recommend that you create a virtual machine (VM) to use for development. You can choose any cloud provider, but Microsoft Azure has preconfigured VMs that include properly licensed Windows and Visual Studio 2015. You only pay for the minutes your VM is running, so it is a way for users of Linux, Mac OS X, and older Windows versions to have all the benefits of using Visual Studio 2015. Refer to Appendix B, Creating a Virtual Machine for Your Development Environment for more information.

Since October 2014, Microsoft has made a professional-quality edition of Visual Studio available to everyone for free. It is called the Community Edition.

Tip

Microsoft has combined all its free developer offerings in a program called Visual Studio Dev Essentials. This includes the Community Edition, the free level of Visual Studio Team Services, Azure credits for test and development, and free training from Pluralsight, Wintellect, and Xamarin.

Installing Microsoft Visual Studio 2015

Download and install Microsoft Visual Studio Community 2015 with Update 1 or higher.

Choosing the default installation

If you prefer a smaller, faster installation then choose Default because it only requires 8 GB and should complete the installation in about an hour. With this choice, as shown in the following screenshot, you will be able to complete the first two-thirds of this book. To complete the rest of the book, you can later add additional features, such as support for building Universal Windows Platform (UWP) apps, via Programs and Features in the Control Panel:

If you chose Default, then skip to the Completing the Installation section.

Choosing the custom installation

If you have 34 GB of free disk space and can wait for several hours, then in the installation dialog, choose Custom, and then click on Next. Select the following features:

  • Under Windows and Web Development, tick the following checkboxes:

    • Microsoft SQL Server Data Tools

    • Microsoft Web Developer Tools

    • Universal Windows App Development Tools

  • Under Cross Platform Mobile Development, tick the following checkbox:

    • C#/.NET (Xamarin)

  • Under Common Tools, tick the following checkboxes:

    • Git for Windows

    • GitHub Extension for Visual Studio

Click on Next:

Note

If you have the Home edition of Windows 10, then you will not be able to install emulators for Windows Phone because they require Hyper-V support.

Tip

You can choose to install everything if you want support for languages such as C++, Python, and F#, but these will not be covered in this book.

Completing the installation

On the license terms dialog, click on Install. Wait for the files to download and install.

Tip

While you wait for Visual Studio to install, you can jump to the Understanding .NET Framework, .NET Core, and .NET Native section in this chapter.

Signing in to Visual Studio

The first time that you run Visual Studio, you will be prompted to sign in:

If you have a Microsoft account, for example, a Hotmail, MSN, Live, or Outlook e-mail address, you can use that account. If you don't, then register for a new one at the following link:

https://signup.live.com/

Choosing development settings

After signing in, you will be prompted to choose Development Settings. Choose Visual C# to configure keyboard shortcuts and a default window layout that works best for C# programmers, as shown in the following screenshot:

After you click on Start Visual Studio, you will see the Visual Studio user interface with the Start Page open in the central area. Like most Windows desktop applications, Visual Studio has a menu bar, a toolbar for common commands, and a status bar at the bottom. On the right is the Solution Explorer window that will list all of your open projects, as shown in the following screenshot:

To have quick access to Visual Studio in the future, right-click on its entry in the Windows taskbar and select Pin this program to taskbar:

Updating extensions and products

In the top-right corner of Visual Studio, you will see a flag that has a number next to it. These are notifications of extensions and product updates.

Click on the flag to display the Notifications window, as shown in the following screenshot:

In the Notifications window, click on each entry to install the update. You can install these updates at a later time if you prefer, but it is best to keep your software up-to-date to avoid bugs and security holes. The following screenshot shows an extension downloading and installing:

Using older versions of Visual Studio

If you want to use a free version of Visual Studio older than 2015, then you can use one of the more limited Express editions. A lot of the code in this book will work with older versions if you bear in mind when the following features were introduced:

Year

C#

Features

2005

2

Generics with <T>

2008

3

Lambda expressions with => and manipulating sequences with LINQ (from, in, where, orderby, ascending, descending, select, group, into)

2010

4

Dynamic typing with dynamic and multithreading with Task

2012

5

Simplifying multithreading with async and await

2015

6

string interpolation with $"", importing static types with using static, and other refinements.

 

Understanding .NET Framework, .NET Core, and .NET Native


.NET Framework, .NET Core, and .NET Native are related platforms for developers to build applications and services upon.

Understanding .NET Framework platform

Microsoft's .NET Framework is a development platform that includes a Common Language Runtime (CLR) that manages the execution of code and a rich library of classes for building applications.

Microsoft designed the .NET Framework to have the possibility of being cross-platform, but Microsoft put their implementation effort into making it work best with Windows.

Practically speaking, the .NET Framework is Windows-only.

Understanding the Mono project

The open source community developed a cross-platform .NET implementation named the Mono project (http://www.mono-project.com/).

Mono is cross-platform, but it fell well behind Microsoft's implementation of .NET Framework. It has found a niche as the foundation of the Xamarin mobile platform.

Understanding the .NET Core platform

Today, we live in a truly cross-platform world. Modern mobile and cloud development have made Windows a much less important operating system. So, Microsoft has been working on an effort to decouple the .NET Framework from its close ties with Windows.

While rewriting .NET to be truly cross-platform, Microsoft has taken the opportunity to refactor .NET, to remove major parts that are no longer considered "core".

This new product is branded as the .NET Core 1.0, which includes a cross-platform implementation of the CLR, known as CoreCLR , and a streamlined library of classes known as CoreFX.

Streamlining .NET

.NET Core 1.0 is much smaller than the current version of the .NET Framework because a lot has been removed.

For example, Windows Forms and Windows Presentation Foundation (WPF) can be used to build graphical user interface (GUI) applications, but they are tightly-bound to Windows, so they have been removed from the .NET Core. The latest technology for building Windows apps is the Universal Windows Platform (UWP). You will learn about it in Chapter 13, Building Universal Windows Platform Apps Using XAML.

ASP.NET Web Forms and Windows Communication Foundation (WCF) are old web applications and service technologies that fewer developers choose to use today, so they have also been removed from the .NET Core. Instead, developers prefer to use ASP.NET MVC and ASP.NET Web API. These two technologies have been refactored and combined into a new product that runs on the .NET Core, named ASP.NET Core 1.0. You will learn about it in Chapter 14, Building Web Applications and Services Using ASP.NET Core.

The Entity Framework (EF) 6.x is an object-relational mapping technology for working with data stored in relational databases, such as Oracle and Microsoft SQL Server. It has gained baggage over the years, so the cross-platform version has been slimmed down and named Entity Framework Core 1.0. You will learn about it in Chapter 8, Working with Relational Data Using the Entity Framework.

Some data types in .NET that are included with both the .NET Framework and the .NET Core have been simplified by removing some members. For example, in the .NET Framework, the File class has both a Close and Dispose method, and either can be used to release the file resources. In .NET Core, there is only the Dispose method. This reduces the memory footprint of the assembly and simplifies the API.

Tip

The .NET Framework 4.6 is about 200 MB. The .NET Core 1.0 is about 11 MB. Eventually, the .NET Core may grow to a similar larger size. Microsoft's goal is not to make the .NET Core smaller than the .NET Framework. The goal is to componentize .NET Core to support modern technologies and to have fewer dependencies so that deployment requires only those components that your application really needs.

The future of .NET

The .NET Core is the future of .NET, but in my opinion, we are not there yet. .NET Core 1.0 is a great start, but it will take another version or two to become as mature as the current version of the .NET Framework.

This book will focus features available in .NET Core, but will use the .NET Framework when features have not (yet) been implemented in the .NET Core.

Tip

One of the reasons we picked this cover image for this book is that you can think of .NET Core as a new dawn for .NET. The .NET Framework has become overgrown, like a dense forest, and the .NET Core is like finding a clearing or glade within it. It's a fresh start.

Understanding the .NET Native platform

Another .NET initiative is .NET Native which compiles C# code to native CPU instructions ahead-of-time (AoT) rather than using the CLR to compile IL just-in-time (JIT) to native code later.

The .NET Native compiler improves execution speed and reduces the memory footprint for applications. It supports the following:

  • UWP apps for Windows 10, Windows 10 Mobile, Xbox One, HoloLens, and Internet of Things (IoT) devices such as Raspberry Pi

  • Server-side web development with ASP.NET Core 1.0

  • Console applications for use on the command line

Comparing .NET technologies

The following table summarizes and compares Microsoft's three .NET technologies:

Platform

Feature set

C# compiles to

Host OSes

.NET Framework

Mature and extensive

Intermediate Language (IL) code

Windows only

.NET Core

Brand-new and somewhat limited

Windows, Linux, Mac OS X, Docker

.NET Native

Brand-new and very limited

Native code

 

Writing and compiling code using the Developer Command Prompt


When you install Visual Studio, other tools are installed too. One of those tools is the Developer Command Prompt for VS2015 that has its path set to find developer tools such as the C# compiler.

Writing code using Notepad

Start Notepad (or your favorite text editor) and enter the following code:

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

You can type the code all on one line or spread it out over multiple lines and indent your lines to make it easier to read.

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 and spaces and carriage-returns to lay out your code however you like.

From the File menu, choose Save As.

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

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 myfirstapp.cs, as shown in the following screenshot:

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

Compiling code using the Developer Command Prompt

Start the Developer Command Prompt for VS2015 by typing the letters deve in the Windows 10 Search box, as you can see in the following screenshot. You will also find it on the Start Menu or Start Screen listed in All apps in the Visual Studio 2015 folder:

At the Command Prompt, enter the commands to do the following:

  • Change to the C:\Code folder

  • Compile the source code using the C# compiler

  • Request a directory listing

  • Run the application by entering the name of the EXE

Here are the commands:

cd C:\Code
csc myfirstapp.cs
dir
myfirstapp

The output in the Command Prompt window should look like this:

Note that your source code, the file named myfirstapp.cs, has been compiled into an assembly named myfirstapp.exe. When you enter the name of the assembly, it is loaded and executed by .NET Framework 4.6 and its CLR.

You can copy the myfirstapp.exe file onto any computer with Windows 10 and it will run correctly because all copies of Windows 10 have .NET Framework 4.6 installed. Actually, you can copy the file onto a computer with an older version of Windows as long as it has .NET Framework 4.0 or later installed.

Fixing compiler errors

If the compiler displays errors, read them carefully, and fix them in Notepad. Save your changes and recompile.

Tip

At the Command 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 semi-colon at the end of a line, or a mismatched pair of curly braces. For example, if you had mistyped a lowercase m for the Main method you would see this error message:

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

Decompiling code using ILDASM

The C# compiler converts your 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 the .NET virtual machine known as the Common Language Runtime (CLR).

At runtime, the CLR loads the IL code from the assembly, JIT 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 Mac OS X 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, all .NET applications use IL code for their instructions, stored in an assembly. Microsoft provides a tool that can open an assembly and reveal this IL code.

Tip

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

Disassembling compiled assemblies

Disassembling a compiled assembly is an advanced technique. I will walk you through the process, but do not worry about fully understanding what you are seeing yet!

Start the IL Disassembler by entering the following at the Developer Command Prompt:

ildasm myfirstapp.exe

You will see the IL DASM tool with the compiled EXE assembly loaded:

Double-click on MANIFEST in the tree view to show the metadata version (4.0.30319) of .NET and the Microsoft Core Library (mscorlib) assembly version (4.0.0.0) that this assembly needs to run. The following screenshot tells us that to run this assembly, we would need .NET Framework 4.0 or later installed:

Close the MANIFEST window, expand Program, and then double-click on the Main method. Note the IL instructions: ldstr (load string), nop (no operation), and ret (return). Remember that IL is an assembly language that is executed by the .NET CLR:

Anyone can use this tool to see any .NET assembly's IL code. Don't panic! This is not a reason to avoid C#.

All applications are lists of instructions that must be visible to the machine that runs it. If the machine can read these instructions, so can anything else. Therefore, all software can be reverse-engineered. It's just a matter of the effort required. .NET just happens to make it very easy!

Tip

ILSpy is a popular open source tool that does everything IL DASM does and can also reverse-engineer the IL code into C# or Visual Basic .NET source code. I used this tool for a client who had lost the source code for an assembly and needed to recover it!

 

Writing and compiling code using Microsoft Visual Studio 2015


We will now recreate the same application using Microsoft Visual Studio 2015.

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 slowly 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, accurate coder, letting Visual Studio write most of your code for you is a huge benefit!

Writing code using Visual Studio 2015

Start Microsoft Visual Studio 2015.

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

At the top of the New Project dialog box, choose .NET Framework 4.6.1 (or later). From the Installed Templates list on the left, choose Visual C#. In the list at the center, choose Console Application. Enter the name Ch01_MyFirstApp, set the location to C:\Code, enter Chapter01 as the solution name, and click on OK or press Enter:

In the code editor, inside the Main method, press Enter to insert a new line between the innermost braces { }, and then type the letters sy, as you can see in the following screenshot:

Note that IntelliSense shows a list of keywords, namespaces, and types that contain the letters sy, and highlights the first 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 and namespaces, such as AccessViolationException and Action, in the System namespace, as shown in the following screenshot:

Type the letters con and IntelliSense shows a list of matching types and namespaces:

Press the down arrow on your keyboard to highlight Console, and then type a dot.

IntelliSense shows a list of the members of the Console class:

Tip

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

Type the letters wr. IntelliSense shows two matching members containing these letters:

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 19 variations:

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

Type the text Hello C#!, 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 by pressing End, and type a semicolon to fix the error.

Compiling code using Visual Studio

From the Debug menu, choose Start Without Debugging or press Ctrl + F5. Your completed application runs in a console window and closes when you press any key:

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

Hello C#!

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.

On the Build menu, choose Build Ch01_MyFirstApp or press Shift + F6.

After a few seconds, the status bar tells us that the build failed and the error list is activated. You can also view the error list by pressing Ctrl + W, E:

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

If an error shows the line number, for example Line 13 in the preceding screenshot, then you can double-click on the error to jump to the line causing the problem.

If it's a more general error, such as the missing Main method, the compiler can't tell you the 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).

Fix the two (as shown in the preceding screenshot) errors before you continue. Note that the error list updates to show no errors.

Experimenting with C# Interactive

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

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

Tip

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

  • Wait asynchronously 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.match(/IEMobile\\/10\\.0/)){var msViewportStyle=document.createElement(\"style ...

Other useful windows

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

  • The Solution Explorer window for managing all the projects and files you work on

  • The Team Explorer window for source code management tools, such as GitHub

  • The Server Explorer window for managing database connections

If you ever can't see a window you need, go to the View menu to make it reappear or learn its keyboard shortcut, as shown here:

Tip

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.

 

Targeting the .NET Core


For 15 years, .NET programmers have been targeting the .NET Framework, so there are many projects that may need to move from Windows-only to cross-platform by retargeting to the .NET Core.

Understanding the .NET Portability Analyzer

To ensure that a project will work cross-platform, we can install and run the Visual Studio 2015 extension named .NET Portability Analyzer.

It allows you to choose multiple platforms that you would like to target and then scans your compiled assemblies, passes a list of the types and methods that you use to a web service, and produces a report that lists which ones are not supported on each platform along with recommendations for fixes.

Installing the .NET Portability Analyzer

In Visual Studio, go to the Tools menu and choose Extensions and Updates….

On the left-hand side of the dialog, click on Online. In the Search Visual Studio Gallery box, type portability and press Enter.

Click on the .NET Portability Analyzer entry and then click on the Download button. Once the extension is installed, restart Visual Studio:

Configuring the .NET Portability Analyzer

In Visual Studio, go to the Tools menu and choose Options.

In the Options dialog box, scroll down through the left-hand side list and choose .NET Portability Analyzer. In the Target Platforms section, deselect everything except for the following:

  • .NET Core (Cross-platform) 1.0 (shown as 5.0 in the following screenshot)

  • .NET Framework 4.5

  • .NET Native 1.0

  • ASP.NET Core 1.0 (shown as ASP.NET 5 in the screenshot below):

Tip

Microsoft Azure has a Platform-as-a-Service (PaaS) feature named Cloud Services, which is limited to the .NET Framework 4.5; this is why it is a common target platform to check with the analyzer.

Analyzing a solution

In Visual Studio, open the previous solution, named Chapter01. In the Solution Explorer window, right-click on the project named Ch01_MyFirstApp (not the solution), choose Analyze, and then choose Analyze Assembly Portability.

After a few seconds, a report will display in the main area.

Tip

Be patient with the .NET Portability Analyzer because it has to send data to a web service and wait for a response.

Note that the Console class in the System namespace and its WriteLine method are supported by the following:

  • .NET Core (Cross-Platform) 1.0 (shown as 5.0 in the following screenshot)

  • .NET Framework 4.5

  • ASP.NET Core 1.0 (shown as ASP.NET 5 in the following screenshot)

However, it is not supported by .NET Native 1.0:

Note

At the time of writing this, the .NET Portability Analyzer has not been updated to show the new version branding for .NET Core and related products, which can be found at http://www.hanselman.com/blog/ASPNET5IsDeadIntroducingASPNETCore10AndNETCore10.aspx.

Press Ctrl + W, E to view the error list, which has also been populated. As we saw earlier, double-clicking on an error will jump the code editor to the line that could cause an issue:

.NET Portability and this book

I used the .NET Portability Analyzer while writing all the code in this book to ensure that, whenever possible, I can show you code that will work cross-platform using the .NET Core 1.0. If there are useful features that aren't cross-platform yet, then I will point that out in the text. Hopefully, they will be implemented in .NET Core in future versions.

Creating new projects for the .NET Core

Let's recreate the console application, but this time, target the .NET Core from the start.

Managing .NET Core development with Command Line Tools

There are two sets of command-line tools that you can use to manage the .NET Core:

  • .NET Version Manager, .NET Execution Environment, .NET Development Utilities (dnvm, dnx, dnu): These were used by Microsoft during the initial development of the .NET Core between 2013 and 2015. They are installed as part of Visual Studio 2015. These tools will be deprecated with the final release of the .NET Core.

  • .NET CLI (dotnet): This is a driver, which will be used by the final release of the .NET Core. It provides a simplified layer on top of other underlying tools. The .NET CLI must be installed separately.

Tip

At the time of writing, the DNX tools are more advanced than the .NET CLI, so in Chapter 15, Taking C# Cross-Platform, I will need to show you how to use both sets of tools. For this chapter, we can use the newer CLI tool because we are only using basic features. I recommend that you browse http://cs6dotnetcore.azurewebsites.net/ for information about changes between the time of writing this book and the release of the final versions of .NET Core 1.0 and its related technologies and tools.

Installing the .NET Command Line Tools

First, we must install the .NET Command Line Tools (CLI).

Start Microsoft Edge and go to the https://github.com/dotnet/cli.

Scroll down the page to find the Installers section and click on the link to download the MSI file for Windows. Open the file and install.

Creating a .NET Core application using Command Line Tools

Start the Developer Command Prompt for VS2015. At the prompt, enter the following command:

dotnet

You should see the following output:

Enter the following at the prompt to create a new directory, change to it, create a new console application in the directory, and then list the files it created:

cd C:\Code\Chapter01
mkdir Ch01_MySecondApp
cd Ch01_MySecondApp
dotnet new
dir

You should see that the dotnet tool has created three new files for you: NuGet.Config, Program.cs, and project.json.

At the prompt, enter the following to start Notepad for editing the Program class:

notepad Program.cs

In Notepad, modify the WriteLine statement as follows:

Console.WriteLine("Hello C#, Welcome .NET Core!");

Save changes and exit Notepad.

At the prompt, enter the following commands:

dotnet restore
dotnet run

After a few seconds, all the dependency packages will be downloaded and your application will run, showing the following output:

To compile the source code into an assembly containing IL code, enter the following command:

dotnet build

The output in the Command Prompt window should look like this:

Enter the following commands to change to a subdirectory, list the files in it, and execute the compiled console application:

cd bin\Debug\dnxcore50
dir
Ch01_MySecondApp

Tip

The Debug is the name of the configuration and dnxcore50 is the name of the framework. This will change in the release version of the .NET Core.

Creating a .NET Core application using Visual Studio 2015

Start Visual Studio 2015 and open the Chapter01 solution.

In Visual Studio, navigate to File | Add | New Project.

In the Add New Project dialog box, in the Installed Templates list on the left-hand side, choose Visual C#. In the list at the center, choose Console Application (Package). Enter the name Ch01_DotNetCore, and click on OK or press Enter:

In the Solution Explorer window, right-click on the solution named Chapter01 and choose Properties.

Set the Startup Project to Current selection and click on OK.

Inside the Main method of the Program class, enter the following statements:

Console.WriteLine("Welcome, .NET Core!");
Console.ReadLine();

As you type code, you will notice that Visual Studio shows you which types and methods might not be available when targeting .NET Core. For example, the BufferHeight property is available when targeting the .NET Framework but not the .NET Core, as shown in the following screenshot as DNX 4.5.1 and DNX Core 5.0 respectively:

You can tell the compiler to include statements available only when .NET Framework is available by using conditional compilation symbols, as follows:

#if DNX451
    Console.BufferHeight = 300;
#elseif DNXCORE50
    // some alternative for .NET Core
#endif

Tip

In Chapter 5, Using Specialized .NET Types, you will learn more about conditional compilation symbols so that you can create projects that target both the .NET Framework and the .NET Core with a single code base.

Note

The names of the conditional compilation symbols will change in the future. Visit https://github.com/dotnet/corefx/blob/master/Documentation/architecture/net-platform-standard.md for more information.

In the Solution Explorer window, double-click on Properties for the Ch01_DotNetCore project.

In the Properties window, click on the Debug tab, select the Use Specific Runtime checkbox, and select the latest version of the .NET Core platform for the x64 CPU architecture, as shown in the following screenshot:

In the Visual Studio Debug menu, choose Start or press F5.

Note that the Command Prompt window shows that the console application is running the dnx-coreclr-win-x64.1.0.0-rc1-update1 runtime:

Tip

Throughout the first half of this book, I will show example code by creating console applications, so you can decide if you want to target the .NET Framework by choosing Console Application, or target the .NET Core by choosing Console Application (Package).

 

Managing source code with GitHub


Git is a commonly used source code management system. GitHub is a company, website, and desktop application that makes it easier to manage Git.

Visual Studio 2015 has built-in support for using Git with GitHub as well as Microsoft's own source code management system, named Visual Studio Team Services.

I used GitHub to store solutions to all the practical exercises at the end of each chapter.

Using the Team Explorer window

In Visual Studio, navigate to View | Team Explorer menu to see the Team Explorer window:

Although it is a good idea to sign up with an online source code management system provider, you can clone a GitHub repository without signing up for an account.

Cloning a GitHub repository

In the Team Explorer window, expand Local Git Repositories, click on the Clone menu, and then enter the following URL of a Git repository to clone it:

https://github.com/markjprice/cs6dotnetcore.git

Enter a path for the cloned Git repository:

C:\Code\Repos\cs6dotnetcore

Click on the Clone button:

Wait for the Git repository to clone locally:

You will now have a local copy of the complete solutions to all the hands-on practice exercises for this book.

Managing a GitHub repository

Double-click on the cs6dotnetcore repo to open a detail view.

You can click on the options in the Project section to view Pull Requests and Issues, and other aspects of a repository.

You can double-click on an entry in the Solutions section to open it in the Solution Explorer:

 

Practicing and exploring


Test your knowledge and understanding by answering some questions, get some hands-on practice, and explore, with deeper research into the topics covered in this chapter.

Exercise 1.1 – test your knowledge

Answer the following questions:

  1. Why can a programmer use different languages to write applications that run on .NET?

  2. What do you type at the Command Prompt to compile the C# source code?

  3. What is the Visual Studio 2015 keyboard shortcut to save, compile, and run an application, without attaching the debugger?

  4. What is the Visual Studio 2015 keyboard shortcut to view the error list?

  5. What does ildasm.exe do?

  6. Is the .NET Core better than the .NET Framework?

  7. How is .NET Native different from the .NET Core?

  8. What does the .NET Portability Analyzer do?

  9. What is the difference between Git and GitHub?

  10. What is the name of the entry-point method of a .NET application and how should it be declared?

Exercise 1.2 – practice managing Visual Studio Windows

Practice closing and viewing windows, such as Error List and Toolbox.

You can pin, unpin, float, and rearrange windows by dragging their title bars. As you do so, Visual Studio will show blue tinted boxes and overlays to help you to understand where the window will be moved when you release the mouse button.

Tip

You can always reset Visual Studio back to one of the default layouts by clicking on the Tools menu and Import and Export Settings….

Exercise 1.3 – practice coding anywhere

You do not need Visual Studio to practice writing C#. Simply go to the .NET Fiddle website (https://dotnetfiddle.net/) and start coding. It's also a great way to share snippets of C# code with other developers:

Exercise 1.4 – explore topics

Use the following links to read more details about the topics covered in this chapter:

 

Summary


In this chapter, we set up the development environment, we used the Developer Command Prompt to compile and decompile an application, we used Visual Studio to create the same application and explore the features that make it so easy to use for development, and we discussed the differences between the .NET Framework, the .NET Core, and .NET Native.

In the next chapter, you will learn to speak C#.

About the Author

  • Mark J. Price

    Mark J. Price is a Microsof Certifed Trainer (MCT) and Microsof Specialist:

    • Programming in C# and Architecting Microsof Azure Solutions, with more than 20 years of educational and programming experience.

    Since 1993, Mark has passed more than 80 Microsof programming exams and specializes in preparing others to pass them too. His students range from professionals with decades of experience to 16-year-old apprentices with none. He successfully guides all of them by combining educational skills with real-world experiences in consulting and developing systems for enterprises worldwide. Between 2001 and 2003, Mark was employed full time to write ofcial courseware for Microsof in Redmond, USA. His team wrote the frst training courses for C# while it was still an early alpha version. While with Microsof, he taught "train-the-trainer" classes to get other MCTs up to speed on C# and .NET. Currently, Mark creates and delivers training courses for Episerver's Digital Experience Cloud, the best .NET CMS for Digital Marketing and E-commerce. In 2010, Mark studied for a Postgraduate Certifcate in Education (PGCE). He taught GCSE and A-Level mathematics in two London secondary schools. He holds a Computer Science BSc. Hons. Degree from the University of Bristol, UK.

    Browse publications by this author

Latest Reviews

(23 reviews total)
Um bom livro, a Packtpub sempre traz conteúdo relevante a preços competitivos.
Livro incrível... Explica nos mínimos detalhes o .Net Core
Packt offers great books and great deals. If you want to learn you must have a look to Pack.
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial