C# 7 and .NET Core: Modern Cross-Platform Development - Mark J. Price - E-Book

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

Mark J. Price

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 492

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Hello, C#! Welcome, .NET Core!
Choosing your development environment
Using alternative C# IDEs
Deploying cross-platform
Installing Microsoft Visual Studio 2017 for Windows
Choosing workloads
Choosing additional components
Signing in to Visual Studio 2017
Choosing your settings
Reviewing Visual Studio's user interface
Installing Microsoft Visual Studio Code for Windows, macOS, or Linux
Installing Microsoft Visual Studio Code for macOS
Installing .NET Core for macOS
Installing Homebrew
Installing OpenSSL
Installing .NET Core SDK
Installing the Visual Studio Code extension for C#
Understanding .NET
Understanding .NET Framework
Understanding the Mono and Xamarin projects
Understanding .NET Core
Streamlining .NET
Understanding .NET Standard
.NET used in this book
Understanding .NET Native
Comparing .NET technologies
Writing and compiling code using the .NET Core CLI tool
Writing code using a simple text editor
If you are using Windows Notepad
If you are using macOS TextEdit
Compiling code using the .NET Core CLI tool
Restoring packages and running the application
Fixing compiler errors
Understanding Intermediate Language
Writing and compiling code using Microsoft Visual Studio 2017
Writing code using Microsoft Visual Studio 2017
Coding with Visual Studio's editor
Compiling code using Visual Studio 2017
Fixing mistakes with the error list
Adding existing projects to Visual Studio 2017
Autoformatting code
Experimenting with C# Interactive
Other useful windows
Writing and compiling code using Microsoft Visual Studio Code
Writing code using Visual Studio Code
Compiling code using Visual Studio Code
Managing source code with GitHub
Using Git with Visual Studio 2017
Using the Team Explorer window
Cloning a GitHub repository
Managing a GitHub repository
Using Git with Visual Studio Code
Configuring Git at the command line
Managing Git with Visual Studio Code
Practicing and exploring
Exercise 1.1 - test your knowledge
Exercise 1.2 - practice coding anywhere
Exercise 1.3 - explore topics
Summary
2. Speaking C#
Understanding C# basics
Using Visual Studio 2017
Using Visual Studio Code on macOS, Linux, or Windows
C# grammar
Statements
Comments
Blocks
C# vocabulary
C# keywords
Writing the code
Verbs are methods
Nouns are types, fields, and variables
Counting types and methods
Building and running with Visual Studio 2017
Building and running with Visual Studio Code
Declaring variables
Naming variables
Literal values
Storing text
Storing numbers
Storing whole numbers
C# 7 improvements
Storing real numbers
Using Visual Studio 2017
Using Visual Studio Code
Writing code to explore numbers
Comparing double and decimal
Storing Booleans
The object type
The dynamic type
Local variables
Inferring the type of a local variable
Making a value type nullable
Checking for null
Storing multiple values in an array
Building console applications
Displaying output to the user
Getting input from the user
Importing a namespace
Simplifying the usage of the console
Reading arguments and working with arrays
Passing arguments with Visual Studio 2017
Passing arguments with Visual Studio Code
Viewing the output
Enumerating arguments
Running on Windows
Running on macOS
Handling platforms that do not support an API
Operating on variables
Experimenting with unary operators
Experimenting with arithmetic operators
Comparison and Boolean operators
Practicing and exploring
Exercise 2.1 - test your knowledge
Exercise 2.2 - practice number sizes and ranges
Exercise 2.3 - explore topics
Summary
3. Controlling the Flow, Converting Types, and Handling Exceptions
Selection statements
Using Visual Studio 2017
Using Visual Studio Code on macOS, Linux, or Windows
The if statement
Pattern matching with the if statement
The switch statement
Pattern matching with the switch statement
Iteration statements
The while statement
The do statement
The for statement
The foreach statement
How does the foreach statement work?
Casting and converting between types
Casting from numbers to numbers
Casting explicitly
Using the convert type
Rounding numbers
Converting from any type to a string
Parsing from strings to numbers or dates and times
Handling exceptions
The try statement
Catching all exceptions
Catching specific exceptions
The finally statement
Simplifying disposal with the using statement
Checking for overflow
The checked statement
The unchecked statement
Looking for help
Microsoft Docs and MSDN
Go to definition
StackOverflow
Google
Subscribing to blogs
Design patterns
Singleton pattern
Practice and explore
Exercise 3.1 - test your knowledge
Exercise 3.2 - explore loops and overflow
Exercise 3.3 - practice loops and operators
Exercise 3.4 - practice exception handling
Exercise 3.5 - explore topics
Summary
4. Using .NET Standard Types
Using assemblies and namespaces
Comparing .NET Framework with .NET Core
Base Class Libraries and CoreFX
Assemblies, NuGet packages, and platforms
Namespaces
Referencing a dependent assembly
Browsing assemblies with Visual Studio 2017
Understanding .NET Core project files
Relating assemblies and namespaces
Importing a namespace
Relating C# keywords to .NET types
Storing and manipulating text
Getting the length of a string
Getting the characters of a string
Splitting a string
Getting part of a string
Checking a string for content
Other string members
Building strings efficiently
Pattern matching with regular expressions
The syntax of a regular expression
Examples of regular expressions
Storing data with collections
Understanding collections
Lists
Dictionaries
Stacks
Queues
Sets
Working with lists
Working with dictionaries
Sorting collections
Using specialized collections
Internationalizing an application
Globalizing an application
Practicing and exploring
Exercise 4.1 - test your knowledge
Exercise 4.2 - practice regular expressions
Exercise 4.3 - explore topics
Summary
5. Debugging, Monitoring, and Testing
Debugging tools
Debugging an application
Setting a breakpoint
The debugging toolbar
Debugging windows
Stepping through code
Customizing breakpoints
Monitoring performance and resource usage
Evaluating the efficiency of types
Monitoring performance and memory use
Measuring the efficiency of processing strings
Unit testing an application
Creating a class library that needs testing with Visual Studio 2017
Creating a unit test project with Visual Studio 2017
Creating a class library that needs testing with Visual Studio Code
Writing unit tests
Running unit tests with Visual Studio 2017
Running unit tests with Visual Studio Code
Practicing and exploring
Exercise 5.1 - test your knowledge
Exercise 5.2 - practice debugging and unit testing
Exercise 5.3 - explore topics
Summary
6. Building Your Own Types with Object-Oriented Programming
Talking about OOP
Building class libraries
Creating a class library with Visual Studio 2017
Creating a class library with Visual Studio Code
Defining a class
Instantiating a class
Referencing an assembly using Visual Studio 2017
Referencing an assembly using Visual Studio Code
Importing a namespace
Managing multiple projects with Visual Studio Code
Inheriting from System.Object
Storing data with fields
Defining fields
Understanding access modifiers
Storing a value using the enum keyword
Storing multiple values using collections
Making a field static
Making a field constant
Making a field read-only
Initializing fields with constructors
Writing and calling methods
Combining multiple values with tuples
Referencing the System.ValueTuple package with Visual Studio 2017
Referencing the System.ValueTuple package with Visual Studio Code
Defining methods with tuples
Naming the fields of a tuple
Deconstructing tuples
Defining and passing parameters to methods
Overloading methods
Optional parameters and named arguments
Controlling how parameters are passed
Splitting classes using partial
Controlling access with properties and indexers
Defining read-only properties
Defining settable properties
Defining indexers
Practicing and exploring
Exercise 6.1 - test your knowledge
Exercise 6.2 - practice writing mathematical methods
Exercise 6.3 - explore topics
Summary
7. Implementing Interfaces and Inheriting Classes
Setting up a class library and console application
Using Visual Studio 2017
Using Visual Studio Code
Defining the classes
Simplifying methods with operators
Implementing some functionality with a method
Implementing some functionality with an operator
Defining local functions
Raising and handling events
Calling methods using delegates
Defining events
Implementing interfaces
Common interfaces
Comparing objects when sorting
Defining a separate comparer
Managing memory with reference and value types
Defining a struct type
Releasing unmanaged resources
Ensuring that dispose is called
Inheriting from classes
Extending classes
Hiding members
Overriding members
Preventing inheritance and overriding
Polymorphism
Casting within inheritance hierarchies
Implicit casting
Explicit casting
Handling casting exceptions
Inheriting and extending .NET types
Inheriting from an exception
Extending types when you can't inherit
Using static methods to reuse functionality
Using extension methods to reuse functionality
Practice and explore
Exercise 7.1 - test your knowledge
Exercise 7.2 - practice creating an inheritance hierarchy
Exercise 7.3 - explore topics
Summary
8. Working with Databases Using the Entity Framework Core
Relational Database Management Systems
Using a sample database
Using Microsoft SQL Server on Windows
Connecting to Microsoft SQL Server LocalDb
Creating the Northwind sample database
Managing the Northwind sample database
Using SQLite on macOS and mobile platforms
Running a script for SQLite
Choosing a .NET data provider
Connecting to the database
Setting up Entity Framework Core
Using Visual Studio 2017
Using Visual Studio Code
Entity Framework Core models
EF Core conventions
EF Core annotation attributes
EF Core Fluent API
Building an EF Core Model
Querying an EF Core model
Logging EF Core
Loading patterns with EF Core
Eager and lazy loading entities
Explicit loading entities
Manipulating data with EF Core
Inserting entities
Updating entities
Deleting entities
Transactions
Defining an explicit transaction
Practicing and exploring
Exercise 8.1 - test your knowledge
Exercise 8.2 - explore the EF Core documentation
Summary
9. Querying and Manipulating Data with LINQ
Writing LINQ queries
Extending sequences with the enumerable class
Filtering entities with Where
Targeting a named method
Simplifying the code by removing the explicit delegate instantiation
Targeting a lambda expression
Sorting entities with OrderBy
Sorting by multiple properties with the ThenBy method
Working with sets
Projecting entities with Select
Building an EF Core model
Joining and grouping
Sweetening the syntax with syntactic sugar
Using multiple threads with parallel LINQ
Creating your own LINQ extension methods
Working with LINQ to XML
Generating XML using LINQ to XML
Reading XML by using LINQ to XML
Practicing and exploring
Exercise 9.1 - test your knowledge
Exercise 9.2 - practice querying with LINQ
Exercise 9.3 - explore topics
Summary
10. Working with Files, Streams, and Serialization
Managing the filesystem
Managing directories
Managing files
Managing paths
Getting file information
Reading and writing with streams
Writing to text and XML streams
Compressing streams
Encoding text
Encoding strings as byte arrays
Encoding and decoding text in files
Serializing object graphs
Serializing with XML
Deserializing with XML
Customizing the XML
Serializing with JSON
Serializing with other formats
Practice and explore
Exercise 10.1 - test your knowledge
Exercise 10.2 - practice serializing as XML
Exercise 10.3 - explore serialization formats
Exercise 10.4 - explore topics
Summary
11. Protecting Your Data
Understanding the vocabulary of protection
Keys and key sizes
IVs and block sizes
Salts
Generating keys and IVs
Encrypting and decrypting data
Encrypting symmetrically with AES
Using Visual Studio 2017
Using Visual Studio Code
Creating the Protector class
Hashing data
Hashing with SHA256
Signing data
Signing with SHA256 and RSA
Practicing and exploring
Exercise 11.1 - test your knowledge
Exercise 11.2 - practice protecting data with encryption and hashing
Exercise 11.3 - practice protecting data with decryption
Exercise 11.4 - explore topics
Summary
12. Improving Performance and Scalability with Multitasking
Understanding processes, threads, and tasks
Running tasks asynchronously
Running multiple actions synchronously
Running multiple actions asynchronously using tasks
Waiting for tasks
Continuing with another task
Nested and child tasks
Synchronizing access to shared resources
Accessing a resource from multiple threads
Applying a mutually exclusive lock to a resource
Understanding the lock statement
Making operations atomic
Applying other types of synchronization
Implementing multitasking for a GUI
Creating a GUI that blocks
Creating a GUI that doesn't block
Other types with Async methods
await in catch blocks
Improving scalability for client-server applications
Practicing and exploring
Exercise 12.1 - test your knowledge
Exercise 12.2 - explore topics
Summary
13. Building Universal Windows Platform Apps Using XAML
Understanding Universal Windows Platform
Adapting your app's layout
Taking advantage of unique device capabilities
Understanding XAML
Simplifying code using XAML
Choosing common controls
Creating an app for Universal Windows Platform
Using resources and templates
Sharing resources
Replacing a control template
Data binding
Binding to elements
Binding to data
Animating with storyboards
Testing in emulators
Practicing and exploring
Exercise 13.1 - test your knowledge
Exercise 13.2 - practice building a universal tip calculator
Exercise 13.3 - explore topics
Summary
14. Building Web Applications Using ASP.NET Core MVC
Understanding ASP.NET Core
Classic ASP.NET versus modern ASP.NET Core
Client-side web development
Understanding HTTP
Creating an ASP.NET Core project with Visual Studio 2017
Performing database migrations
Reviewing authentication with ASP.NET Identity
Creating an ASP.NET Core project with Visual Studio Code
Managing client-side packages with Bower
Exploring an ASP.NET Core MVC web application
ASP.NET Core startup
Understanding the default route
ASP.NET Core MVC controllers
ASP.NET Core MVC models
Create Entity models for Northwind
Configure Entity Framework Core as a service
Create view models for requests
Fetch the model in the controller
ASP.NET Core MVC views
Rendering the Home controller's views
Sharing layouts between views
Defining custom styles
Defining a typed view
Taking ASP.NET Core MVC further
Passing parameters using a route value
Passing parameters using a query string
Annotating models
Practicing and exploring
Exercise 14.1 - test your knowledge
Exercise 14.2 - practice building a data-driven web application
Exercise 14.3 - explore topics
Summary
15. Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API
Understanding Xamarin.Forms
How Xamarin.Forms extends Xamarin
Mobile first, cloud first
Installing Xcode
Installing Visual Studio for Mac
Building services using ASP.NET Core Web API and Visual Studio Code
Creating an ASP.NET Core Web API project
Creating a web service for the Northwind database
Creating the Northwind database
Referencing the EF Core NuGet packages
Creating the entity model and database context
Creating the data repository
Configuring and registering the data repository
Set the database connection string
Creating the Web API controller
Testing the web service
Testing GET requests with any browser
Testing POST, PUT, DELETE, and other requests with Postman
Building mobile apps using Xamarin.Forms and Visual Studio for Mac
Creating a Xamarin.Forms project
Creating a model
Creating an interface for dialing phone numbers and implement for iOS and Android
Creating views for the customers list and customer details
Test the mobile app with iOS
Adding NuGet packages for calling a REST service
Getting customers from the service
Practicing and exploring
Exercise 15.1 - test your knowledge
Exercise 15.2 - explore topics
Summary
16. Packaging and Deploying Your Code Cross-Platform
Porting to .NET Core
Could you port?
Should you port?
Differences between .NET Framework and .NET Core
Understanding the .NET Portability Analyzer
Sharing code cross-platform with .NET Standard class libraries
Creating a .NET Standard class library
Using Visual Studio 2017
Using Visual Studio Code on macOS
Understanding NuGet packages
Referencing packages
Understanding metapackages
Understanding Frameworks
Fixing dependencies
Switching to a different .NET Standard
Publishing your applications
Creating a console application to publish
Publishing with Visual Studio 2017
Publishing with Visual Studio Code
Deploying to the cloud
Creating an ASP.NET Core MVC web application to publish
Register an Azure account
Create an Azure web app
Publishing an ASP.NET web application to the web app
Developing on and for Linux
Practicing and exploring
Exercise 16.1 - test your knowledge
Exercise 16.2 - explore topics
Summary
A. Answers to the Test Your Knowledge Questions
Chapter 1 - Hello, C#! Welcome, .NET Core!
Chapter 2 - Speaking C#
Chapter 3 - Controlling the Flow, Converting Types, and Handling Exceptions
Chapter 4 - Using .NET Standard Types
Chapter 5 - Debugging, Monitoring, and Testing
Chapter 6 - Building Your Own Types with Object-Oriented Programming
Chapter 7 - Implementing Interfaces and Inheriting Classes
Chapter 8 - Working with Databases Using Entity Framework Core
Chapter 9 - Querying and Manipulating Data with LINQ
Chapter 10 - Working with Files, Streams, and Serialization
Chapter 11 - Protecting Your Data
Chapter 12 - Improving Performance and Scalability with Multitasking
Chapter 13 - Building Universal Windows Platform Apps Using XAML
Chapter 14 - Building Web Applications Using ASP.NET Core MVC
Chapter 15 - Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API
Chapter 16 - Packaging and Deploying Your Code Cross-Platform

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

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

Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2016

