Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
C# 7 and .NET Core: Modern Cross-Platform Development
C# 7 and .NET Core: Modern Cross-Platform Development

C# 7 and .NET Core: Modern Cross-Platform Development: Create powerful cross-platform applications using C# 7, .NET Core, and Visual Studio 2017 or Visual Studio Code , Second Edition

eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

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

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, .NET Standard, and .NET Native; and using various tools to create the simplest application possible with C# 7 and .NET Core.

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 and its command-line tooling during its rocky birth during 2016 and 2017.

This chapter covers the following topics:

  • Choosing your development environment
  • Installing Microsoft Visual Studio 2017 for Windows
  • Installing Microsoft Visual Studio Code for Windows, macOS, or Linux
  • Understanding .NET
  • Writing and compiling code using the .NET Core CLI tool
  • Writing and compiling code using Microsoft Visual Studio 2017
  • Writing and compiling code using Microsoft Visual Studio Code
  • Managing source code with GitHub

Choosing your development environment

Before you start programming, you will need to choose an Interactive Development Environment (IDE) that includes a code editor for C#.

The most mature and full-featured IDE to choose is Microsoft Visual Studio 2017, but it only runs on the Windows operating system.

The most modern and lightweight IDE to choose, and the only one from Microsoft that is cross-platform, is Microsoft Visual Studio Code, and it will run on all common operating systems, including Windows, macOS, and many varieties of Linux, such as Red Hat Enterprise Linux (RHEL) and Ubuntu.

Note

To help you decide if Visual Studio Code is right for you, I recommend that you watch the following video, Beginner's Guide to VS Code: Up and Running in Ten Minutes: https://channel9.msdn.com/Blogs/raw-tech/Beginners-Guide-to-VS-Code

To create apps for iOS (iPhone and iPad), tvOS, macOS, and watchOS, you must have OS X or macOS, and Xcode. Although you can use Visual Studio 2017 with its Xamarin extensions to write a cross-platform mobile app, you still need OS X or macOS, and Xcode to compile it. So, in Chapter 15, Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API, I will show you how to use Visual Studio for Mac running on macOS to create a Xamarin cross-platform mobile app for iOS and Android that calls a web service hosted on ASP.NET Core.

The following table shows which IDE and operating systems can or must be used for each of the chapters in this book:

Choosing your development environment

Tip

Good Practice

If you have the option, then I recommend you try all the coding exercises with both Visual Studio 2017 on Windows, and Visual Studio Code on macOS, Linux, or Windows. It will be good for you to get experience with C# 7 and .NET Core on a variety of operating systems and development tools.

To write the second edition of this book, I used the following listed software, as you can see in the following screenshot:

  • Visual Studio Code version 1.10.2 and Visual Studio for Mac Preview 4, on macOS Sierra version 10.12.3
  • Visual Studio 2017 on Windows 10 (in a virtual machine)
  • Visual Studio Code on Red Hat Enterprise Linux (in a virtual machine)

    Choosing your development environment

Using alternative C# IDEs

There are alternative IDEs for C#, for example, MonoDevelop and JetBrains Rider. You can install either of these two IDEs with the help of the following URLs:

Cloud9 is a web browser-based IDE, so it's even more cross-platform than the others. It is growing in popularity. Here is the link:https://c9.io/web/sign-up/free.

Deploying cross-platform

Your choice of IDE and operating system for development does not limit where your code gets deployed. .NET Core currently supports the following platforms for deployment:

  • Windows 7 SP1, or later
  • Windows Server 2008 R2 SP1, or later
  • OS X El Capitan (version 10.11) and macOS Sierra (version 10.12)
  • Red Hat Enterprise Linux 7.2
  • Ubuntu 14.04 LTS, 16.04 LTS
  • Linux Mint 17
  • Debian 8.2
  • CentOS 7.1
  • Oracle Linux 7.1
  • Docker

Note

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

In the next section, you will install Microsoft Visual Studio 2017 for Windows. If you prefer to use Microsoft Visual Studio Code, jump ahead to the section titled, Installing Microsoft Visual Studio Code for Windows, macOS, or Linux.

