57,59 €
C# 7.1 and .NET Core 2.0 – Modern Cross-Platform Development, Third Edition, is a practical guide to creating powerful cross-platform applications with C# 7.1 and .NET Core 2.0. It gives readers of any experience level a solid foundation in C# and .NET. The first part of the book runs you through the basics of C#, as well as debugging functions and object-oriented programming, before taking a quick tour through the latest features of C# 7.1 such as default literals, tuples, inferred tuple names, pattern matching, out variables, and more.
After quickly taking you through C# and how .NET works, this book dives into the .NET Standard 2.0 class libraries, covering topics such as packaging and deploying your own libraries, and using common libraries for working with collections, performance, monitoring, serialization, files, databases, and encryption. The final section of the book demonstrates the major types of application that you can build and deploy cross-device and cross-platform. In this section, you'll learn about websites, web applications, web services, Universal Windows Platform (UWP) apps, and mobile apps. By the end of the book, you'll be armed with all the knowledge you need to build modern, cross-platform applications using C# and .NET.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 636
BIRMINGHAM - MUMBAI
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
Third edition: November 2017
Production reference: 1291117
ISBN 978-1-78839-807-7
www.packtpub.com
Author
Mark J. Price
Copy Editor
Tom Jacob
Reviewers
Dustin Heffron
Efraim Kyriakidis
Proofreader
Safis Editing
Acquisition Editor
Ben Renow-Clarke
Indexer
Rekha Nair
Project Editor
Radhika Atitkar
Graphics
Kirk D'Penha
Content Development Editor
Chris Nelson
Production Coordinator
Shantanu Zagade
Technical Editors
Bhagyashree Rai
Gaurav Gavas
Mark J. Price is a Microsoft Certified Solutions Developer (MCSD), Microsoft Specialist: Programming in C#, and Episerver Certified Developer, with more than 20 years of educational and programming experience.
Since 1993, Mark has passed more than 80 Microsoft programming exams, and he 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 Microsoft Certified Trainers up-to-speed on C# and .NET.
Currently, Mark creates and delivers classroom and e-learning training courses for Episerver's Digital Experience Cloud, the best .NET CMS for Digital Marketing and E-commerce. He is an Episerver Certified Developer (ECD) on Episerver CMS.
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.
Dustin Heffron is a software engineer by day and an independent game developer by night. He has over 10 years of experience programming in various languages, eight of which have been in working with C# and .NET.
Currently, Dustin develops tools to automate and test medical instruments at Becton Dickinson. He is also the cofounder and CEO for SunFlake Studios. Dustin has a long history of reviewing for Packt, including XNA 4.0 Game Development by Example: Beginner's Guide, C# 6 and .NET Core 1.0: Modern Cross-Platform Development, and the video tutorial series XNA 3D Programming by Example. He also coauthored the video tutorial series XNA 3D Toolkit with Larry Louisiana.
Efraim Kyriakidis is a skilled software engineer with over 10 years of experience on developing and delivering software solutions for diverse customers and projects. He's well-versed in all stages of the software development life cycle. His first acquaintance with computers and programming was a state of the art Commodore 64, back in the '80s as a kid. Since then he has grown and received his Diploma from Aristotle University Thessaloniki in Greece. Throughout his career, he mainly worked with Microsoft technologies, using C# and .NET since .NET 1.0. He currently works for Siemens AG in Germany as a software developer.
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.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
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/1788398076.
If you'd like to join our team of regular reviewers, you can email 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
What this book covers
Part 1 – C# 7.1
Part 2 – .NET Core 2.0 and .NET Standard 2.0
Part 3 – App Models
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
Hello, C#! Welcome, .NET Core!
Setting up your development environment
Using alternative C# IDEs
Deploying cross-platform
Installing Microsoft Visual Studio 2017
Choosing workloads
Choosing additional components
Installing Microsoft Visual Studio Code
Installing Microsoft Visual Studio Code for macOS
Installing .NET Core SDK for macOS
Installing Node Package Manager for macOS
Installing the Visual Studio Code extension for C#
Installing Visual Studio for Mac
Installing Xcode
Downloading and installing Visual Studio for Mac
Understanding .NET
Understanding .NET Framework
Understanding the Mono and Xamarin projects
Understanding .NET Core
Understanding .NET Standard
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
Creating and compiling apps using the .NET Core CLI tool
Creating a console application at Command Prompt
Restoring packages, compiling code, and running the application
Fixing compiler errors
Understanding intermediate language
Writing and compiling code using Visual Studio 2017
Writing code using Microsoft Visual Studio 2017
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 Visual Studio Code
Writing code using Visual Studio Code
Compiling code using Visual Studio Code
Autoformatting code
Writing and compiling code using Visual Studio for Mac
Next steps
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 C# anywhere
Exercise 1.3 – Explore topics
Summary
Part 1, C# 7.1
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
Help for writing correct code
Verbs are methods
Nouns are types, fields, and variables
Revealing the extent of the C# vocabulary
Building and running with Visual Studio 2017
Building and running with Visual Studio Code
Adding more types with Visual Studio 2017 and 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 types
Storing Booleans
The object type
The dynamic type
Local variables
Specifying the type of a local variable
Inferring the type of a local variable
Making a value type nullable
Understanding nullable reference types
The billion-dollar mistake
Changing the defaults for nullable types in C# 8.0
Checking for null
Storing multiple values in an array
Exploring console applications further
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
Controlling the Flow and Converting Types
Selection statements
Using Visual Studio 2017
Using Visual Studio Code on macOS, Linux, or Windows
The if statement
The code
Pattern matching with the if statement
The switch statement
The code
Pattern matching with the switch statement
Iteration statements
The while statement
The do statement
The for statement
The foreach statement
Casting and converting between types
Casting from numbers to numbers
Casting numbers implicitly
Casting numbers explicitly
Using the convert type
Rounding numbers
Converting from any type to a string
Converting from a binary object to a string
Parsing from strings to numbers or dates and times
Handling exceptions when converting types
The try statement
Catching all exceptions
Catching specific exceptions
Checking for overflow
The checked statement
The unchecked statement
Looking for help
Microsoft Docs and MSDN
Go to definition
Stack Overflow
Subscribing to blogs
Design patterns
Singleton pattern
Practicing and exploring
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
Writing, Debugging, and Testing Functions
Writing functions
Writing a times table function
Writing a function that returns a value
Writing mathematical functions
Formatting numbers for output
Calculating factorials with recursion
Debugging an application during development
Creating an application with a deliberate bug
Setting a breakpoint
The debugging toolbar
Debugging windows
Stepping through code
Customizing breakpoints
Logging during development and runtime
Instrumenting with Debug and Trace
Writing to the default trace listener
Configuring trace listeners
Switching trace levels
Unit testing functions
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 4.1 – Test your knowledge
Exercise 4.2 – Practice writing functions with debugging and unit testing
Exercise 4.3 – Explore topics
Summary
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
Setting fields with default literal
Writing and calling methods
Combining multiple values with tuples
Defining methods with tuples
Naming the fields of a tuple
Inferring tuple names
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 5.1 – Test your knowledge
Exercise 5.2 – Explore topics
Summary
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
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 or Visual Studio Code
Implementing interfaces
Common interfaces
Comparing objects when sorting
Attempting to sort objects without a method to compare
Defining a method to compare
Defining a separate comparer
Making types more reusable with generics
Making a generic type
Making a generic method
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
Using Visual Studio 2017
Using Visual Studio 2017 or Visual Studio Code
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
Practicing and exploring
Exercise 6.1 – Test your knowledge
Exercise 6.2 – Practice creating an inheritance hierarchy
Exercise 6.3 – Explore topics
Summary
Part 2 – .NET Core 2.0 and .NET Standard 2.0
Understanding and Packaging .NET Standard Types
Understanding assemblies and namespaces
Base Class Libraries and CoreFX
Assemblies, NuGet packages, and platforms
Namespaces
Understanding dependent assemblies
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 and Visual Studio Code
Relating assemblies and namespaces
Browsing assemblies with Visual Studio 2017
Using Visual Studio 2017 or Visual Studio Code
Importing a namespace
Relating C# keywords to .NET types
Sharing code cross-platform with .NET Standard 2.0 class libraries
Creating a .NET Standard 2.0 class library
Using Visual Studio 2017
Using Visual Studio Code
Understanding NuGet packages
Understanding metapackages
Understanding frameworks
Fixing dependencies
Publishing your applications for deployment
Creating a console application to publish
Publishing with Visual Studio 2017 on Windows
Publishing with Visual Studio Code on macOS
Packaging your libraries for NuGet distribution
Understanding dotnet commands
Adding a package reference
Using Visual Studio Code
Using Visual Studio 2017
Packaging a library for NuGet
Testing your package
Using Visual Studio Code
Using Visual Studio 2017
Using Visual Studio 2017 and Visual Studio Code
Porting from .NET Framework to .NET Core
Could you port?
Should you port?
Differences between .NET Framework and .NET Core
Understanding the .NET Portability Analyzer
Using non-.NET Standard libraries
Practicing and exploring
Exercise 7.1 – Test your knowledge
Exercise 7.2 – Explore topics
Summary
Using Common .NET Standard Types
Working with numbers
Working with big integers
Working with complex numbers
Working with 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
Working with collections
Common features of all collections
Understanding collections
Lists
Dictionaries
Stacks
Queues
Sets
Working with lists
Working with dictionaries
Sorting collections
Using specialized collections
Using immutable collections
Working with network resources
Working with URIs, DNS, and IP addresses
Pinging a server
Working with types and attributes
Versioning of assemblies
Reading assembly metadata
Creating custom attributes
Doing more with reflection
Internationalizing your code
Globalizing an application
Practicing and exploring
Exercise 8.1 – Test your knowledge
Exercise 8.2 – Practice regular expressions
Exercise 8.3 – Practice writing extension methods
Exercise 8.4 – Explore topics
Summary
Working with Files, Streams, and Serialization
Managing the filesystem
Handling cross-platform environments and filesystems
Using Windows 10
Using macOS
Managing drives
Managing directories
Managing files
Managing paths
Getting file information
Controlling files
Reading and writing with streams
Writing to text and XML streams
Writing to text streams
Writing to XML streams
Disposing of file resources
Implementing disposal with try statement
Simplifying disposal with the using statement
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
Practicing and exploring
Exercise 9.1 – Test your knowledge
Exercise 9.2 – Practice serializing as XML
Exercise 9.3 – Explore topics
Summary
Protecting Your Data and Applications
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 the commonly used SHA256
Signing data
Signing with SHA256 and RSA
Testing the signing and validating
Generating random numbers
Generating random numbers for games
Generating random numbers for cryptography
Testing the random key or IV generation
Authenticating and authorizing users
Implementing authentication and authorization
Testing authentication and authorization
Protecting application functionality
Practicing and exploring
Exercise 10.1 – Test your knowledge
Exercise 10.2 – Practice protecting data with encryption and hashing
Exercise 10.3 – Practice protecting data with decryption
Exercise 10.4 – Explore topics
Summary
Working with Databases Using Entity Framework Core
Understanding modern databases
Using a sample relational database
Using Microsoft SQL Server
Connecting to SQL Server
Creating the Northwind sample database for SQL Server
Managing the Northwind sample database with Server Explorer
Using SQLite
Creating the Northwind sample database for SQLite
Managing the Northwind sample database with SQLiteStudio
Setting up Entity Framework Core
Choosing an EF Core data provider
Connecting to the database
Using Visual Studio 2017
Using Visual Studio Code
Defining Entity Framework Core models
EF Core conventions
EF Core annotation attributes
EF Core Fluent API
Building an EF Core model
Defining the Category entity class
Defining the Product entity class
Defining the Northwind database context class
Querying an EF Core model
Logging EF Core
Pattern matching with Like
Defining global filters
Loading patterns with EF Core
Eager and lazy loading entities
Explicit loading entities
Manipulating data with EF Core
Inserting entities
Updating entities
Deleting entities
Pooling database contexts
Transactions
Defining an explicit transaction
Practicing and exploring
Exercise 11.1 – Test your knowledge
Exercise 11.2 – Practice exporting data using different serialization formats
Exercise 11.3 – Explore the EF Core documentation
Summary
Querying and Manipulating Data Using 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
Sorting by a single property using OrderBy
Sorting by a subsequent property using ThenBy
Filtering by type
Working with sets
Using LINQ with EF Core
Projecting entities with Select
Building an EF Core model
Joining and grouping
Aggregating sequences
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 using LINQ to XML
Practicing and exploring
Exercise 12.1 – Test your knowledge
Exercise 12.2 – Practice querying with LINQ
Exercise 12.3 – Explore topics
Summary
Improving Performance and Scalability Using Multitasking
Monitoring performance and resource usage
Evaluating the efficiency of types
Monitoring performance and memory use
Using Visual Studio 2017
Using Visual Studio Code
Creating the Recorder class
Measuring the efficiency of processing strings
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
Understanding async and await
Improving responsiveness for console apps
Improving responsiveness for GUI apps
Improving scalability for web applications and web services
Common types that support multitasking
await in catch blocks
Practicing and exploring
Exercise 13.1 – Test your knowledge
Exercise 13.2 – Explore topics
Summary
Part 3 – App Models
Building Web Sites Using ASP.NET Core Razor Pages
Understanding web development
Understanding HTTP
Client-side web development
Understanding ASP.NET Core
Classic ASP.NET versus modern ASP.NET Core
Creating an ASP.NET Core project with Visual Studio 2017
Creating an ASP.NET Core project with Visual Studio Code
Reviewing the ASP.NET Core Empty project template
Testing the empty website
Enabling static files
Enabling default files
Exploring Razor Pages
Enabling Razor Pages
Defining a Razor Page
Using shared layouts with Razor Pages
Setting a shared layout
Defining a shared layout
Using code-behind files with Razor Pages
Using Entity Framework Core with ASP.NET Core
Creating Entity models for Northwind
Creating a class library for the Northwind entity classes
Defining the entity classes
Creating a class library for Northwind database context
Using Visual Studio 2017
Using Visual Studio Code
Defining the database context class
Creating the Northwind database in the website
Configure Entity Framework Core as a service
Manipulating data
Practicing and exploring
Exercise 14.1 – Practice building a data-driven website
Exercise 14.2 – Explore topics
Summary
Building Web Sites Using ASP.NET Core MVC
Setting up an ASP.NET Core MVC website
Creating an ASP.NET Core MVC website
Using Visual Studio 2017
Using Visual Studio Code
Reviewing the ASP.NET Core MVC project template
Performing database migrations
Using Visual Studio 2017
Using Visual Studio Code
Testing the ASP.NET MVC website
Reviewing authentication with ASP.NET Identity
Understanding an ASP.NET Core MVC website
ASP.NET Core startup
Understanding the default route
Understanding ASP.NET Core MVC controllers
Understanding ASP.NET Core MVC models
Configuring an EF Core entity data model
Creating view models for requests
Fetch the model in the controller
Understanding ASP.NET Core MVC views
Rendering the Home controller's views
Sharing layouts between views
Defining custom styles
Defining a typed view
Passing parameters using a route value
Passing parameters using a query string
Practicing and exploring
Exercise 15.1 – Practice improving scalability by understanding and implementing async action methods
Exercise 15.2 – Explore topics
Summary
Building Web Services and Applications Using ASP.NET Core
Building web services using ASP.NET Core Web API
Understanding ASP.NET Core controllers
Creating an ASP.NET Core Web API project
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 and Visual Studio Code
Creating a web service for the Northwind database
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 and Visual Studio Code
Creating data repositories for entities
Configuring and registering the customers repository
Creating the Web API controller
Documenting and testing web services using Swagger
Testing GET requests with any browser
Testing POST, PUT, and DELETE requests with Swagger
Installing a Swagger package
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 and Visual Studio Code
Testing GET requests with Swagger UI
Testing POST requests with Swagger UI
Building SPAs using Angular
Understanding the Angular project template
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 and Visual Studio Code
Calling NorthwindService
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 and Visual Studio Code
Modifying the home component to call NorthwindService
Testing the Angular component calling the service
Using Visual Studio 2017
Using Visual Studio Code
Using Visual Studio 2017 and Visual Studio Code
Using other project templates
Installing additional template packs
Practicing and exploring
Exercise 16.1 – Practice with React and Redux
Exercise 16.2 – Explore topics
Summary
Building Windows Apps Using XAML and Fluent Design
Understanding the modern Windows platform
Understanding Universal Windows Platform
Understanding Fluent Design System
Filling user interface elements with acrylic brushes
Connecting user interface elements with animations
Parallax views and Reveal lighting
Understanding XAML Standard 1.0
Simplifying code using XAML
Choosing common controls
Creating a modern Windows app
Enabling developer mode
Creating a UWP project
Exploring common controls and acrylic brushes
Exploring Reveal
Installing more controls
Using resources and templates
Sharing resources
Replacing a control template
Data binding
Binding to elements
Binding to data sources
Modifying the NorthwindService
Creating the Northwind app
Building apps using Windows Template Studio
Installing Windows Template Studio
Selecting project types, frameworks, pages, and features
Retargeting the project
Customizing some views
Testing the app's functionality
Practicing and exploring
Exercise 17.1 – Explore topics
Summary
Building Mobile Apps Using XAML and Xamarin.Forms
Understanding Xamarin and Xamarin.Forms
How Xamarin.Forms extends Xamarin
Mobile first, cloud first
Building mobile apps using Xamarin.Forms
Adding Android SDKs
Creating a Xamarin.Forms solution
Creating a model
Creating an interface for dialing phone numbers
Implement the phone dialer for iOS
Implement the phone dialer for Android
Creating views for the customers list and customer details
Creating the view for the list of customers
Creating the view for the customer details
Testing the mobile app with iOS
Adding NuGet packages for calling a REST service
Getting customers from the service
Practicing and exploring
Exercise 18.1 - Explore topics
Summary
Summary
Good luck!
Answers to the Test Your Knowledge Questions
Chapter 1 – Hello, C#! Welcome, .NET Core!
Chapter 2 – Speaking C#
Chapter 3 – Controlling the Flow and Converting Types
Chapter 4 – Writing, Debugging, and Testing Functions
Chapter 5 – Building Your Own Types with Object-Oriented Programming
Chapter 6 – Implementing Interfaces and Inheriting Classes
Chapter 7 – Understanding and Packaging .NET Standard Types
Chapter 8 – Using Common .NET Standard Types
Chapter 9 – Working with Files, Streams, and Serialization
Chapter 10 – Protecting Your Data and Applications
Chapter 11 – Working with Databases Using Entity Framework Core
Chapter 12 – Querying and Manipulating Data Using LINQ
Chapter 13 – Improving Performance and Scalability Using Multitasking
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 learning 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 an answer.
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/cs7dotnetcore2
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; Visual Studio Code on macOS, Linux, or Windows; or Visual Studio for Mac on macOS. You will learn the different .NET technologies: .NET Framework, .NET Core, .NET Standard, and .NET Native.
Chapter 2, Speaking C#, explains 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 the Flow and Converting Types, talks about writing code that makes decisions, repeats a block of statements, and converts between types, and writing code defensively to handle errors when they inevitably occur. You will also learn the best places to look for help.
Chapter 4, Writing, Debugging, and Testing Functions, is about following the Don't Repeat Yourself (DRY) principle by writing reusable functions, and learning how to use debugging tools to track down and remove bugs, monitoring your code while it executes to diagnose problems, and rigorously testing your code to remove bugs and ensure stability and reliability before it gets deployed into production.
Chapter 5, Building Your Own Types with Object-Oriented Programming, discusses 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 the C# 7 language features such as tuple syntax support and out variables, and C# 7.1 language features such as default literals and inferred tuple names.
Chapter 6, Implementing Interfaces and Inheriting Classes, explains 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 7, Understanding and Packaging .NET Standard Types, presents .NET Core 2.0 types that are part of .NET Standard 2.0, and how they are related to C#. You will learn how to deploy and package your own apps and libraries.
Chapter 8, Using Common .NET Standard Types, discusses the .NET Standard types that allow your code to perform common practical tasks, such as manipulating numbers and text, storing items in collections, and implementing internationalization.
Chapter 9, Working with Files, Streams, and Serialization, talks about interacting with the filesystem, reading and writing to files and streams, text encoding, and serialization.
Chapter 10, Protecting Your Data and Applications, is about protecting your data from being viewed by malicious users using encryption and from being manipulated or corrupted using hashing and signing. You will also learn about authentication and authorization to protect applications from unauthorized uses.
Chapter 11, Working with Databases Using Entity Framework Core, explains reading and writing to databases, such as Microsoft SQL Server and SQLite, using the object-relational mapping technology named Entity Framework Core.
Chapter 12, Querying and Manipulating Data Using LINQ, teaches you 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 13, Improving Performance and Scalability Using Multitasking, discusses allowing multiple actions to occur at the same time to improve performance, scalability, and user productivity. You will learn about the C# 7.1 async Main feature, and how to use types in the System.Diagnostics namespace to monitor your code to measure performance and efficiency.
Chapter 14, Building Web Sites Using ASP.NET Core Razor Pages, is about learning the basics of building websites with a modern HTTP architecture on the server-side using ASP.NET Core. You will learn the new ASP.NET Core feature known as Razor Pages that simplifies creating web pages for small web sites.
Chapter 15,Building Web Sites Using ASP.NET Core MVC, is about learning how to build large, complex websites in a way that is easy to unit test and manage with teams of programmers using ASP.NET Core. You will learn about startup configuration, authentication, routes, models, views, and controllers in ASP.NET Core MVC.
Chapter 16, Building Web Services and Applications Using ASP.NET Core, explains building web applications with a combination of a modern frontend technology, such as Angular or React, and a backend REST architecture web service using ASP.NET Core Web API.
Chapter 17, Building Windows Apps Using XAML and Fluent Design, talks 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), and applying principles and features of Fluent Design to light it up. This app can then run on any device running Windows 10, Xbox One, and even Mixed Reality devices such as HoloLens.
Chapter 18, Building Mobile Apps Using XAML and Xamarin.Forms, discusses introducing you to taking C# mobile by building a cross-platform app for iOS and Android. The client-side mobile app will be created with Visual Studio for Mac using XAML and Xamarin.Forms.
Appendix, Answers to the Test Your Knowledge Questions, has the answers to the test questions at the end of each chapter.
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:
Visual Studio 2017 on
Windows 10
Visual Studio for Mac on
macOS
Visual Studio Code on
Windows 10 or macOS
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 17, Building Windows Apps Using XAML and Fluent Design. Earlier versions of Windows, such as 7 or 8.1, will work for the other chapters.
The best version of macOS to use is Sierra or High Sierra because you will need macOS to build iOS mobile apps in Chapter 18,Building Mobile Apps Using XAML and Xamarin.Forms. Although you can use Visual Studio 2017 on Windows to write the code for iOS and Android mobile apps, you must have macOS and Xcode to compile them.
If you have heard that C# is a popular general-purpose programming language used to create every type of software, ranging from web applications and services, to business applications and games, then this book is for you.
If you have heard that C# can create software that runs on a wide range of devices, from desktop to server, from mobile to gaming systems such as Xbox One, 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 Augmented Reality (AR) or Virtual Reality (VR) devices such as HoloLens, then this book is for you.
If you have heard that Microsoft has a popular cross-platform developer tool named Visual Studio Code that creates these cross-platform apps, and you are curious to try it, then this book is for you.
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 email [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.
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.
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 emailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your email 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 Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/CSharp-7.1-and-.NET-Core-2.0-Modern-Cross-Platform-Development-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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/CSharp71andNETCore20ModernCrossPlatformDevelopmentThirdEdition_ColorImages.pdf.
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 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.
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.
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# 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 in 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:
Setting up
your development environment
Understanding .NET
Writing and compiling code using the .NET Core CLI tool
Writing and compiling code using Visual Studio 2017
Writing and compiling code using Visual Studio Code
Writing and compiling code using Visual Studio for Mac
Managing source code with GitHub
Before you start programming, you will need to choose an Integrated Development Environment (IDE) that includes a code editor for C#. Microsoft has a family of IDEs:
Visual Studio 2017
Visual Studio for Mac
Visual Studio Code
The most mature and fully-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.
The most suitable IDE to choose for mobile development is Visual Studio for Mac. To create apps for iOS (iPhone and iPad), tvOS, macOS, and watchOS, you must have macOS and Xcode. Although you can use Visual Studio 2017 with its Xamarin extensions to write a cross-platform mobile app, you still need macOS and Xcode to compile it.
The following table shows which IDE and operating systems can or must be used for each of the chapters in this book:
Chapters
IDE
Operating systems
Chapters 1 to 16
Visual Studio 2017
Windows 7 SP1 or later
Chapters 1 to 16
Visual Studio Code
Windows, macOS, Linux
Chapters 1 to 16
Visual Studio for Mac
macOS
Chapter 17
Visual Studio 2017
Windows 10
Chapter 18
Visual Studio for Mac
macOS
To write the third edition of this book, I used the following listed software, as shown in the following screenshot:
Visual Studio 2017 on Windows 10 in a virtual machine
Visual Studio for Mac on macOS
Visual Studio Code on macOS
Visual Studio Code on RHEL (not shown in screenshot)
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
Your choice of IDE and operating system for development does not limit where your code gets deployed. .NET Core 2.0 supports the following platforms for deployment:
Windows 7 SP1, or later
Windows Server 2008 R2 SP1, or later
Windows IoT 10, or later
macOS Sierra (version 10.12), or later
RHEL 7.3, or later
Ubuntu 14.04, or later
Fedora 25, or later
Debian 8.7, or later
openSUSE 42.2, or later
Tizen 4, or later
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 Installing Microsoft Visual Studio Code for Windows, macOS, or Linuxsection.If you prefer to use Microsoft Visual Studio for Mac, jump ahead to theInstalling Microsoft Visual Studio for Macsection.
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 Fall Creators Update.
Since October 2014, Microsoft has made a professional-quality edition of Visual Studio available to everyone for free. It is called Community Edition.
Download and install Microsoft Visual Studio 2017 version 15.4 or later from the following link:
https://www.visualstudio.com/downloads/
On the Workloads tab, choose the following, as partially shown in the following screenshot:
Universal Windows Platform development
.NET desktop development
ASP.NET and web development
Azure development
Node.js development
.NET Core cross-platform development
On the Individual components tab, choose the following additional components:
Class Designer
GitHub extension for Visual Studio
PowerShell tools
Click on Install, and wait for the installer to acquire the selected software, and install it. When the installation is complete, click on Launch.
The first time that you run Visual Studio 2017, you will be prompted to sign in. If you have a Microsoft account, you can use that account. If you don't, then register for a new one at the following link:
https://signup.live.com/
When starting Visual Studio 2017 for the first time, you will be prompted to configure your environment. For Development Settings, choose Visual C#. For the color theme, I chose Blue, but you can choose whatever tickles your fancy.
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:
InChapter 14,Building Web Sites Using ASP.NET Core Razor Pages,Chapter 15, Building Web Sites Using ASP.NET Core MVC,andChapter 16,Building Web Services and Applications Using ASP.NET Core,you will need Node.js and NPM installed.
Download the Node.js installer for Windows from the following link:
https://nodejs.org/en/download/
Run the Node.js installer, as shown in the following screenshot:
Between June 2015 and September 2017, Microsoft released a new version of Visual Studio Code almost every month. Visual Studio Code has rapidly improved and surprised Microsoft with its popularity. Even if you plan to use Visual Studio 2017 or Visual Studio for Mac 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 the following link:
https://code.visualstudio.com/
In this book, I will show examples and screenshots of Visual Studio Code 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:
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
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 -fsSLhttps://raw.githubusercontent.com/Homebrew/install/master/install)"
Terminal will prompt you to press Enter to continue and then prompt for your password.
The next step is to download the .NET Core SDK installer for macOS (x64) from the following link:
https://www.microsoft.com/net/download/core
Run the dotnet-sdk-2.0.0-sdk-osx-x64.pkg installer package, as shown in the following screenshot:
Click on Continue, accept the license agreement, click on Install, and then, once it has finished, click on Close.
In Chapter 14, Building Web Sites Using ASP.NET Core Razor Pages, Chapter 15,Building Web Sites Using ASP.NET Core MVC,andChapter 16,Building Web Services and Applications Using ASP.NET Core, you will need Node.js and NPM installed.
In Terminal, enter commands to install Node.js and NPM, and then check their versions, which at the time I wrote this book, were Node.js version 8.4 and NPM version 5.3, as shown in the following screenshot:
brew install node
node -v
npm -v
The C# for Visual Studio Code extension is not necessary, but it provides IntelliSense as you type, so it's very handy to install.
Launch Visual Studio Code and click on the Extensions icon, or go to 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 on Install, and then click on Reload, to reload the window and activate the extension.
In November 2016, Microsoft released a preview version of Visual Studio for Mac. Initially, it could only be used to create Xamarin mobile apps, because it is a fork of the Xamarin Studio product. The final release version, available since May 2017, has support for creating .NET Standard 2.0 class libraries, ASP.NET Core web applications and services, and console apps, so it can be used to complete (almost) all of the exercises in this book.
Although Visual Studio 2017 on Windows can be used to create mobile apps for iOS and Android, only Xcode running on macOS or OS X can compile iOS apps, so it is my opinion that a developer might as well use the native Visual Studio for Mac to create mobile apps.
If you have not already installed Xcode on your Mac, install it now from the App Store.
On the Apple menu, choose App Store....
In the App Store, enter xcode in the Search box, and one of the first results will be Xcode, as shown in the following screenshot:
Click on Get, and wait for Xcode to install.
You can download and install Visual Studio for Mac from the following link:
https://www.visualstudio.com/vs/visual-studio-mac/
In the Visual Studio for MacInstaller, accept the License Terms and the Privacy Statement, choose to install all components, and then click on Continue, as shown in the following screenshot:
Click on Continue, and then click on Install.
Agree to the license terms for the components, such as the Android SDK, click on Continue, and wait for Visual Studio for Mac to fully install.
Start Visual Studio for Mac to see the Welcome Page, as shown in the following screenshot:
If you are prompted to update components, then click on Restart and Install Updates.
Now that you have installed and set up your development environment, you will learn some background about .NET before diving in to writing code.
.NET Framework, .NET Core, .NET Standard, and .NET Native are related and overlapping platforms for developers to build applications and services upon.
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.
Third parties developed a .NET implementation named the Mono project that you can read more about at the following link: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