Second edition: March 2017

Production reference: 1210317

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78712-955-9

www.packtpub.com

Credits

Author

Mark J. Price

Copy Editor

Zainab Bootwala

Reviewer

Fabio Claudio Ferracchiati

Project Coordinator

Izzat Contractor

Commissioning Editor

Aaron Lazar

Proofreader

Safis Editing

Acquisition Editor

Nitin Dasan

Indexer

Francy Puthiry

Content Development Editor

Siddhi Chavan

Graphics

Abhinash Sahu

Technical Editors

Sunith Shetty

Abhishek Sharma

Production Coordinator

Nilesh Mohite

About the Author

Mark J. Price is a Microsoft Certified Trainer (MCT) and Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with more than 20 years of educational and programming experience.

Since 1993, Mark has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them too. His students range from professionals with decades of experience to 16 year old apprentices with none. He successfully guides all of them by combining educational skills with real-world experience in consulting and developing systems for enterprises worldwide.

Between 2001 and 2003, Mark was employed full-time to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET.

Currently, Mark creates and delivers training courses for Episerver's Digital Experience Cloud, the best .NET CMS for Digital Marketing and E-commerce.

In 2010, Mark studied for a Postgraduate Certificate in Education (PGCE). He taught GCSE and A-Level mathematics in two London secondary schools. He holds a Computer Science BSc. Hons. Degree from the University of Bristol, UK.

