39,59 €
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:
Seitenzahl: 492
Veröffentlichungsjahr: 2017
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
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
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.
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.
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.
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!
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.
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.
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:
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.
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.
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.
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 e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
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!
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
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# 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:
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.
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:
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:
There are alternative IDEs for C#, for example, MonoDevelop and JetBrains Rider. You can install either of these two IDEs with the help of the following URLs:
Cloud9 is a web browser-based IDE, so it's even more cross-platform than the others. It is growing in popularity. Here is the link:https://c9.io/web/sign-up/free.
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:
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.
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.
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/
On the Workloads tab, choose the following, as partially shown in the following screenshot:
On the Individual components tab, choose the following additional components, as shown in the following screenshot:
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.
While you wait for Visual Studio 2017 to install, you can jump ahead to the Understanding .NET section in this chapter.
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/.
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:
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:
To have quick access to Visual Studio in the future, right-click on its entry in the Windows taskbar and select Pin to taskbar.
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/.
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:
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 -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:
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:
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.
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:
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.
.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 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.
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.
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
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/
.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.
.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.
The situation with .NET today is that there are three forked .NET platforms, all controlled by Microsoft:
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:
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.
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:
The following table summarizes and compares .NET technologies:
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:
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!
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#!"); } }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!
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:
In TextEdit, from the File menu, choose Save..., or press Cmd + S.
In the dialog box, change to your user folder (mine is named markjprice) or any directory in which you want to use to save your projects, click on the New Folder button, and name the folder Code. Open the Code folder, and click the New Folder button, and name the folder Chapter01. Open the Chapter01 folder, and click the New Folder button, and name the folder Ch01_HelloCS. Open the Ch01_HelloCS folder.
In the Plain Text Encoding field, select Unicode (UTF-8) from the drop-down list, uncheck the box for If no extension is provided, use ".txt" to avoid appending the .txt file extension, enter the filename as MyApp.cs, and click on Save, as shown in the following screenshot:
If you are using Windows, start Command Prompt.
If you are using macOS, launch Terminal.
At the prompt, enter the following command:
dotnetYou should see the following output describing the dotnet CLI tool:
The output from the dotnet command-line tool will be identical on Windows, macOS, and Linux.
Enter the following commands at the prompt to:
If you are using Windows, in Command Prompt, enter:
cd C:\Code\Chapter01\Ch01_HelloCSdotnet new consoledirIf you are using macOS, in Terminal, enter:
cd Code/Chapter01/Ch01_HelloCSdotnet new consolelsThe 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:
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.csIf you are using macOS, in Terminal:
rm Program.csIn all future examples, we will use the Program.cs