Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
.NET Core 2.0 By Example
.NET Core 2.0 By Example

.NET Core 2.0 By Example: Learn to program in C# and .NET Core by building a series of practical, cross-platform projects

eBook
£22.99 £32.99
Paperback
£41.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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
Table of content icon View table of contents Preview book icon Preview Book

.NET Core 2.0 By Example

Getting Started

In this chapter, we are going to learn about tools used to perform development tasks for .NET Core 2.0 on Windows and Linux operating systems. Also, we will learn how to set up Linux and virtualization using VirtualBox and Hyper-V. This chapter will cover how to install .NET Core 2.0 and tools for Windows and Linux (Ubuntu). We will learn about the virtual machine (VM) setup for Ubuntu and create your first simple .NET Core 2.0 running application code. We will configure the VM to manage your first application. The purpose of this chapter is to get a general idea of the required tools and how to install .NET core 2.0 SDK for Windows and Linux, and give you basic F# understanding.

This chapter will cover the following:

  • Downloading the required tools for Windows and Linux
  • Installing .NET Core 2.0 and tools (Windows)
  • Setting up an Ubuntu Linux VM
  • Installing .NET Core 2.0 and tools (Linux)
  • Creating simple running code
  • F# primer

Downloading required tools for Windows and Linux

In this section, we will discuss the prerequisites to be downloaded for both Windows and Linux operating systems to start development with .NET Core 2.0. We will start with Windows and then move to Linux. 

Downloads for Windows

Microsoft offers the Visual Studio integrated development environment (IDE) for developers to develop computer programs for Microsoft Windows, as well as websites, web applications, web services, and mobile applications. Microsoft gives us the choice to pick from four Visual Studio adaptations—Community, Professional, Enterprise, and Code. You can download one of these, depending on your individual prerequisite. How these versions differ from each other is explained next.

Navigate to https://www.visualstudio.com/downloads in the browser of your choice. You will see four choices. Select the Visual Studio product based on your requirements.

All versions of Visual Studio 2017 are available for Windows and Macintosh operating systems:

  • Visual Studio Community: This is a free, open source version of Visual Studio with limited features. This is for the individual developer. 
  • Visual Studio Professional: This version has professional developer tools, services, and subscription benefits for small teams (five members).
  • Visual Studio Enterprise: This version supports all Visual Studio features and is meant for end-to-end solution development to meet the demanding quality and scaling needs of teams of all sizes. It is great for enterprise organizations. Some of the key features that come with this version are testing tools, architectural layer diagrams, live dependency validation, architecture validation, code clone detection, IntelliTrace, .NET memory dump analysis, and so on.
  • Visual Studio Code: This is a free, open source version and cross-platform (Linux, macOS, Windows) editor that can be extended with plugins to meet your needs. It includes support for debugging, embedded Git control, syntax highlighting, extension support, intelligent code completion, snippets, and code refactoring.
Make a note that Visual Studio is an IDE, while Visual Studio Code is an editor, just like Notepad is an editor. So Visual Studio Code is much more lightweight, fast, and fluid with great support for debugging and has embedded Git control. It is a cross-platform editor and supports Windows, Linux, and Macintosh. Debugging support is good and has rich IntelliSense and refactoring. Like most editors, it is keyboard-centric. It is a file and folders-based editor and doesn't need to know the project context, unlike an IDE. There is no File | New Project support in Visual Studio Code as you would be used to in Visual Studio IDE. Instead, Visual Studio Code offers a terminal, through which we can run dotnet command lines to create new projects.

So, for development in Windows, we can use either of these:

  • Visual Studio 2017 IDE
  • Visual Studio Code editor

If we choose Visual Studio 2017, all we need to do is download Visual Studio 2017 version 15.3 from https://www.visualstudio.com/downloads. It comes bundled with the .NET Core 2.0 SDK and its templates and so we will be ready for development immediately after installing it. Also with Visual Studio 2017, F# tools automatically get installed once we create an F# project or open an F# project for the very first time. So, the F# development setup is taken care of as well. We will see the installation of Visual Studio 2017 in the Installing .NET Core 2.0 and tools (Windows) section of this chapter.

If we choose Visual Studio Code for development, we need to download Visual Studio Code from https://code.visualstudio.com/download and the .NET Core 2.0.0 SDK from https://www.microsoft.com/net/core#windowscmd . We will look at the installation of Visual Studio Code in the Installing .NET Core 2.0 and tools (Windows) section of this chapter.

Downloads for Linux

As mentioned in the preceding section, Microsoft Visual Studio Code is a cross-platform editor, and it supports Linux operating systems. So, we are going to use Visual Studio Code to create all the example applications on Linux in this book.

Let's start downloading the tools required to stop our development of .NET Core 2.0 applications on the Linux operating system:

  1. Download Visual Studio Code from https://code.visualstudio.com/. We are going to install the Ubuntu 32-bit version, so we will download the Visual Studio Code 32-bit version. Select the Linux x86 .deb stable package for download, as shown in the following image:

If you have a Linux machine handy, you can skip the next download step. If you wish to try development on the Linux platform and have a Windows machine to work with, then the next two steps are for you.

  1. Download VirtualBox from https://www.virtualbox.org/. It is Oracle's open source general-purpose full virtualizer. At the time of writing this chapter, the latest version of VirtualBox is 5.1. The version 5.1.26 was released on July 27, 2017. Using this, we will set up a Linux (Ubuntu) virtual machine on the Windows host machine. Click on Download VirtualBox 5.1. It will open a page that has options on VirtualBox binaries. We can select an option based on the machine on which we are installing it. We are installing it on a Windows machine, so we will click on Windows hosts. In a similar way, we can select different platforms. On clicking Windows hosts, it will download the VirtualBox executable VirtualBox-5.1.26-117224-Win.exe:

VirtualBox needs the Ubuntu International Standards Organization (ISO) image to create the Ubuntu VM, so next we need to download the ISO image of Ubuntu.

  1. Download the ISO image of Ubuntu by navigating to https://www.ubuntu.com. By default, the virtual machine software uses 32-bit Linux, so we will select 32-bit. Hover over the Downloads menu and click on the highlighted Desktop link:

It will take us to the downloads page for the desktop. Click Download on Ubuntu for the desktop. It will start the download of Ubuntu 17.04 ISO. An ISO image of approximately 1.5 GB will be downloaded.

  1. Download .NET Core 2.0 SDK from https://www.microsoft.com/net/download/linux

With this, we are done with the downloads for our setup in Linux. In the next section, we will learn how to install and set up these tools.

Ubuntu 17.04: As of writing this chapter, this is the latest version, and its code name is Zesty Zapus, released on April 13, 2017. Ubuntu releases carry a version number in the form of XX.YY, with XX representing the year and YY representing the month of the official release. For example, the latest version released in April 2017 is represented by 17 (year) and 04 (month). Ubuntu code names use an adjective animal combination, that is an adjective word followed by the name of an animal, typically one that's unique. At the time of writing, Ubuntu 17.10 is due to be released in October 2017; examples covered here used the Ubuntu 17.04 version.

Installing .NET Core 2.0 and tools (Windows)

Now that we are done with the downloads, it's time to install. As seen in the last section on Windows, we have two options for development in Windows:

  • Visual Studio 2017 version 15.3
  • Visual Studio Code

Based on your choice, you can follow the appropriate installation steps.

Installing Visual Studio 2017 version 15.3

Double-click on the executable file downloaded for Visual Studio 2017 version 15.3 in the earlier section. This will start the installation. C# comes by default in every Visual Studio installation, so there is nothing to do for C#. Visual Studio 2017 also comes with F# support in all its editions: Community, Professional, and Enterprise. F# is an optional component though. The installer includes it as a selectable workload, or you can select it manually in the Individual components tab, under the Development activities category. Select F# language support:

Visual Studio 2017 version 15.3 comes with the .NET Core SDK. Select .NET Core cross-platform development under Workloads during the Visual Studio 2017 version 15.3 installation:

For other versions of Visual Studio, download the .NET Core 2.0 SDK from https://www.microsoft.com/net/download/core, or update Visual Studio to 2017 15.3 and select .NET Core cross-platform development under Workloads.

Installing Visual Studio Code

Install Visual Studio Code by double-clicking the Visual Studio Code setup executable from its download location. It's a simple installation for Windows. Once Visual Studio Code is installed, launch it. The following screenshot shows the user interface layout of Visual Studio Code. It follows the conventional editor style and displays files and folders you have access to on the left side and the code content in the editor on the right side. It can be roughly divided into seven sections, as shown in the following screenshot:

Let's discuss them:

  1. Menu bar: The standard menu bar for doing various operations in the editor, such as opening a file/folder, editing, viewing and installing extensions, changing themes, debugging, running and configuring tasks, and getting help.
  2. Activity bar: Groups the most commonly performed activities on the leftmost side of the editor. It lets the user switch between the views. It is customizable and lets the user choose the views to be displayed in the bar, by right-clicking on the bar and selecting/unselecting the views. The bar itself can be hidden in the same way. By default, it has five views, as shown in the following screenshot:
    • EXPLORER: This view lets your browse, open, and manage all the files and folders in your project. You can create, delete, and rename files and folders, as well as move files and folders from here. You can also open the files/folders in Terminal (Command Prompt in Windows) from here by right-clicking and selecting Open in Command Prompt. You can find the file/folder location as well from here.

    • SEARCH: This view lets you search and replace globally across your open folder.

    • SOURCE CONTROL: This lets you work with Git source control by default.

    • DEBUG: This view displays the breakpoints, variables, and call stack for debugging.

    • EXTENSIONS: This is used to install and manage extensions in Visual Studio Code.

  1. Side bar: This contains the view selected from the activity bar.
  2. Command Palette: As stated earlier, Visual Studio Code is keyboard-centric, so anyone who loves using a keyboard is going to have a great time working on Visual Studio Code. The Ctrl Shift P key combination brings up what is called a Command Palette. We can access all the functionality of Visual Studio Code from here. To make effective use of Visual Studio Code, it is highly recommended that the reader makes himself/herself well versed with the commands from the help menu item links:
  1. Editor: The editor is where the content of the file is displayed and the user can edit it. Visual Studio Code provides a feature called Split Editor (open to the side in Linux). Go to the View menu in the menu bar and select Split Editor (alternatively you can type the command Ctrl +\). This will create a new editor region, where you can edit a group of files. These regions are called editor groups. The open editors can also be seen in the Explorer view in the sidebar. Visual Studio Code allows up to three editor groups, designated as LEFT, CENTER, and RIGHT, as shown in the following screenshot:
  1. Panels: Displays the TERMINAL, OUTPUT, PROBLEMS, and DEBUG CONSOLE panes below the editor. To see it in action, go to the View menu and click any of the menu items from PROBLEMS, OUTPUT, DEBUG CONSOLE, and TERMINAL. Alternatively, you can also press their corresponding commands. We will see more on panels when we write our first application.
  2. Status Bar: Displays information about the opened project and files being edited, such as errors, warnings, current line and column number, encoding, and file type.