Thank you to my parents, Pamela and Ian, for raising me to be polite, hardworking, and curious about the world. Thank you to my sisters, Emily and Juliet, for loving me despite being their awkward older brother. Thank you to my friends and colleagues who inspire me technically and creatively. Lastly, thanks to all the students I have taught over the years for motivating me to be the best teacher that I can be.

About the Reviewer

Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works for React Consulting (www.reactconsulting.it). He is a Microsoft Certified Solution Developer for .NET, a Microsoft Certified Application Developer for .NET, a Microsoft Certified Professional, and a prolific author and technical reviewer. Over the past ten years, he's written articles for Italian and international magazines and co-authored more than ten books on a variety of computer topics.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787129551.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Preface

There are C# books that are thousands of pages long that aim to be comprehensive references to the C# programming language and the .NET Framework.

This book is different. It is concise and aims to be a fast-paced read that is packed with hands-on walkthroughs. I wrote this book to be the best step-by-step guide to modern cross-platform C# proven practices using .NET Core.

I will point out the cool corners and gotchas of C# so you can impress colleagues and employers and get productive fast. Rather than slowing down and boring some readers by explaining every little thing, I will assume that if a term I use is new to you, then you will know how to Google it.

At the end of each chapter is a section titled Practice and explore, in which you will complete hands-on practical exercises and explore topics deeper on your own with a little nudge in the right direction from me.