Installing Microsoft Visual Studio 2017 for Windows

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

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

Note

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.

Download and install Microsoft Visual Studio 2017 from the following link:https://www.visualstudio.com/downloads/

Choosing workloads

On the Workloads tab, choose the following, as partially shown in the following screenshot:

  • Universal Windows Platform development
  • .NET desktop development
  • ASP.NET and web development
  • Azure development
  • Mobile development with .NET
  • .NET Core cross-platform development

    Choosing workloads

Choosing additional components

On the Individual components tab, choose the following additional components, as shown in the following screenshot:

  • Class Designer
  • PowerShell tools
  • Git for Windows
  • GitHub extension for Visual Studio

Choosing additional components

Click Install, and wait for the installer to acquire the selected software, and install it, as shown in the following screenshot:

Choosing additional components

When the installation is complete, click Launch.

Note

While you wait for Visual Studio 2017 to install, you can jump ahead to the Understanding .NET section in this chapter.

Signing in to Visual Studio 2017

The first time that you run Visual Studio 2017, 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 your settings

When starting Visual Studio 2017 for the first time, you will be prompted to configure your environment. For Development Settings, choose Visual C#. For color theme, I chose Blue, but you can choose whatever suits you, as shown in the following screenshot:

Choosing your settings

Reviewing Visual Studio's user interface

You will see the Microsoft 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 that will list your open projects:

Reviewing Visual Studio's user interface

Note

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

Installing Microsoft Visual Studio Code for Windows, macOS, or Linux

Between June 2015 and March 2017, Microsoft released a new version of Visual Studio Code every month (except for December 2016 because even Microsoft employees deserve a break for Christmas). Visual Studio Code has rapidly improved, and has surprised Microsoft with its popularity. Even if you plan to use Visual Studio 2017 as your primary development tool, I recommend that you learn how to use Visual Studio Code and the .NET Core command-line tool as well.

You can download Visual Studio Code from https://code.visualstudio.com/.

Installing Microsoft Visual Studio Code for macOS

In this book, I will show examples and screenshots of Visual Studio Code by using the version for macOS. The steps for doing the same with Visual Studio Code for Windows and variants of Linux is very similar, so I will not repeat the instructions for every platform.

After downloading Visual Studio Code for macOS, drag and drop it to your Applications folder, as shown in the following screenshot:

Installing Microsoft Visual Studio Code for macOS

Installing .NET Core for macOS

You will now need to install the .NET Core SDK for macOS. The full instructions, including a video to watch, are described at the following link, and I have included the basic steps in this book for your convenience: https://www.microsoft.com/net/core#macos.

Installing Homebrew

The first step is to install Homebrew (if you don't already have it).

Start macOS's Terminal app and enter the following command at the prompt:

/usr/bin/ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)"

Terminal will prompt you to press RETURN to continue, and then prompt for your password, as shown in the following screenshot:

Installing Homebrew

Installing OpenSSL

The second step is to use Homebrew to install OpenSSL, which is required by .NET Core.

At the prompt, enter the following commands:

brew update
brew install openssl
mkdir -p /usr/local/lib
ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib  /usr/local/lib/
ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/

Terminal will output messages as shown in the following screenshot:

Installing OpenSSL

Installing .NET Core SDK

The third step is to download the .NET Core SDK installer for macOS (x64) from the following link: https://www.microsoft.com/net/download/core.

Note

The .NET Core SDK installer package installs .NET Core version 1.1.1 and the .NET Core Command Line Interface (CLI) tool version 1.0.1. Yes, the version numbers are confusing! A single CLI tool with its own version number is used for multiple versions of .NET Core runtime. .NET Core 1.1.1 is the Current branch and gets new features and bug fixes. .NET Core 1.0.4 is the Long Term Support (LTS) branch and only gets bug fixes. Both were released on March 7, 2017 with Visual Studio 2017.

Run the dotnet-1.1.1-sdk-osx-x64.pkg installer package, as shown in the following screenshot:

Installing .NET Core SDK

Click Continue, accept the license agreement, click Install, and then, as shown in the next screenshot, click Close:

Installing .NET Core SDK

Installing the Visual Studio Code extension for C#

This extension is not necessary but it provides IntelliSense as you type, so it's very handy to install.

Launch Visual Studio Code and click the Extensions icon, or choose View | Extensions, or press Cmd + Shift + X .

C# is the most popular extension so you should see it at the top of the list, as shown in the following screenshot:

Installing the Visual Studio Code extension for C#

Click Install, and then click Reload, to reload the window and activate the extension.

Now that you have installed and set up your development environment, you will learn some background about .NET before diving in to writing code.

Understanding .NET

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

Understanding .NET Framework

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

Microsoft designed .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, .NET Framework is Windows-only, and a legacy platform.

Understanding the Mono and Xamarin projects

Third parties developed a .NET implementation named the Mono project that you can read more about here: http://www.mono-project.com/.

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

Microsoft purchased Xamarin in 2016 and now gives away what used to be an expensive Xamarin extension for free with Visual Studio 2017. Microsoft renamed the Xamarin Studio development tool to Visual Studio for Mac and has given it the ability to create ASP.NET Core Web API services. Xamarin is targeted at mobile development and building cloud services to support mobile apps.

Note

You will use Visual Studio for Mac in Chapter 15 , Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API to create a mobile app for iOS and Android that calls an ASP.NET Core Web API service.

Understanding .NET Core

Today, we live in a truly cross-platform world. Modern mobile and cloud development has made Windows a much less important operating system. So, Microsoft has been working on an effort to decouple .NET 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 .NET Core, which includes a cross-platform implementation of the CLR known as CoreCLR, and a streamlined library of classes known as CoreFX.

Scott Hunter, Microsoft Partner Director Program Manager for .NET, says, "Forty percent of our .NET Core customers are brand-new developers to the platform, which is what we want with .NET Core. We want to bring new people in."

The following table shows when important versions of .NET Core were released, and Microsoft's schedule for the next major release:

Version

Released

.NET Core RC1

November 2015

.NET Core 1.0

June 2016

.NET Core 1.1

November 2016

.NET Core 1.0.4 (LTS) and .NET Core (Current) 1.1.1

March 2017

.NET Core 2.0

Scheduled for release in Q3 2017

Tip

Good Practice

If you need to work with .NET Core 1.0 and 1.1, then I recommend that you read the announcement for .NET Core 1.1, although the information at the following URL is useful for all .NET Core developers: https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-net-core-1-1/

Streamlining .NET

.NET Core is much smaller than the current version of .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 .NET Core. The latest technology used to build Windows apps is the Universal Windows Platform (UWP), and UWP is built on a custom version of .NET Core. 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 application and service technologies that fewer developers choose to use for new development projects today, so they have also been removed from .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 .NET Core named ASP.NET Core. You will learn about ASP.NET Core MVC in Chapter 14, Building Web Applications Using ASP.NET Core MVC, and ASP.NET Core Web API in Chapter 15, Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API.

The Entity Framework (EF) 6.x is an object-relational mapping technology to work 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. You will learn about it in Chapter 8, Working with Databases Using Entity Framework Core.

Some common but old data types in .NET Framework have been removed from .NET Core, such as  HashTable and ArrayList in System.Collections, but can be added back using a separate class library or NuGet package. Some data types in .NET that are included with both .NET Framework and .NET Core have been simplified by removing some members. For example, in .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 you must learn.

As well as removing large pieces from .NET Framework to make .NET Core, Microsoft has componentized .NET Core into NuGet packages: small chunks of functionality that can be deployed independently.

Note

.NET Framework 4.6 is about 200 MB and must be deployed as a single unit. .NET Core 1.0 is about 11 MB. Eventually, .NET Core and all its NuGet packages may grow to hundreds of megabytes. Microsoft's primary goal is not to make .NET Core smaller than .NET Framework. The goal is to componentize .NET Core to support modern technologies and to have fewer dependencies so that deployment requires only those packages that your application needs.