Now we are familiar with Visual Studio Code, its layout, and basic functionality.

Go to the Help menu and explore in detail the features that Visual Studio Code offers. The Interactive Playground highlights a number of features in Visual Studio Code and also lets you interactively try them out. The Help menu also has Documentation, Introductory Videos, Tips and Tricks, which are very handy.

Remember, Visual Studio Code is an editor and therefore we need to add support for the language we want to work with through extensions. Visual Studio Code is very rich in extensions. For our example and for the purpose of learning .NET Core 2.0, we will install extensions for C# and F#, as we will be working with them.

Let's start with C#, as after a fresh install we do not have support for C# and hence there would be no IntelliSense to work with on the editor. To install C#, let's switch to Extension View and search for C#. We will choose C# for Visual Studio Code (powered by OmniSharp), as shown in the following screenshot:

Click Install and then click on Reload and Visual Studio Code will start supporting C# along with its IntelliSense.

Similarly, search F# and Install it. We will be using the Ionide-fsharp extension, as shown in the following screenshot:

With Visual Studio Code, we need to install .NET Core SDK - 2.0.0 (x64) also, as Visual Studio Code doesn't install it. Double-click on the executable of .NET Core 2.0 SDK to install it, as shown in the following screenshot:

And with this, we are done with the installation of our prerequisites for development on the Windows platform. Next, we will set up a Linux (Ubuntu) VM and perform the installation of prerequisites there. If you are using a Windows platform and do not wish to set up a Linux VM, the next section can be skipped.

The Visual Studio Code user interface was developed on the Electron framework, which is an open source framework used to build cross-platform desktop applications with JavaScript, HTML, and CSS. The editor is powered by Microsoft's Monaco Editor and gets its intelligence from OmniSharp/Roslyn and TypeScript. As all of these are open source, you can search them and see the source code in GitHub.

Setting up an Ubuntu Linux VM

In this section, we will see how to set up Linux (Ubuntu) on a virtual machine, so that a Windows user can also develop and test their .NET Core 2.0 applications in Linux. To do so, let’s start with the VirtualBox setup. Oracle provides an open source VirtualBox executable, which we downloaded in the previous section. The following are the steps we need to follow to set up VirtualBox:

  1. Double-click on the VirtualBox executable. It will open a wizard. Before installation, click on Disk usage and check Disk Space Requirement. It is recommended that the virtual machine for Ubuntu Linux is set up with at least 2 GB RAM and 25 GB free hard drive space. So, instead of choosing the default drive (the C drive in our case, where Windows is installed), select another drive if it exists (for example, the D drive) so that you can easily allocate more space, and it also prevents any impact on the host operating system.
  2. The VirtualBox setup needs approximately 241 MB of disk space to install. It's recommended to create a new folder (for example, VirtualBox) to easily identify and track the VM. 
  1. Keep clicking the Next button until the last page. At the end, a warning will be displayed that the installation of VirtualBox will reset the network connection and temporarily disconnect the machine from the network. This is alright if you are working on the same physical machine. So, click on the Yes button and continue, and then click on the Install button and finish the installation:
  1. Once the preceding installation is done, open the VirtualBox manager to create a new virtual machine. Click on New and give the Name of the machine (for example, Ubuntu, as shown), and select the Type as Linux and the Version as Ubuntu (32 bit):
  1. We need to specify the memory size. More memory is good, but we should consider our disk space before selecting it. A minimum of 2 GB system memory is required for Ubuntu 17.04. Select Create and then select VDI (VirtualBox Disk Image) as Hard disk file type. Select a Dynamically allocated hard disk. It will use space on your physical hard disk as it fills up (up to the maximum fixed size). Set the disk space maximum size to 25 GB and click on Create. It will create a virtual machine with the Ubuntu operating system (32-bit) and 4 GB RAM, and the full details will be displayed on the final page:

 

Ubuntu setup using Hyper-V

For Windows machines, we can use Hyper-V to create a Linux virtual machine. Let's start with the basic settings and important configuration changes:

  1. First, enable Hyper-V Management Tools and Hyper-V Platform from Windows Features
  1. Change the default virtual directory. By default, Hyper-V uses the same drive as that on which the OS is installed but this is not a good practice. We should change the default drive the drive on which the operating system is not installed, such as the D drive in our case.  It's a good practice to keep Windows and system files separate from other files. To make configuration changes, open Hyper-V Manager and then Hyper-V Settings. Instead of the default selection, change it to some other drive (D in our case). Create a new folder named Virtual Machine on this new drive location:
   
  1. Create a virtual switch. A virtual switch is used to join computers and to create networks. We can create three types for virtual switches:
    • External: An accessible network where the virtual machines are hosted on the same physical computer and all external servers from which the host machine can connect.
    • InternalCreates a virtual switch that can be used only by the virtual machines that run on the same physical computer, and between virtual machines and the physical computer. An internal virtual switch doesn't provide connectivity to a physical network connection.
    • Private: Creates a virtual switch that can be used only by the virtual machines that run on the same physical computer.