You can download solutions for the exercises from the following GitHub repository. I will provide instructions on how to do this using Visual Studio 2017 and Visual Studio Code at the end of Chapter 1, Hello, C#! Welcome, .NET Core!

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

What this book covers

Chapter 1, Hello, C#! Welcome, .NET Core!, is about setting up your development environment and using various tools to create the simplest application possible with C#. You will learn how to write and compile code using Visual Studio 2017 on Windows, or Visual Studio Code on macOS, Linux, or Windows. You will learn about the different .NET technologies: .NET Framework, .NET Core, .NET Standard, and .NET Native.

Chapter 2, Speaking C#, is about the C# language---the grammar and vocabulary that you will use every day to write the source code for your applications. In particular, you will learn how to declare and work with variables of different types.

Chapter 3, Controlling Flow, Converting Types, and Handling Exceptions, is about writing code that makes decisions, repeats a block of statements, converts between types, and handles errors. You will also learn the best places to look for help.

Chapter 4, Using .NET Standard Types, is about commonly used .NET Core types that are part of .NET Standard and how they are related to C#. You will learn about the .NET Standard class library assemblies and the NuGet packages of types that allow your applications to connect existing components to perform common practical tasks, such as manipulating text, storing items in collections, and implementing internationalization.

Chapter 5, Debugging, Monitoring, and Testing, is about debugging tools, monitoring, diagnosing problems, and testing your code to remove bugs and ensuring high performance, stability, and reliability.