Understanding .NET Standard

The situation with .NET today is that there are three forked .NET platforms, all controlled by Microsoft:

  • .NET Framework
  • Xamarin
  • .NET Core

Each have different strengths and weaknesses because they are designed for different scenarios. This has led to the problem that a developer must learn three platforms, each with annoying quirks and limitations.

So, Microsoft is working on defining .NET Standard 2.0: a set of APIs that all .NET platforms must implement. At the time that I write this, in March 2017, there is .NET Standard 1.6, but only .NET Core supports it; .NET Framework and Xamarin do not.

.NET Standard 2.0 will be implemented by .NET Framework, .NET Core, and Xamarin. For .NET Core, this will add many of the missing APIs that developers need to port old code written for .NET Framework to the cross-platform .NET Core. However, Microsoft warns that some APIs will be "implemented", but throw an exception to indicate to a developer that they should not actually be used! You will learn how to handle this in Chapter 2Speaking C#.

.NET Standard 2.0 is the near future of .NET, and it will make it much easier for developers to share code between any flavor of .NET, but we are not there yet. Microsoft says .NET Standard 2.0, and .NET Core 2.0, are scheduled for release in Q3 2017. That could mean July 1, 2017, but based on previous experience, I think late September 2017 is more realistic.

The following diagram summarizes how the three variants of .NET (sometimes known as app models) will share the common .NET Standard 2.0 and infrastructure:

Understanding .NET Standard

.NET used in this book

The first edition of this book focused on .NET Core, but used .NET Framework when important or useful features had not been implemented in .NET Core. Visual Studio 2015 was used for most examples, with Visual Studio Code shown only briefly.

The second edition has been purged of all .NET Framework code examples. It has been rewritten so that all code is pure .NET Core and can be written with either Visual Studio 2017 or Visual Studio Code on any supported operating system.

The only exceptions are in Chapter 13Building Universal Windows Platform Apps Using XAML, that uses .NET Core for UWP and requires Visual Studio 2017 running on Windows 10, and in Chapter 15, Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API, when we will write a Xamarin mobile app with Visual Studio for Mac.

Understanding .NET Native

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

.NET Native 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
  • Console applications for use on the command line

Comparing .NET technologies

The following table summarizes and compares .NET technologies:

Comparing .NET technologies

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:

If you are using Windows Notepad

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

If you are using Windows Notepad

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:

If you are using macOS TextEdit

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:

Compiling code using the .NET Core 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:

Restoring packages and running the application

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.

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:

Writing code using Microsoft Visual Studio 2017

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:

Coding with Visual Studio's editor

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:

Coding with Visual Studio's editor

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

Coding with Visual Studio's editor

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:

Coding with Visual Studio's editor

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:

Coding with Visual Studio's editor

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:

Coding with Visual Studio's editor

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:

Coding with Visual Studio's editor

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:

Compiling code using Visual Studio 2017

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:

Fixing mistakes with the error list

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:

Fixing mistakes with the error list

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:

Autoformatting code

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:

Autoformatting code

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:

Experimenting with C# Interactive

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:

Other useful windows

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.

Writing and compiling code using Microsoft Visual Studio Code

The instructions and screenshots in this section are for macOS, but the same actions will work with Visual Studio Code on either Windows or Linux. The main differences will be native command-line actions such as deleting a file: both the command and the path are likely to be different. The dotnet CLI tool will be identical on all platforms.

Writing code using Visual Studio Code

Start Visual Studio Code.

Navigate to File | Open..., or press Cmd + O.

In the dialog box, open the Code folder, select the Chapter01 folder, click the New Folder button, enter the name Ch01_WelcomeDotNetCore, and click Create, as shown in the following screenshot:

Writing code using Visual Studio Code

Select the Ch01_WelcomeDotNetCore folder, and click Open or press Enter.