Create a Private or External type of virtual switch. This will be used for the virtual machine:  

Open Network and Sharing Center on your host machine and then open the external virtual switch properties. You will find Hyper-V Extensible Virtual Switch. This provides network connectivity to the virtual machine. Enable this or the virtual machine won't be able to connect to the host machine network:

  1. Create a new virtual machine, and choose the name and location for the virtual machine. Select Generation 1 on the next page and select External Virtual Switch. Select the Install an operating system from a bootable CD/DVD-ROM option and select Image file (.iso), which we downloaded earlier for Ubuntu. Continue clicking the Next button in the wizard and the Ubuntu virtual machine will be created. Click on Start and connect to it:
  1. After connection, we will be able to see the following screen. Select Install Ubuntu and set the language as English. Choose the Erase disk and install Ubuntu option and then click Continue
  1. Provide the username and password that you want and click Continue. Restart the system once the installation is done:

After restarting the virtual machine, it will display a login page. Enter the password that you provided while installing Ubuntu. On successful login, it will open the homepage, from where we can start Visual Studio Code and .NET Core 2.0 SDK installation on this Ubuntu machine.

Installing .NET Core 2.0 and tools (Linux)

To install Visual Studio Code in Linux, download the .deb (32 bit) file from http://code.visualstudio.com/download, as shown in the following screenshot:

Open the folder location the .deb file has been downloaded to. Right-click and select Open in Terminal. This will open Terminal from this location. Run the following command:

sudo dpkg -i <fileName>.deb

<fileName>: Enter the filename that was downloaded, which is code_1.15.1-1502903950_i386.deb in our case, as shown in the following screenshot:

Right-click on the Downloads folder, and select Open in Terminal. It will display the following terminal window:

It may show error messages stating that dependencies have not been installed. Run the following command to install the dependencies:

sudo apt-get install -f

This will complete the installation of Visual Studio Code in this Ubuntu machine.

Now, let's install the .NET Core 2.0 SDK. Open the folder location where the dotnet-sdk-2.0.0 file is downloaded. Right-click and select Open in Terminal. It will open Terminal from this location. Run the following command:

 sudo apt-get install dotnet-sdk-2.0.0

Congratulations! We are all set to run Visual Studio Code! Please refer to the Installing Visual Studio Code section of this chapter to get an overview of Visual Studio Code.

Open Extensions View from the Visual Studio Code activity bar. Search F# and install the Ionide-fsharp extension for F# language support, as we discussed in the Installing Visual Studio Code section under the Install .NET Core 2.0 and tools (Windows) section.

Now, search C# and install the C# for Visual Studio Code (powered by OmniSharp) extension for C# language support.

Creating simple running code

Let's create our very first .NET Core 2.0 application. We will create it using Visual Studio Code as well as Visual Studio 2017 in Windows, and with Visual Studio Code in Ubuntu.

The .NET Core 2.0 SDK installs the templates for creating the class library, console, web, MVC, razor, web API, and so on, for applications based on .NET Core 2.0. As our first application, we will create a simple MVC application on .NET Core 2.0, and get familiar with the application code and the .NET Core 2.0 command-line integration.

Let's start by creating this application in Windows using Visual Studio 2017, and then we will create the same application from Visual Studio Code, first in Windows and then in Linux.

Creating an application in Windows through Visual Studio 2017 version 15.3

For this, we need to perform the following steps:

  1. Open Visual Studio 2017.
  2. Go to File | New | Project. In the New Project dialog, you should see the .NET Core template inside Visual C#:
  1. Click on .NET Core and select ASP.NET Core Web Application.
  2. Name the project HelloDotNetCore2 and click OK.
  1. It will show a New ASP.NET Core Web Application dialog. Ensure .NET Core and ASP.NET Core 2.0 are selected in the two dropdowns displayed in this dialog, as we are discussing .NET Core 2.0 here. The first dropdown signifies the target framework of the application and the second dropdown is the version of ASP.NET Core that we are using. You have the option to choose .NET Framework as the target framework in the first dropdown, but then the resulting application would not be cross-platform. If the application has to be cross-platform, it should target .NET Core. The second dropdown has the different versions of ASP.NET Core that have been released so far, such as 1.0, 1.1, and 2.0. We will keep it as ASP.NET Core 2.0. You will also notice that with ASP.NET Core 2.0, the number of templates has increased from the previous version. Apart from Empty, Web API, and Web Application, which were present in ASP.NET 1.1, we also have templates for Web Application (Model-View-Controller),  Angular, React.js, and React.js and Redux. We will choose Web Application (Model-View-Controller) as our template. There is support for a Docker container but let's keep it unchecked for the time being. We will discuss Docker in detail in a later chapter. Also, keep the Authentication as No Authentication. We will explore authentication options in detail in a later chapter. Click OK:
  1. And voila! Visual Studio creates the HelloDotNetCore2 project for us and restores the required packages to build in the background. You can check this by inspecting the Package Manager Console output. Your very first ASP.NET Core 2.0 is ready to be run:
  1. Click Debug or press F5 to run the application. We will see a detailed walk- through of all the project artifacts in the next chapter.

Creating application in Windows through Visual Studio Code

Visual Studio is the IDE and is aware of projects and templates. As stated earlier, Visual Studio Code is a file and folder-based editor and hence it is not aware of projects and templates. So to create the same application through Visual Studio Code, we will make use of the .NET command line. Let's get going!

Open Visual Studio Code, go to View, and click on TERMINAL. It will open Command Prompt/the PowerShell terminal in the bottom section of Visual Studio Code. If you see the PowerShell terminal, type cmd so that it turns into Command Prompt. This is an optional step if you are comfortable with PowerShell.

Let's try and explore the commands available to create a new project, so let's type dotnet --help . This is the help command for dotnet and will let us know about the options that we have available for creating a .NET Core 2.0 MVC application as shown in the following screenshot:

The SDK lists all the possible commands and options that can be used with explanations. So keep in mind, any time you need any help with .NET commands, SDK is there to help us. Just ask for help by typing dotnet --help in the terminal.

From the command list, it looks like the command of interest to us is the new command, as its description reads that this command initializes .NET projects.

So, let's ask SDK how to use the new command by typing dotnet new --help. This will let us know the command that we need to run to create a new MVC application:

Based on the preceding help text, let's enter the following command:

dotnet new mvc -lang C# -n HelloDotNETCore2

This will create a new MVC project named HelloDotNetCore2 in the C# language, in the folder named HelloDotNetCore2 at the location of the terminal. Now let's build and run the application by typing the following commands:

cd HelloDotNetCore2
dotnet build
dotnet run

The first command navigates to the newly created folder, HelloDotNetCore2. Then, we build the application with the second command and run it through the third command. The dotnet build command is just to show that we have a build command as well. The dotnet run command actually builds and runs the application. Now, go to the browser of your choice and navigate to http://localhost:5000 to see the application running in your browser:

Alternatively, you can go to the Explorer view in the activity bar, open the HelloDotNetCore2 folder, and press F5. This will also build the application and launch it in the browser.

Steps for creating the application in Ubuntu through Visual Studio Code are the same as in Windows, but instead of Command Prompt, we have Bash.

F# primer

F# is a functional programming language. Functional programming treats programs as mathematical expressions. It focuses on functions and constants that don't change, rather than variables and states. F# is a Microsoft programming language for concise and declarative syntax. Let's begin with a brief history of how this language came into existence. The first attempt at functional programming was Haskell .NET. F# development began in 2005 and after that, various versions came along. At the time of writing this chapter, F# 4.1 is the latest version; it was released in March 2017. This comes with Visual Studio 2017 and supports .NET Core.

The F# language can be used for the following tasks:

  • To solve mathematical problems
  • For graphic design
  • For financial modeling
  • For compiler programming
  • For CPU design

It is also used for CRUD applications, web pages GUI games, and other programs.

F# keywords

Keywords and their use in the F# language are outlined in the following table:

Keyword

Description

abstract

Indicates that either it has no implementation or is a virtual and has default implementation.

begin

In verbose syntax, indicates the start of a code block.

default

Indicates an implementation of an abstract method; used together with an abstract method declaration to create a virtual method.

elif

Used in conditional branching. A short form of else-if.

end

Used in type definitions and type extensions, indicates the end of a section of member definitions.

In verbose syntax, used to specify the end of a code block that starts with the begin keyword.

exception

Used to declare an exception type.

finally

Used together with try to introduce a block of code that executes regardless of whether an exception occurs.

fun

Used in lambda expressions, and is also known as anonymous functions.

function

Used as a shorter alternative to the fun keyword and a match expression in a lambda expression that has pattern matching on a single argument.

inherit

Used to specify a base class or base interface.

interface

Used to declare and implement interfaces.

let

Used to associate or bind a name to a value or function.

member

Used to declare a property or method in an object type.

mutable

Used to declare a variable; that is, a value that can be changed.

override

Used to implement a version of an abstract or virtual method that differs from the base version.

rec

Used to indicate that a function is recursive.

select

Used in query expressions to specify what fields or columns to extract. Note that this is a contextual keyword, which means that it is not actually a reserved word and it only acts like a keyword in an appropriate context.

static

Used to indicate a method or property that can be called without an instance of a type, or a value member that is shared among all instances of a type.

struct

Used to declare a structure type. Also used in generic parameter constraints. Used for OCaml compatibility in module definitions.

type

Used to declare a class, record, structure, discriminated union, enumeration type, unit of measure, or type abbreviation.

val

Used in a signature to indicate a value, or in a type to declare a member, in limited situations.

yield

Used in a sequence expression to produce a value for a sequence.

 

This reference is taken from the Microsoft official website, and a detailed explanation and description can be found at https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/keyword-reference.

Comments

In the F# language, we have two types of comments for a single line and for multiple lines. This is the same as C#. The following are the two types of comments:

  • A single-line comment which starts with the // symbol.

               Example: // returns an integer exit code

  • A multi-line comment which starts with (* and ends with *).

               Example:  (*Learn more about F# at http://fsharp.org *)

Data types

F# has a rich data type system. We can broadly classify them as:

  • Integral typessbyte, byte, int16, uint16, int32, uint32, int64, and bigint
  • Floating point typesfloat32, float, and decimal
  • Text typeschar and string 
  • Other typesbool

These types are also referred to as fundamental primitive types in F#. Apart from these, F# has an exhaustive list of predefined types as well, such as lists, arrays, records, enumerations, tuples,  units, sequences, and so on. It is recommended that a person learning F# goes through the official Microsoft documentation on F# at https://docs.microsoft.com/en-us/dotnet/fsharp/.

Variable declaration

F# uses the let keyword for the declaration of a variable, for example:

let square x = x*x

The compiler automatically detects this as a value type. If we pass a float value, the compiler will be able to understand that without declaring a data type. Variables in F# are immutable, so once a value is assigned to a variable, it can't be changed. They are compiled as static read-only properties.

The following example demonstrates this:

let x:int32 = 50
let y:int32 = 30
let z:int32 = x + y

Variables x, y, and z are all of type int32 and are immutable, meaning their value cannot be changed.

Let's print their values. The syntax is as follows:

printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

After the preceding code executes, the result is as follows:

x: 50
y: 30
z: 80

Now, suppose we want to modify the value of x from 50 to 60 and check that z reflects the updated sum; we will write the code as:

let x = 60
let y = 30
let z = x + y

On executing this code, we get the following errors, and rightly so because x and z are immutable:

Duplicate definition of value 'x'
Duplicate definition of value 'z'

The correct way of doing it would be to use mutable variables for the declaration, as shown here:

let mutable x = 60
let y = 30 //It's optional to make y mutable.
let mutable z = x + y
x <- 70
z <- x + y

On printing the values again, we will see:

x: 70
y: 30
z: 100

Operators 

F# has the following operators:

  • Arithmetic operators
  • Comparison operators
  • Boolean operators
  • Bitwise operators

Let's discuss these operators in detail.

Arithmetic operators

Arithmetic operators supported by the F# language are outlined in the following table. Assuming variable X = 10 and variable Y = 40 , we have the following expressions:

Operator

Description

Example

+

Adds two values

X + Y  = 50

-

Subtracts the second value from the first

X - Y = -30

*

Multiplies both values

X * Y = 400

/

Divides two values

Y / X = 4

%

Modulus operator and gives the value of the remainder after an integer division

Y % X = 0

**

Exponentiation operator; raises one variable to the power of another

Y**X = 4010

Comparison operators

The following table shows all the comparison operators supported by F# . These operators return true or false.

Let's take X = 20 and Y = 30:

Operator

Description

Example

==

Verifies the values of two variables are equal; if not, then the condition becomes false.

(X == Y) returns false

<> 

Verifies the values of two variables are equal; if values are not equal then the condition becomes true.

(X <> Y) returns true

> 

Verifies the value of the left variable is greater than the value of the right variable; if not, then the condition becomes false.

(X > Y) returns false

< 

Verifies the value of the left variable is less than the value of the right variable; if yes, then the condition becomes true.

(X < Y) returns true

>=

Verifies the value of the left variable is greater than or equal to the value of the right variable; if not, then condition becomes false.

(X >= Y) returns false

<=

Verifies the value of the left variable is less than or equal to the value of the right variable; if yes, then the condition becomes true.

(X <= Y) returns true

Boolean operators

The following table shows all the Boolean operators supported by the F# language. Let's take variable X as true and Y as false:

Operator

Description

Example

&&

Boolean AND operator. If both the bool values are true means 1, then the condition is true.

(X && Y) is false

||

Boolean OR operator. If either of the two bool values is true means 1, then the condition is true.

(X || Y) is true

not

Boolean NOT operator. If the condition is true, then the logical NOT operator will become false and vice versa.

not (X && Y) is true

Bitwise operators

Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &&& (bitwise AND), ||| (bitwise OR), and ^^^ (bitwise exclusive OR) are shown as follows. In the following table, the first variable is X and the second variable is Y:

X

Y

X &&& Y

X ||| Y

X ^^^ Y

0

0

0

0

0

0

1

0

1

1

1

1

1

1

0

1

0

0

1

1

 

It also supports ~~~(Unary, effect of flipping bits) , <<< (left shift operator), and >>>(right shift operator).

Decision-making statements

The F# language has the following (if...else and loop) types of decision-making statements.

if statements

The following table shows all the ways of implementing if statements:

Statement

Description

if/then statement

 An if/then statement consists of a Boolean expression followed by one or more statements.

if/then/else statement

An if/then statement can be followed by an optional else statement, which executes when the Boolean expression is false.

if/then/elif/else statement

An if/then/elif/else statement allows you to have multiple else statements.

Nested if statements

You can use one if or else if statement inside another if or else if statements.

Loop statements

F# provides the following types of loop:

Loop type

Description

for…to and for…downto expressions

The for...to expression is used to iterate in a loop over a range of values of a loop variable. The for…downto expression reduces the value of a loop variable.

for…in expression

This form of for loop is used to iterate over collections of items; that is, loops over collections and sequences.

while…do loop

Repeats a statement or group of statements while the given condition is true. It tests the condition before executing the loop body.

nested loops

We can use one or more loop inside any other for or while loop.

F# functions

F# functions act like variables. We can declare and use them in the same way as we use variables in C#. A function definition starts with the let keyword, followed by the function name and parameters, a colon, its type, and the right-side expression, showing what the function does. The syntax is follows:

Let functionName parameters [ : returnType] = functionbody

In the preceding syntax:

  • functionName is an identifier of the function.
  • parameters gives the list of parameters separated by spaces. We can also specify an explicit type for each parameter and if not specified, the compiler tends to presume it from the function body as variables.
  • functionbody comprises an expression, or a compound expression, which has number of expressions. The final expression in the function body is the return value.
  • returnType is a colon followed by a type and it is optional. If the returnType is not specified, then the compiler determines it from the final expression in the function body.

Have a look at the following example for our syntax: 

let addValue (x : int) = 5 + x

Calling a function

A function can be called by passing the function name followed, by a space, and then arguments (if any) separated by spaces, as shown here:

let sum = addValue 3

We can perform many tasks using F# functions, some of which are as follows:

  • We can create a new function and link that function with a type as it acts as a variable type:
    let square x = x*x
  • We can perform some calculations as well, such as:
    let square x = x*x
  • We can assign a value. Taking the same example:
    let square x = x*x
  • We can pass a function as a parameter to another function like this:
    let squareValue = List.map square[1;2;3] // using square function
  • We can return a function as a result of another function example:
    let squareValue = List.map square[1;2;3]

File sequence

The order of files in a project matters in an F# solution. The file used in any function should be placed above the file where the function is used, because F# has a forward-only model of compilation.

Unlike C#, where the file sequence doesn't matter, the sequencing of files does matter in F#. For example, consider that Program.fs is using DotNetCorePrint.fs. So, DotNetCorePrint.fs should be placed above Program.fs in the solution; otherwise, it will throw a compilation error. To move a file up or down, we can right-click on the file and select Move Up or the keys Alt + the up arrow to move the file. The ordering of the files in Solution Explorer can be seen in the following screenshot:

Basic input/output syntax

We are now going to see how to write and read in F#. To read and write into the console, we can use the following commands:

  • To write: System.Console.Write("Welcome!")
  • To read: System.Console.Read()
  • To print: printfn "Hello"

Let's compare F# with C#:

                                F#

C#

The F# user is free from the obligation of defining types; for example: let square x = x* x

The compiler can identify (integer * integer) or (float * float) when we pass a value.

 

The C# user is bound to provide a type:

Public int square(int x){ return x = x*x ; }

 

F# has immutable data, and the value never changes; for example: let number = [3;2;1]

let moreNumber = 4:: number

In the preceding example, to add one more number, (4), we need to create a new list of items using number, and add the new record, 4 in this case. The same list doesn't get modified for safer asynchronous execution and a simplified understanding of a function.

C# has mutable as well as immutable data. Strings are immutable, the rest are all mutable, for example:

var number = new List<int> {1,2,3}; number.Add(4);

In the preceding example, we created a list and added a new item to the same list. The list gets modified.



F# compiles code in an order. It is favoured for data processing and algorithmic computation. It doesn't work on visibility; it works sequentially.

 

C# code works on visibility. The sequence doesn't matter.

The order of files in a project matters in the F# solution. A file used in any method should be placed above the file where the method has been used.

 





The order doesn't matter in C#.

 

 

 

 

F# has precise syntax; it focuses on what not and how; for example:

let square x = x*x

let squared = List.map square[1;2;3]  // using square function

Right-click execute | result 1;4;9

F# uses declarative syntax, not imperative syntax as in C#. F# helps us to minimize accidental complexity, meaning complexity that is not a part of the problem, but which we introduced as part of the solution, for example:

let rec quicksort = function | [] -> [] | x :: xs ->  let smaller = List.filter((>)x) xs let larger = List.filter ((<=)x) xs

Quicksort smaller @ [x] @ quicksort larger:

 

Let sorted = quicksort [4;5;4;7;9;1;6;1;0;-99;10000;3;2]

 

rec is used for a recursive function. It is assigned in the sorted result. Run it and you will get a sorted result. It is a very simple sorting function with less complexity than C#, which has a high chance of errors.

 

C# code implementation is more about how to implement. It sometimes increases unnecessary complexity as part of the solution to a problem.

Quick sort has a very complex algorithm and a high chance of increasing accidental complexity.

Summary

In this chapter, we discussed downloading Visual Studio Code, .NET Core 2.0, an Ubuntu 17.04 ISO image, and the tools required to start .NET Core application creation, as well as how to install them on Windows and Linux machines. We also discussed how to set up a Ubuntu Linux virtual machine and introduced the F# language. 

In the following chapter, you'll be introduced to native libraries in .NET Core, used to extend console capabilities. We will discuss Interop with existing libraries and ncurses. 

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Bridges the gap between learning and doing and improves your software development skills
  • Covers the best practices of .NET development to improve your productivity
  • Example-based approach to get you started quickly with software programming

Description

With the rise in the number of tools and technologies available today, developers and architects are always exploring ways to create better and smarter solutions. Before, the differences between target platforms was a major roadblock, but that's not the case now. .NET Core 2.0 By Example will take you on an exciting journey to building better software. This book provides fresh and relevant content to .NET Core 2.0 in a succinct format that’s enjoyable to read. It also delivers concepts, along with the implications, design decisions, and potential pitfalls you might face when targeting Linux and Windows systems, in a logical and simple way. With the .NET framework at its center, the book comprises of five varied projects: a multiplayer Tic-tac-toe game; a real-time chat application, Let'sChat; a chatbot; a microservice-based buying-selling application; and a movie booking application. You will start each chapter with a high-level overview of the content, followed by the above example applications described in detail. By the end of each chapter, you will not only be proficient with the concepts, but you’ll also have created a tangible component in the application. By the end of the book, you will have built five solid projects using all the tools and support provided by the .NET Core 2.0 framework.

Who is this book for?

If you are a developer or architect and want to learn how to build cross-platform solutions using Microsoft .NET Core, this book is for you. It is assumed that you have some knowledge of the .NET Framework, OOP, and C# (or a similar programming language).

What you will learn

  • Build cross-platform applications with ASP.NET Core 2.0 and its tools
  • Integrate, host, and deploy web apps with the cloud (Microsoft Azure)
  • Leverage the ncurses native library to extend console capabilities in .NET Core on Linux and interop with native coden .NET Core on Linux and learn how to interop with existing native code
  • Reuse existing .NET Framework and Mono assemblies from .NET Core 2.0 applications
  • Develop real-time web applications using ASP.NET Core
  • Learn the differences between SOA and microservices and get started with microservice development using ASP.NET Core 2.0
  • Walk through functional programming with F# and .NET Core from scratch

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 20, 2018
Length: 458 pages
Edition : 1st
Language : English
ISBN-13 : 9781788390262
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Product Details

Publication date : Mar 20, 2018
Length: 458 pages
Edition : 1st
Language : English
ISBN-13 : 9781788390262
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.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
£169.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
£234.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 £ 120.97
Building Microservices with .NET Core 2.0
£36.99
C# 7 and .NET Core 2.0 Blueprints
£41.99
.NET Core 2.0 By Example
£41.99
Total £ 120.97 Stars icon

Table of Contents

11 Chapters
Getting Started Chevron down icon Chevron up icon
Native Libraries in .NET Core Chevron down icon Chevron up icon
Building Our First .NET Core Game – Tic-Tac-Toe Chevron down icon Chevron up icon
Let&#x27;s Chat Web Application Chevron down icon Chevron up icon
Developing the Let&#x27;s Chat Web Application Chevron down icon Chevron up icon
Testing and Deploying – The Let&#x27;s Chat Web Application Chevron down icon Chevron up icon
To the Cloud Chevron down icon Chevron up icon
Movie Booking Web App Chevron down icon Chevron up icon
Microservices with .NET Core Chevron down icon Chevron up icon
Functional Programming with F# Chevron down icon Chevron up icon
Other Books You May Enjoy 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.3
(6 Ratings)
5 star 50%
4 star 33.3%
3 star 16.7%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




atul sharma May 30, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Being a developer myself and was looking for resources to get up to speed with .Net Core , this book proved to be an excellent starter. The way it builds up right from machine set up and slowly progresses into building up fully functional applications, is seamless and eloquent.The thing that i most liked about this book is , how the instructions of the samples are not limited to the development but extends to the deployment and testing of it. It also has a brief introduction to cloud , followed by an example on how to leverage cloud for application hosting. To summarize, this book is one of my good reads.
Amazon Verified review Amazon
Amazon Customer Apr 16, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good book for the beginners. Examples are good and the apps developed in the book, makes it interesting. Tips and tricks on ASP.NET Core 2.0 and Azure were fresh and great to know.
Amazon Verified review Amazon
Abhimanyu Apr 26, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
PROS:Learned in-depth about ASP.NET Core 2.0 , the examples of developing four simple apps on Azure really helped.I think it is great for beginners and intermediate developers starting with .NET Core 2.0 as it explains the fundamentals from ground zero and using examples.Tips and tricks section was my favorite, which shares a wealth of handy information about Azure, .NET Core working and performance. Gives me quick knowledge which experts take months to accumulate.CONS:The book covers the breadth of technology. Due to the format of the book, few of the topics are not covered in depth, but the additional links and references sort of pointed me in the right direction.Overall, I would recommend this book to people new to asp.net.
Amazon Verified review Amazon
Suhas May 05, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Not only is this a great book for someone who is starting their journey to .NET Core but also helps an intermediate developer to get a clearer understanding of .NET core and fill in some of those gaps. The book does expect you to have a fair understanding of C# and basic programming constructs like async/await etc.The books starts off by discussing how to get started with .NET Core on various platforms - whether it's on Windows, Mac or Linux, covering various tools relevant to each of the operating systems.The authors then give examples of building a Tic Tac Toe game, a Chat application and even a movie booking app on Azure using .NET Core and along the way introducing us to various concepts like ASP.NET Core, SignalR, EF Core and take us through various elements in the platform, giving a good idea of when to use what.Personally what I loved about the book is how it takes an example first approach to explain the concepts in a clear and concise manner which otherwise could have been quite boring and dry.In terms of what is missing - some limitations of .NET Core could have been discussed and where not to use and instead prefer .NET. Practical use cases of where you'd use .NET Core over would also help.In terms of what could be better - Future roadmap talks only about .NET Core 2.1 in Microservices chapter - but its limited to that.For someone coming from .NET background, it would have been good to highlight similarities & differences between .NET Core and .NET (Few are listed, but scattered over like under the heading Handy things to know inside the Microservices with .NET Core chapter)I personally also felt some aspects of Azure were not required in this book since they are not really relevant to .NET Core such as spinning up Azure VMs & Automating using Powershell. Rather an introduction to Powershell Core would have been handy.Overall this book is a great read and would definitely recommend this.
Amazon Verified review Amazon
Penelope May 11, 2020
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
In Chpter 8: Could make the getting started with EFcore code example to work. The MovieBooking app had problems though. Theory coverage is great though.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.