Chapter 6, Building Your Own Types with Object-Oriented Programming, is about all the different categories of members that a type can have, including fields to store data and methods to perform actions. You will use OOP concepts, such as aggregation and encapsulation. You will learn about the C# 7 language features such as tuple syntax support and out variables.

Chapter 7, Implementing Interfaces and Inheriting Classes, is about deriving new types from existing ones using object-oriented programming (OOP). You will learn how to define operators and C# 7 local functions, delegates and events, how to implement interfaces about base and derived classes, how to override a type member, how to use polymorphism, how to create extension methods, and how to cast between classes in an inheritance hierarchy.

Chapter 8, Working with Databases Using Entity Framework Core, is about reading and writing to databases, such as Microsoft SQL Server and SQLite, using the object-relational mapping technology known as the Entity Framework Core.

Chapter 9, Querying and Manipulating Data with LINQ, is about Language INtegrated Query (LINQ)---language extensions that add the ability to work with sequences of items and filter, sort, and project them into different outputs.

Chapter 10, Working with Files, Streams, and Serialization, is about managing the filesystem, reading and writing to files and streams, text encoding, and serialization.

Chapter 11, Protecting Your Data, is about protecting your data from being viewed by malicious users using encryption and from being manipulated or corrupted using hashing and signing.

Chapter 12, Improving Performance and Scalability with Multitasking, is about allowing multiple actions to occur at the same time to improve performance, scalability, and user productivity.

Chapter 13, Building Universal Windows Platform Apps Using XAML, is about learning the basics of XAML that can be used to define the user interface for a graphical app for the Universal Windows Platform (UWP). This app can then run on Windows 10, Windows 10 Mobile, Xbox One, and even HoloLens.

Chapter 14, Building Web Applications Using ASP.NET Core MVC, is about learning the basics of building web applications with a modern HTTP architecture on the server side using ASP.NET Core MVC. You will learn about the startup configuration, authentication, routes, models, views, and controllers that make up ASP.NET Core MVC.

Chapter 15, Building Mobile Apps Using Xamarin.Forms and ASP.NET Core Web API, is about learning the basics of how to take C# mobile by building a cross-platform mobile app for iOS and Android that calls a service built on ASP.NET Core Web API. The client-side mobile app will be created with Visual Studio for Mac and the server-side Web API service will be created with Visual Studio Code, both running on macOS.

Chapter 16, Packaging and Deploying Your Code Cross-Platform, is about publishing your apps and libraries, creating and distributing NuGet packages, and deploying your code cross-platform and to the cloud.

Appendix A, Answers to the Test Your Knowledge Questions, has the answers to the test questions at the end of each chapter.

What you need for this book

You can develop and deploy C# on many platforms, including Windows, macOS, and many varieties of Linux. For the best programming experience, and to reach the most platforms, I recommend that you learn the basics of all members of the Visual Studio family: Visual Studio 2017, Visual Studio Code, and Visual Studio for Mac.