In Visual Studio Code, navigate to View | Integrated Terminal, or press Ctrl + `.

At the Terminal prompt, enter the following command:

dotnet new console

You will see that the dotnet command-line tool creates a new console application project for you in the current folder, and the Explorer window shows the two files created, as shown in the following screenshot:

Writing code using Visual Studio Code

In the Explorer window, click on the file named Program.cs to open it in the editor window.

Note

The first time that you do this, C# dependencies will be updated for your platform. This will take a few moments.

When you see the warnings about required assets and unresolved dependencies, click Restore and Yes, as shown in the following screenshot:

Writing code using Visual Studio Code

Modify the text that is being written to the console to say, Welcome, .NET Core!

On the File menu, choose Auto Save. This toggle will save the annoyance of remembering to save before rebuilding your application each time!

Compiling code using Visual Studio Code

Navigate to View | Integrated Terminal or press Ctrl + ` and enter the following command:

dotnet run

The output in the Terminal will show the result of running your application, as shown in the following screenshot:

Compiling code using Visual Studio Code

You now know how to create and build simple .NET Core applications for Windows and macOS (and Linux is just as easy).

You will be able to complete almost all the chapters in this book using either Visual Studio 2017 on Windows or using Visual Studio Code on macOS, Windows, or Linux.

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.

I used GitHub to store solutions to all the practical exercises at the end of each chapter at the following URL:

https://github.com/markjprice/cs7dotnetcore.

Using Git with Visual Studio 2017

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

Using the Team Explorer window

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

Using 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/cs7dotnetcore.git.

Enter a path for the cloned Git repository:

C:\Code\Repos\cs7dotnetcore

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

Using Git with Visual Studio Code

Visual Studio Code has support for Git, but it will use your OS's Git installation, so you must install Git 2.0 or later first before you get these features. You can install Git from here: https://git-scm.com/download.

Note

If you like to use a graphical user interface, you can download GitHub Desktop here: https://desktop.github.com.

Configuring Git at the command line

Launch Terminal, and enter the following command to check your configuration:

git config --list

The output should include your username and e-mail address, because these will be used with every commit that you make:

...other congfiguration...
user.name=Mark J. Price
[email protected]

If your user name and e-mail has not been set, to set your user name and email, enter the following commands, using your own name and e-mail, not mine:

git config --global user.name "Mark J. Price"
git config --global user.email [email protected]

You can check an individual configuration setting like this:

git config user.name

Managing Git with Visual Studio Code

Launch Visual Studio Code.