My recommendation for the operating system and development tool combinations is as follows:

Windows 10 for Visual Studio 2017macOS for Visual Studio for MacmacOS for Visual Studio Code

The best version of Windows to use is Microsoft Windows 10 because you will need this version to create Universal Windows Platform apps in Chapter 13, Building Universal Windows Platform Apps Using XAML. Earlier versions of Windows, such as 7 or 8.1 will work for all other chapters.

Who this book is for

If you have heard that C# is a popular general-purpose cross-platform programming language used to create everything, ranging from business applications, web sites, and services, to games for mobile devices, Xbox One, and the Windows 10 desktop to tablet and phone platforms, then this book is for you.

If you have heard that .NET Core is Microsoft's bet on a cross-platform .NET future, optimized for server-side web development in the cloud, and client-side mobile development with Xamarin, combined with a cross-platform development tool in Visual Studio Code, then this book is for you.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit

http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/CSharp-7-And-NET-Core-Modern-CrossPlatform-Development-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/CSharp7andDotNETCoreModernCrossPlatformDevelopmentSecondEdition_ColorImages.pdf

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

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 environmentInstalling Microsoft Visual Studio 2017 for WindowsInstalling Microsoft Visual Studio Code for Windows, macOS, or LinuxUnderstanding .NETWriting and compiling code using the .NET Core CLI toolWriting and compiling code using Microsoft Visual Studio 2017Writing and compiling code using Microsoft Visual Studio CodeManaging 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:

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.3Visual Studio 2017 on Windows 10 (in a virtual machine)Visual Studio Code on Red Hat Enterprise Linux (in a virtual machine)

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:

For MonoDevelop IDE, visit http://www.monodevelop.com/For JetBrains Rider, visit https://www.jetbrains.com/rider/

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 laterWindows Server 2008 R2 SP1, or laterOS X El Capitan (version 10.11) and macOS Sierra (version 10.12)Red Hat Enterprise Linux 7.2Ubuntu 14.04 LTS, 16.04 LTSLinux Mint 17Debian 8.2CentOS 7.1Oracle Linux 7.1Docker

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 developmentASP.NET and web developmentAzure developmentMobile development with .NET.NET Core cross-platform development

Choosing additional components

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

Class DesignerPowerShell toolsGit for WindowsGitHub extension for Visual Studio

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

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:

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:

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 .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 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 updatebrew install opensslmkdir -p /usr/local/libln -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 .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:

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

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:

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 FrameworkXamarin.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 2, Speaking 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:

.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 13, Building 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 PiServer-side web development with ASP.NET CoreConsole applications for use on the command line

Comparing .NET technologies

The following table summarizes and compares .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 projectdotnet new classlib: creates a new assembly library projectdotnet new web: creates a new empty ASP.NET Core projectdotnet new mvc: creates a new ASP.NET Core MVC projectdotnet new webapi: creates a new ASP.NET Core Web API projectdotnet restore: downloads dependencies for the projectdotnet build: compiles the projectdotnet test: runs unit tests on the projectdotnet run: runs the projectdotnet migrate: migrates a .NET Core project created with the preview CLI tools to the current CLI tool MS Build formatdotnet pack: creates a NuGet package for the projectdotnet 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:

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

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:

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:

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 projectCreate a new console application in the directoryList the files that the dotnet command-line tool created

If you are using Windows, in Command Prompt, enter:

cd C:\Code\Chapter01\Ch01_HelloCSdotnet new consoledir

If you are using macOS, in Terminal, enter:

cd Code/Chapter01/Ch01_HelloCSdotnet new consolels

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 applicationCh01_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