Navigate to View | Integrated Terminal or press Ctrl+ ` and enter the following commands:

cd Code
mkdir Repos
cd Repos
git clone https://github.com/markjprice/cs7dotnetcore.git

It will take a minute to clone all the solutions for all the chapters to your local drive, as shown in the following screenshot:

Managing Git with Visual Studio Code

It is best to open one project folder at a time because the cs7dotnetcore repository does not include any dependencies, so you will need to restore them using the dotnet restore command, or wait for Visual Studio Code to prompt you after opening a folder.

For more information about source code version control with Visual Studio Code, visit: https://code.visualstudio.com/Docs/editor/versioncontrol.

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, for example C# and F#, to write applications that run on .NET Core?
  2. What do you type at the prompt to build and execute C# source code?
  3. What is the Visual C# developer settings keyboard shortcut to save, compile, and run an application without attaching the debugger?
  4. What is the Visual Studio Code keyboard shortcut to view the Integrated Terminal?
  5. Is Visual Studio 2017 better than Visual Studio Code?
  6. Is .NET Core better than .NET Framework?
  7. How is .NET Native different from .NET Core?
  8. What is .NET Standard and why is it important?
  9. What is the difference between Git and GitHub?
  10. What is the name of the entry-point method of a .NET console application and how should it be declared?

Exercise 1.2 - practice coding anywhere

You do not need Visual Studio 2017 or Visual Studio Code to practice writing C#.

Go to one of the following websites and start coding:

Exercise 1.3 - 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, used Windows' Command Prompt and macOS's Terminal to compile and run a console application, used Visual Studio 2017 and Visual Studio Code to create the same application, and discussed the differences between .NET Framework, .NET Core, .NET Standard, and .NET Native.

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

Left arrow icon Right arrow icon

Key benefits

  • Build modern, cross-platform applications with .NET Core
  • Get up to speed with C#, and up to date with all the latest features of C# 7
  • Start creating professional web applications with ASP.NET Core

Description

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.

Who is this book for?

This book is targeted towards readers who have some prior programming experience or have a science, technology, engineering, or mathematics (STEM) background, and want to gain a solid foundation with C# and to be introduced to the types of applications they could build and will work cross-platform on Windows, Linux, and macOS.

What you will learn

  • • Build cross-platform applications using C# 7 and .NET Core
  • • Explore ASP.NET Core and learn how to create professional web applications
  • • Improve your application's performance using multitasking
  • • Use Entity Framework Core and find out how to build code-first databases
  • • Master object-oriented programming with C# to increase code reuse and efficiency
  • • Familiarize yourself with cross-device app development using the Universal Windows Platform and XAML
  • • Query and manipulate data using LINQ
  • • Protect your data by using encryption and hashing
Estimated delivery fee Deliver to Ukraine

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 24, 2017
Length: 594 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787129559
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Ukraine

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Mar 24, 2017
Length: 594 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787129559
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 164.97
Enterprise Application Architecture with .NET Core
$54.99
C# 7 and .NET Core: Modern Cross-Platform Development
$54.99
C# 7 and .NET Core Cookbook
$54.99
Total $ 164.97 Stars icon
Banner background image

Table of Contents

17 Chapters
1. Hello, C#! Welcome, .NET Core! Chevron down icon Chevron up icon
2. Speaking C# Chevron down icon Chevron up icon
3. Controlling the Flow, Converting Types, and Handling Exceptions Chevron down icon Chevron up icon
4. Using .NET Standard Types Chevron down icon Chevron up icon
5. Debugging, Monitoring, and Testing Chevron down icon Chevron up icon
6. Building Your Own Types with Object-Oriented Programming Chevron down icon Chevron up icon
7. Implementing Interfaces and Inheriting Classes Chevron down icon Chevron up icon
8. Working with Databases Using the Entity Framework Core Chevron down icon Chevron up icon
9. Querying and Manipulating Data with LINQ Chevron down icon Chevron up icon
10. Working with Files, Streams, and Serialization Chevron down icon Chevron up icon
11. Protecting Your Data Chevron down icon Chevron up icon
12. Improving Performance and Scalability with Multitasking Chevron down icon Chevron up icon
13. Building Universal Windows Platform Apps Using XAML Chevron down icon Chevron up icon
14. Building Web Applications Using ASP.NET Core MVC Chevron down icon Chevron up icon
15. Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API Chevron down icon Chevron up icon
16. Packaging and Deploying Your Code Cross-Platform Chevron down icon Chevron up icon
A. Answers to the Test Your Knowledge Questions Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(11 Ratings)
5 star 63.6%
4 star 9.1%
3 star 9.1%
2 star 18.2%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Frank Semeraro Sep 05, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent reference. Very well written.
Amazon Verified review Amazon
Hawkeyedriver Nov 07, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I use this as a textbook now!
Amazon Verified review Amazon
Helena Mar 01, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
very good
Amazon Verified review Amazon
MC May 19, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I like his style! Just started reading, but he gets down to business in a conversational education process.
Amazon Verified review Amazon
James Firminger Sep 07, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book from a great writer. Coming from an PHP / Open Source background, I'd alway been a little bit sceptcial of ASP.net, but the strides MS are making in opening in up the environment and making it multi-platform, really piqued my interest. Had a bit of experience with C#, but this took me further and I'm now starting to get to the point where I'm going to create my next web app in .NetCore.The book assumes no real knowledge of C#, but covers the basics. I skipped most of that and dug in to the more meaty bits (starting with custom events / delegates). All my questions were answered, due to the clarity of explanations.I programmed most of the examples using a Mac and then added my files to OneDrive, so that I could continue on my PC. Happy reading.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela