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

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

Mark J. Price

0,0
43,19 €

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

The book has now been updated

About This Book

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

Who This Book Is For

Are you struggling to get started with C#? Or maybe you're interested in the potential of the new cross-platform features that .NET Core can offer? If so, C# 6 and .NET Core 1.0 is the book for you. While you don't need to know any of the latest features of C# or .NET to get started, it would be beneficial if you have some programming experience.

What You Will Learn

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

In Detail

With the release of .NET Core 1.0, you can now create applications for Mac OS X and Linux, as well as Windows, using the development tools you know and love. C# 6 and .NET Core 1.0 has been divided into three high-impact sections to help start putting these new features to work.

First, we'll run you through the basics of C#, as well as object-orient programming, before taking a quick tour through the latest features of C# 6 such as string interpolation for easier variable value output, exception filtering, and how to perform static class imports. We'll also cover both the full-feature, mature .NET Framework and the new, cross-platform .NET Core.

After quickly taking you through C# and how .NET works, we'll dive into the internals of the .NET class libraries, covering topics such as performance, monitoring, debugging, internationalization, serialization, and encryption. We'll look at Entity Framework Core 1.0 and how to develop Code-First entity data models, as well as how to use LINQ to query and manipulate that data.

The final section will demonstrate the major types of applications that you can build and deploy cross-device and cross-platform. In this section, we'll cover Universal Windows Platform (UWP) apps, web applications, and web services. Lastly, we'll help you build a complete application that 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.

Style and approach

This book takes a step-by-step approach and is filled with exciting projects and fascinating theory. It uses three high-impact sections to equip you with all the tools you'll need to build modern, cross-platform applications using C# and .NET Core.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 503

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



Table of Contents

C# 6 and .NET Core 1.0
Credits
About the Author
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Hello, C#! Welcome, .NET Core!
Setting up your development environment
Using alternative C# IDEs
Using Visual Studio 2015 on Windows 10
Installing Microsoft Visual Studio 2015
Choosing the default installation
Choosing the custom installation
Completing the installation
Signing in to Visual Studio
Choosing development settings
Updating extensions and products
Using older versions of Visual Studio
Understanding .NET Framework, .NET Core, and .NET Native
Understanding .NET Framework platform
Understanding the Mono project
Understanding the .NET Core platform
Streamlining .NET
The future of .NET
Understanding the .NET Native platform
Comparing .NET technologies
Writing and compiling code using the Developer Command Prompt
Writing code using Notepad
Compiling code using the Developer Command Prompt
Fixing compiler errors
Decompiling code using ILDASM
Disassembling compiled assemblies
Writing and compiling code using Microsoft Visual Studio 2015
Writing code using Visual Studio 2015
Compiling code using Visual Studio
Fixing mistakes with the error list
Experimenting with C# Interactive
Other useful windows
Targeting the .NET Core
Understanding the .NET Portability Analyzer
Installing the .NET Portability Analyzer
Configuring the .NET Portability Analyzer
Analyzing a solution
.NET Portability and this book
Creating new projects for the .NET Core
Managing .NET Core development with Command Line Tools
Installing the .NET Command Line Tools
Creating a .NET Core application using Command Line Tools
Creating a .NET Core application using Visual Studio 2015
Managing source code with GitHub
Using the Team Explorer window
Cloning a GitHub repository
Managing a GitHub repository
Practicing and exploring
Exercise 1.1 – test your knowledge
Exercise 1.2 – practice managing Visual Studio Windows
Exercise 1.3 – practice coding anywhere
Exercise 1.4 – explore topics
Summary
2. Speaking C#
Understanding C# basics
The C# grammar
Statements
Blocks
The C# vocabulary
Writing the code
Verbs are methods
Nouns are types, fields, and variables
Counting types and methods
Declaring variables
Naming variables
Storing text
Storing numbers
Storing whole numbers
Storing real numbers
Sizes of numbers in memory
Comparing double and decimal
Storing Booleans
The object type
The dynamic type
Local variables
Inferring the type of a local variable
Making a value type nullable
Storing multiple values in an array
Building console applications
Displaying output to the user
Getting input from the user
Importing a namespace
Simplifying the usage of the console in C# 6
Reading arguments and working with arrays
Operating on variables
Experimenting with unary operators
Experimenting with arithmetic operators
Comparison and Boolean operators
Practicing and exploring
Exercise 2.1 – test your knowledge
Exercise 2.2 – practice number sizes and ranges
Exercise 2.3 – explore topics
Summary
3. Controlling the Flow, Converting Types, and Handling Exceptions
Selection statements
The if-else statement
The switch-case statement
Autoformatting code
Iteration statements
The while statement
The do-while statement
The for statement
The foreach statement
How does the foreach statement actually work?
Casting and converting between types
Casting from numbers to numbers
Using the Convert type
Rounding numbers
Converting from any type to a string
Parsing from strings to numbers or dates and times
Handling exceptions
The try-catch statement
Catching all exceptions
Catching specific exceptions
The finally statement
Simplifying disposal with the using statement
Checking for overflow
The checked statement
The unchecked statement
Looking for help
MSDN
Getting the definition of code
StackOverflow
Google
Design patterns
Practice and explore
Exercise 3.1 – test your knowledge
Exercise 3.2 – explore loops and overflow
Exercise 3.3 – practice loops and operators
Exercise 3.4 – practice exception handling
Exercise 3.5 – explore topics
Summary
4. Using Common .NET Types
Using assemblies and namespaces
Comparing .NET Framework with .NET Core
Base Class Libraries and CoreFX
Assemblies
Namespaces
Referencing an assembly
Referencing Microsoft Core Library
An example of assembly references
Relating assemblies and namespaces
Importing a namespace
Browsing assemblies and namespaces
Relating C# keywords to .NET types
Storing and manipulating text
Getting the length of a string
Getting the characters of a string
Splitting a string
Extracting part of a string
Checking a string for content
Other string members
Building strings efficiently
Validating input with regular expressions
The syntax of a regular expression
Examples of regular expressions
Storing data with collections
Understanding collections
Lists
Dictionaries
Stacks
Queues
Sets
Working with lists
Working with dictionaries
Sorting collections
Avoiding old collections
Using specialized collections
Practicing and exploring
Exercise 4.1 – test your knowledge
Exercise 4.2 – practice regular expressions
Exercise 4.3 – explore topics
Summary
5. Using Specialized .NET Types
Debugging and diagnostics
Debugging an application
Setting a breakpoint
The debugging toolbar
Debugging windows
Stepping through code
Customizing breakpoints
Monitoring performance and resource usage
Evaluating the efficiency of types
Monitoring performance and memory use
Measuring the efficiency of processing strings
Monitoring with Debug and Trace
Writing to the default trace listener
Configuring trace listeners
Configuring compiler symbols for .NET Framework
Defining compiler symbols for .NET Core
Checking compiler symbols
Switching trace levels
Unit testing an application
Creating a unit of code that needs testing
Creating a unit test project
Running unit tests
Internationalizing an application
Globalizing an application
Localizing an application
Interoperating with unmanaged code
Automating Microsoft Excel using COM Interop
Accessing the Win32 API with P/Invoke
Practicing and exploring
Exercise 5.1 – test your knowledge
Exercise 5.2 – practice using Debug and Trace
Exercise 5.3 – explore topics
Summary
6. Building Your Own Types with Object-Oriented Programming
Talking about OOP
Building class libraries
Creating a class library to share code
Defining a class
Instantiating a class
Storing data with fields
Defining fields
Storing a value using the enum keyword
Storing multiple values using collections
Making a field static
Making a field constant
Making a field read only
Initializing fields with constructors
Writing and calling methods
Overloading methods
Optional parameters and named arguments
Splitting classes using partial
Controlling access with properties and indexers
Defining read-only properties
Defining settable properties
Defining indexers
Simplifying methods with operators
Raising and handling events
Calling methods using delegates
Defining events
Practicing and exploring
Exercise 6.1 – test your knowledge
Exercise 6.2 – practice writing mathematical methods
Exercise 6.3 – explore topics
Summary
7. Implementing Interfaces and Inheriting Classes
Implementing interfaces
Common interfaces
Comparing objects when sorting
Defining a separate comparer
Managing memory with reference and value types
Defining a type using the struct keyword
Releasing unmanaged resources
Ensuring that dispose is called
Inheriting from classes
Extending classes
Hiding members
Overriding members
Preventing inheritance and overriding
Polymorphism
Casting within inheritance hierarchies
Implicit casting
Explicit casting
Handling casting exceptions
Documenting your types
Inheriting and extending .NET types
Inheriting from the Exception class
Extending types when you can't inherit
Using static methods to reuse functionality
Using extension methods to reuse functionality
Practice and explore
Exercise 7.1 – test your knowledge
Exercise 7.2 – practice creating an inheritance hierarchy
Exercise 7.3 – explore topics
Summary
8. Working with Relational Data Using the Entity Framework
Relational Database Management Systems
Connecting to Microsoft SQL Server LocalDb
The Northwind sample database
Choosing a .NET data provider
Using ADO.NET
Connecting to the database
Executing commands and reading result sets
Loading a connection string from configuration
Using Entity Framework 6
Building an Entity Framework 6 model
Entity Framework Code First models
EF Code First conventions
EF annotation attributes
EF Fluent API
Querying an Entity Data Model
Logging SQL statements
Manipulating data with Entity Data Models
Inserting entities
Updating entities
Transactions
Defining an explicit transaction
Loading patterns with EF
Lazy loading entities
Eager loading entities
Explicit loading entities
Using Entity Framework Core
Practicing and exploring
Exercise 8.1 – test your knowledge
Exercise 8.2 – explore the EF Core documentation
Exercise 8.3 – explore topics
Summary
9. Querying and Manipulating Data with LINQ
Writing LINQ queries
Extending sequences with the Enumerable class
Filtering entities with Where
Targeting a named method
Simplifying the code by removing the explicit delegate instantiation
Targeting a lambda expression
Sorting sequences with OrderBy
Sorting by multiple properties with the ThenBy method
Working with sets
Projecting entities with Select statement
Joining and grouping
Sweetening the syntax with syntactic sugar
Using multiple threads with Parallel LINQ
Creating your own LINQ extension methods
Working with LINQ to XML
Generating XML using LINQ to XML
Reading XML by using LINQ to XML
Practicing and exploring
Exercise 9.1 – test your knowledge
Exercise 9.2 – practice querying with LINQ
Exercise 9.3 – explore topics
Summary
10. Working with Files, Streams, and Serialization
Managing the filesystem
Managing directories
Managing files
Managing paths
Getting file information
Reading and writing with streams
Writing to text and XML streams
Compressing streams
Encoding text
Encoding strings as byte arrays
Encoding and decoding text in files
Serializing object graphs
Serializing with XML
Deserializing with XML
Customizing the XML
Serializing with JSON
Serializing with other formats
Serializing with runtime serializers
Practice and explore
Exercise 10.1 – test your knowledge
Exercise 10.2 – practice serializing as XML
Exercise 10.3 – explore serialization formats
Exercise 10.4 – explore Microsoft's System.IO types
Exercise 10.5 – explore topics
Summary
11. 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
Hashing data
Hashing with SHA256
Signing data
Signing with SHA256 and RSA
Authenticating and authorizing users
Managing local accounts
Authenticating with Windows
Authorizing with Windows
Practicing and exploring
Exercise 11.1 – test your knowledge
Exercise 11.2 – practice protecting data with encryption and hashing
Exercise 11.3 – practice protecting data with decryption
Exercise 11.4 – explore topics
Summary
12. Improving Performance and Scalability with Multitasking
Understanding processes and threads
Running tasks asynchronously
Running multiple actions synchronously
Running multiple actions asynchronously using tasks
Waiting for tasks
Continuing with another task
Nested and child tasks
The async and await keywords
Creating a GUI that blocks
Creating a GUI that doesn't block
Other types with Async methods
await in catch blocks
Improving scalability for client-server applications
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
Practicing and exploring
Exercise 12.1 – test your knowledge
Exercise 12.2 – explore topics
Summary
13. Building Universal Windows Platform Apps Using XAML
Understanding the UWP
Adapting your app's layout
Taking advantage of unique device capabilities
Understanding XAML
Simplifying code using XAML
Creating a Windows desktop application using WPF
Choosing common controls
Creating an app for the Universal Windows Platform
Analyzing UWP portability
Using resources and templates

Sharing resources
Replacing a control template
Data binding
Binding to elements
Binding to data
Animating with storyboards
Testing in emulators
Practicing and exploring
Exercise 13.1 – test your knowledge
Exercise 13.2 – practice building a universal tip calculator
Exercise 13.3 – explore topics
Summary
14. Building Web Applications and Services Using ASP.NET Core
Understanding ASP.NET Core
Classic ASP.NET versus modern ASP.NET Core
Client-side web development
Install Web Essentials 2015
The HyperText Transfer Protocol (HTTP)
Create a web application project
Exploring the parts of an ASP.NET Core web application
ASP.NET Core startup
Understanding the default route
ASP.NET Core controllers
Defining the Home controller's actions
ASP.NET Core models
Create Entity models for Northwind
Configure Entity Framework Core as a service
Create view models for requests
Fetch the model in the controller
ASP.NET Core views
Rendering the Home controller's views
Sharing layouts between views
Defining custom styles
Defining a typed view
Taking ASP.NET Core further
Passing parameters using a route value
Passing parameters using a query string
Annotating models
ASP.NET Core Web API
Scaffolding an API controller
Calling a Web API service from a UWP app
Practicing and exploring
Exercise 14.1 – test your knowledge
Exercise 14.2 – practice building a data-driven web application
Exercise 14.3 – explore topics
Summary
15. Taking C# Cross-Platform
Understanding cross-platform development
Visual Studio Code
.NET Core 1.0
ASP.NET Core 1.0
Entity Framework Core 1.0
.NET Native
Xamarin
Cross-device Universal Windows Platform (UWP)
Installing Visual Studio Code and ASP.NET Core
Installing Visual Studio Code
Managing development from the terminal
Installing Homebrew
Installing ASP.NET Core and the .NET Version Manager
Listing the installed versions of .NET
Switching from Mono to .NET Core
Building a console application
Creating the source files
Editing the code
Downloading dependency packages and compiling
Building cross-platform web applications using ASP.NET Core
Creating the simplest ASP.NET Core web application
Installing Yeoman and related tools
Scaffolding projects using Yeoman
Editing projects using Visual Studio Code
Understanding the .NET Core command-line tools
Understanding the DNX tools
Understanding the CLI tools
Common DNX commands
Common CLI commands
Practicing and exploring
Exercise 15.1 – test your knowledge
Exercise 15.2 – practice transferring an existing ASP.NET application
Exercise 15.3 – explore topics
Summary
16. Building a Quiz
Designing the quiz application
Choosing the platform
Deciding the functional requirements
Separating concerns
Building the quiz solution
Defining the entity models
Creating the data repository
Creating the web application
Defining view models
Adding sample quiz questions
Configuring session state
Adding custom controller actions
Adding custom views
Running the quiz
Configuring the project to use Kestrel and .NET Core
Hosting ASP.NET Core web apps in Microsoft Azure
Register an Azure account
Create an Azure web app
Publishing an ASP.NET web application to the Web App
Practicing and exploring
Exercise 16.1 – test your knowledge
Exercise 16.2 – practice by extending the quiz web app
Exercise 16.3 – explore topics
Summary
A. Answers to the Test Your Knowledge Questions
Chapter 1 – Hello, C#! Welcome, .NET Core!
Chapter 2 – Speaking C#
Chapter 3 – Controlling the Flow, Converting Types, and Handling Exceptions
Exercise 3.2
Chapter 4 – Using Common .NET Types
Chapter 5 – Using Specialized .NET Types
Chapter 6 – Building Your Own Types with Object-Oriented Programming
Chapter 7 – Implementing Interfaces and Inheriting Classes
Chapter 8 – Working with Relational Data Using the Entity Framework
Chapter 9 – Querying and Manipulating Data with LINQ
Chapter 10 – Working with Files, Streams, and Serialization
Chapter 11 – Protecting Your Data and Applications
Chapter 12 – Improving Performance and Scalability with Multitasking
Chapter 13 – Building Universal Windows Platform Apps Using XAML
Chapter 14 – Building Web Applications and Services Using ASP.NET Core
Chapter 15 – Taking C# Cross-Platform
Chapter 16 – Building a Quiz
B. Creating a Virtual Machine for Your Development Environment
Signing up for a Microsoft account
Creating a Microsoft Azure subscription
Managing your Microsoft Azure account
Creating a virtual machine
Connecting to your virtual machine using remote desktop
Supporting other platforms
Summary
Index

C# 6 and .NET Core 1.0Modern Cross-Platform Development

C# 6 and .NET Core 1.0

Copyright © 2016 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

Production reference: 1180316

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-569-1

www.packtpub.com

Credits

Author

Mark J. Price

Reviewers

Dustin Heffron

Liviu Ignat

Efraim Kyriakidis

Commissioning Editor

Edward Gordon

Acquisition Editor

Kirk D'Costa

Content Development Editor

Pooja Mhapsekar

Technical Editor

Vivek Pala

Copy Editor

Pranjali Chury

Project Coordinator

Francina Pinto

Proofreader

Safis Editing

Indexer

Tejal Soni

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Author

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

Since 1993, Mark has passed more than 90 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 no experience at all. He successfully guides all of them by combining educational skills with real-world experience, consulting on 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# and .NET while they were still an early alpha version. While with Microsoft, he delivered "train-the-trainer" classes to get other MCTs up to speed in C# and .NET.

In 2010, Mark took a postgraduate certificate in education (PGCE). He taught GCSE and A-level mathematics in two secondary schools in London. Mark holds a Computer Science BSc (Hons) degree from the University of Bristol, UK.

I'd like to thank my parents, Pamela and Ian, for raising me to be polite, hardworking, and curious about the world. I'm grateful to my sisters, Emily and Juliet, for loving me despite being their awkward older brother. I'd also like to express my gratitude to my friends and colleagues who inspire me technically and creatively. Lastly, thanks to all the students I have taught over the years for making me strive to be a better teacher, especially Jared.

About the Reviewers

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 and 7 years of experience working with C# and .NET.

Currently, Dustin works as a software engineer for Johnson Controls Inc. He is also the cofounder and CEO of SunFlake Studios, which was founded in late 2015. He released his first commercial game, Squash Master, in early 2016 and is planning to develop additional games in the coming months and years.

Dustin has a long history of reviewing for Packt Publishing, including the book XNA 4.0 Game Development by Example: Beginner's Guide and the video tutorial series XNA 3D Programming by Example. He also coauthored the video tutorial series XNA 3D Toolkit with Larry Louisiana.

Liviu Ignat is a full-stack developer and architect, technology geek, and entrepreneur, who has been writing commercial software since 2004. He started with VB6, soon moved to .NET Java, and then continued by moving to front-end web development. He has fun with everything that is a functional language, such as F#, Scala, Swift, JavaScript, and so on.

Currently, he is a senior software engineer at AppDirect (http://appdirect.com), Munich, and he is also the CTO of his own startup (http://giftdoodle.com). He has been involved in building distributed backend services, mostly with .NET and complex single-page web apps. He is a big fan of microservices with C#, NodeJS, Scala, and Docker, single-page apps, and native apps with Android and IOS.

When he is not coding, Liviu loves snowboarding during the winter, sailing to exotic places during the summer, or just traveling the world. You can find and contact him at http://ignat.email/.

Efraim Kyriakidis is a skilled software engineer with over 10 years of experience in developing and delivering software solutions for diverse customers and projects. He's well-versed in all stages of the software development lifecycle. 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 up and received his diploma as Electro technic engineer from Aristotle University Thessaloniki in Greece. Through out his career he has 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.

www.PacktPub.com

eBooks, discount offers, and more

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://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

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

Preface

There are many C# books, some, more than a thousand 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# and .NET proven practices.

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

At the end of each chapter, there is a section entitled Practicing and Exploring, which contains questions to test your knowledge, and usually a hands-on practical exercise, and you will explore topics in depth on your own with a little nudge in the right direction from me.

You can download solutions for the exercises from the GitHub repository at https://github.com/markjprice/cs6dotnetcore. I will provide instructions on how to do this using Visual Studio 2015 at the end of Chapter 1, Hello C#!, Welcome .NET Core!.

What this book covers

Chapter 1, Hello C#!, Welcome .NET Core!, is about setting up your development environment and using various tools to create the simplest application possible with C#. You will learn how to compile C# code at the Command Prompt and how to write and compile code using Visual Studio. You will also learn about the different .NET platforms: .NET Framework, .NET Core, 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 the Flow, Converting Types, and Handling Exceptions, is about writing code that makes decisions, repeats blocks of statements, converts between types, and handles errors. You will also learn the best places to look for help.

Chapter 4, Using Common .NET Types, is about how .NET types are related to C#. You will learn about .NET Framework, .NET Core, and their class library assemblies of types that allow your applications to connect together existing components to perform common practical tasks.

Chapter 5, Using Specialized .NET Types, is about .NET types used to diagnose problems, support multiple languages and cultures, and access features and applications outside of .NET.

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 for storing data and methods for performing actions. You will use OOP concepts such as aggregation and encapsulation.

Chapter 7, Implementing Interfaces and Inheriting Classes, is about deriving new types from existing ones using OOP. You will learn how to implement interfaces, about base and derived classes, how to override a type member, how to use polymorphism, and how to cast between classes in an inheritance hierarchy.

Chapter 8, Working with Relational Data Using the Entity Framework, is about reading and writing to Microsoft SQL Server (and other databases) using classic ADO.NET and the object-relational mapping technology known as Entity Framework.

Chapter 9, Querying and Manipulating Data with LINQ, is about Language Integrated Queries (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 reading and writing to files and streams, text encoding, and serialization.

Chapter 11, Protecting Your Data and Applications, is about protecting your data using encryption and hashing, and checking who is running your application and what they are allowed to do.

Chapter 12, Improving Performance and Scalability with Multitasking, is about allowing multiple actions to be executed 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, which 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 and Services Using ASP.NET Core, is about building web applications and services using a modern HTTP architecture on the server side using Microsoft ASP.NET Core 1.0. You will learn about the models, views, and controllers that make up MVC and the Web API.

Chapter 15, Taking C# Cross-Platform, is about introducing you to how you can take C# cross-platform using .NET Core, ASP.NET Core 1.0, Entity Framework Core 1.0, and Visual Studio Code.

Chapter 16, Building a Quiz, is about designing and building a quiz application that helps students learn C#, .NET Core, and related topics.

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

Appendix B, Creating a Virtual Machine for Your Development Environment, shows how to set up a virtual machine in Microsoft Azure for use as a development environment.

What you need for this book

Although you can develop and deploy C# on many platforms, including Mac OS X and Linux, for the best learning experience, you need two pieces of software:

Microsoft Windows 10Microsoft Visual Studio Community 2015 with Update 1 (or later)

The best version of Windows to use is Microsoft Windows 10 because you 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 don't have a Windows computer, then you can use a virtual machine running Windows in the cloud. Refer to Appendix B, Creating a Virtual Machine for Your Development Environment for instructions.

The best version of Visual Studio to use is Microsoft Visual Studio Community 2015 with Update 1 (or later), which is the version I used while writing this book. In Chapter 15, Taking C# Cross-Platform, I will introduce you to Visual Studio Code, which runs on Windows, Linux, and Mac OS X, and can create cross-platform applications for all these OSes.

Who this book is for

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

Reader feedback

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

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

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

Customer support

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

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

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

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

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

Errata

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

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

Piracy

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

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

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

Questions

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

Chapter 1. Hello, C#! Welcome, .NET Core!

This chapter is about setting up your development environment, understanding the similarities and differences between .NET Core, .NET Framework, and .NET Native, and using various tools to create the simplest application possible with C#.

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 1.0 during its rocky birth in the early months of 2016.

This chapter covers the following topics:

Setting up your development environmentUnderstanding the .NET Framework, .NET Core, and .NET NativeWriting and compiling code by using the Developer Command PromptWriting and compiling code by using Microsoft Visual Studio 2015Targeting the .NET CoreManaging source code with GitHub

Setting up your development environment

Before you start programming, you will need to set up your Interactive Development Environment (IDE) that includes a code editor for C#. The best IDE to choose is Microsoft Visual Studio 2015, but it only runs on the Windows operating system.

Using alternative C# IDEs

There are alternative IDEs for C#, for example, MonoDevelop, JetBrainsProject Rider, and Microsoft Visual Studio Code. They each have versions available for Windows, Linux, and Mac OS X, allowing you to write code on one operating system and deploy to the same, or a different, one:

For MonoDevelop IDE, visit http://www.monodevelop.com/For JetBrains Project Rider, visit http://blog.jetbrains.com/dotnet/2016/01/13/project-rider-a-csharp-ide/For Microsoft Visual Studio Code, visit https://code.visualstudio.com/

Cloud9 is a web browser-based IDE, so it's even more cross-platform than the others. here is the link:

https://c9.io/web/sign-up/free

In Chapter 15, Taking C# Cross-Platform, I will show you how to use Visual Studio Code running on Mac OS X to create an ASP.NET Core 1.0 web application that can be deployed to Windows, Mac OS X, or Linux operating systems, or to Docker containers.

Tip

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

Using Visual Studio 2015 on Windows 10

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

Tip

If you don't have Windows, I recommend that you create a virtual machine (VM) to use for development. You can choose any cloud provider, but Microsoft Azure has preconfigured VMs that include properly licensed Windows and Visual Studio 2015. You only pay for the minutes your VM is running, so it is a way for users of Linux, Mac OS X, and older Windows versions to have all the benefits of using Visual Studio 2015. Refer to Appendix B, Creating a Virtual Machine for Your Development Environment for more information.

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

Tip

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.

Installing Microsoft Visual Studio 2015

Download and install Microsoft Visual Studio Community 2015 with Update 1 or higher.

Choosing the default installation

If you prefer a smaller, faster installation then choose Default because it only requires 8 GB and should complete the installation in about an hour. With this choice, as shown in the following screenshot, you will be able to complete the first two-thirds of this book. To complete the rest of the book, you can later add additional features, such as support for building Universal Windows Platform (UWP) apps, via Programs and Features in the Control Panel:

If you chose Default, then skip to the Completing the Installation section.

Choosing the custom installation

If you have 34 GB of free disk space and can wait for several hours, then in the installation dialog, choose Custom, and then click on Next. Select the following features:

Under Windows and Web Development, tick the following checkboxes:
Microsoft SQL Server Data ToolsMicrosoft Web Developer ToolsUniversal Windows App Development Tools
Under Cross Platform Mobile Development, tick the following checkbox:
C#/.NET (Xamarin)
Under Common Tools, tick the following checkboxes:
Git for WindowsGitHub Extension for Visual Studio

Click on Next:

Note

If you have the Home edition of Windows 10, then you will not be able to install emulators for Windows Phone because they require Hyper-V support.

Tip

You can choose to install everything if you want support for languages such as C++, Python, and F#, but these will not be covered in this book.

Completing the installation

On the license terms dialog, click on Install. Wait for the files to download and install.

Tip

While you wait for Visual Studio to install, you can jump to the Understanding .NET Framework, .NET Core, and .NET Native section in this chapter.

Signing in to Visual Studio

The first time that you run Visual Studio, you will be prompted to sign in:

If you have a Microsoft account, for example, a Hotmail, MSN, Live, or Outlook e-mail address, you can use that account. If you don't, then register for a new one at the following link:

https://signup.live.com/

Choosing development settings

After signing in, you will be prompted to choose Development Settings. Choose Visual C# to configure keyboard shortcuts and a default window layout that works best for C# programmers, as shown in the following screenshot:

After you click on Start Visual Studio, you will see the 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 window that will list all of your open projects, as shown in the following screenshot:

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

Updating extensions and products

In the top-right corner of Visual Studio, you will see a flag that has a number next to it. These are notifications of extensions and product updates.

Click on the flag to display the Notifications window, as shown in the following screenshot:

In the Notifications window, click on each entry to install the update. You can install these updates at a later time if you prefer, but it is best to keep your software up-to-date to avoid bugs and security holes. The following screenshot shows an extension downloading and installing:

Using older versions of Visual Studio

If you want to use a free version of Visual Studio older than 2015, then you can use one of the more limited Express editions. A lot of the code in this book will work with older versions if you bear in mind when the following features were introduced:

Year

C#

Features

2005

2

Generics with <T>

2008

3

Lambda expressions with => and manipulating sequences with LINQ (from, in, where, orderby, ascending, descending, select, group, into)

2010

4

Dynamic typing with dynamic and multithreading with Task

2012

5

Simplifying multithreading with async and await

2015

6

string interpolation with $"", importing static types with using static, and other refinements.

Understanding .NET Framework, .NET Core, and .NET Native

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

Understanding .NET Framework platform

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

Microsoft designed the .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, the .NET Framework is Windows-only.

Understanding the Mono project

The open source community developed a cross-platform .NET implementation named the Mono project (http://www.mono-project.com/).

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

Understanding the .NET Core platform

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

Streamlining .NET

.NET Core 1.0 is much smaller than the current version of the .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 the .NET Core. The latest technology for building Windows apps is the Universal Windows Platform (UWP). 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 applications and service technologies that fewer developers choose to use today, so they have also been removed from the .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 the .NET Core, named ASP.NET Core 1.0. You will learn about it in Chapter 14, Building Web Applications and Services Using ASP.NET Core.

The Entity Framework (EF) 6.x is an object-relational mapping technology for working 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 1.0. You will learn about it in Chapter 8, Working with Relational Data Using the Entity Framework.

Some data types in .NET that are included with both the .NET Framework and the .NET Core have been simplified by removing some members. For example, in the .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.

Tip

The .NET Framework 4.6 is about 200 MB. The .NET Core 1.0 is about 11 MB. Eventually, the .NET Core may grow to a similar larger size. Microsoft's goal is not to make the .NET Core smaller than the .NET Framework. The goal is to componentize .NET Core to support modern technologies and to have fewer dependencies so that deployment requires only those components that your application really needs.

The future of .NET

The .NET Core is the future of .NET, but in my opinion, we are not there yet. .NET Core 1.0 is a great start, but it will take another version or two to become as mature as the current version of the .NET Framework.

This book will focus features available in .NET Core, but will use the .NET Framework when features have not (yet) been implemented in the .NET Core.

Tip

One of the reasons we picked this cover image for this book is that you can think of .NET Core as a new dawn for .NET. The .NET Framework has become overgrown, like a dense forest, and the .NET Core is like finding a clearing or glade within it. It's a fresh start.

Understanding the .NET Native platform

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

The .NET Native compiler improves execution speed and reduces the memory footprint for applications. It supports the following:

UWP apps for Windows 10, Windows 10 Mobile, Xbox One, HoloLens, and Internet of Things (IoT) devices such as Raspberry PiServer-side web development with ASP.NET Core 1.0Console applications for use on the command line

Comparing .NET technologies

The following table summarizes and compares Microsoft's three .NET technologies:

Platform

Feature set

C# compiles to

Host OSes

.NET Framework

Mature and extensive

Intermediate Language (IL) code

Windows only

.NET Core

Brand-new and somewhat limited

Windows, Linux, Mac OS X, Docker

.NET Native

Brand-new and very limited

Native code

Writing and compiling code using the Developer Command Prompt

When you install Visual Studio, other tools are installed too. One of those tools is the Developer Command Prompt for VS2015that has its path set to find developer tools such as the C# compiler.

Writing code using Notepad

Start Notepad (or your favorite text editor) and enter the following code:

class Program { static void Main() { System.Console. WriteLine("Hello C#!"); } }

You can type the code all on one line or spread it out over multiple lines and indent your lines to make it easier to read.

Note

C# is case sensitive, meaning that you must type uppercase and lowercase characters exactly as shown in the preceding code. C# is not whitespace sensitive, meaning that it does not care if you use tabs and spaces and carriage-returns to lay out your code however you like.

From the File menu, choose Save As.

In the dialog box, change to drive C: (or any drive that you want to use to save your projects), click on the New Folder button, and name the folder Code.

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 myfirstapp.cs, as shown in the following screenshot:

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

Compiling code using the Developer Command Prompt

Start the Developer Command Prompt for VS2015 by typing the letters deve in the Windows 10 Search box, as you can see in the following screenshot. You will also find it on the Start Menu or Start Screen listed in All apps in the Visual Studio 2015 folder:

At the Command Prompt, enter the commands to do the following:

Change to the C:\Code folderCompile the source code using the C# compilerRequest a directory listingRun the application by entering the name of the EXE

Here are the commands:

cd C:\Codecsc myfirstapp.csdirmyfirstapp

The output in the Command Prompt window should look like this:

Note that your source code, the file named myfirstapp.cs, has been compiled into an assembly named myfirstapp.exe. When you enter the name of the assembly, it is loaded and executed by .NET Framework 4.6 and its CLR.

You can copy the myfirstapp.exe file onto any computer with Windows 10 and it will run correctly because all copies of Windows 10 have .NET Framework 4.6 installed. Actually, you can copy the file onto a computer with an older version of Windows as long as it has .NET Framework 4.0 or later installed.

Fixing compiler errors

If the compiler displays errors, read them carefully, and fix them in Notepad. Save your changes and recompile.

Tip

At the Command Prompt, you can press the up and down arrows on your keyboard to cycle through previous commands you have entered.

A typical error might be using the wrong case, a missing semi-colon at the end of a line, or a mismatched pair of curly braces. For example, if you had mistyped a lowercase m for the Main method you would see this error message:

error CS5001: Program does not contain a static 'Main' method suitable for an entry point

Decompiling code using ILDASM

The C# compiler converts your source code into Intermediate Language (IL) code and stores the IL in an assembly (a DLL or EXE file).

IL code statements are like assembly language instructions, but they are executed by the .NET virtual machine known as theCommon Language Runtime (CLR).

At runtime, the CLR loads the IL code from the assembly, JIT compiles it into native CPU instructions, and then it is executed by the CPU on your machine.

The benefit of this two-step compilation process is that Microsoft can create CLRs for Linux and Mac OS X as well as for Windows. The same IL code runs everywhere because of the second compilation process that generates code for the native operating system and CPU instruction set.

Regardless of which language the source is written in, all .NET applications use IL code for their instructions, stored in an assembly. Microsoft provides a tool that can open an assembly and reveal this IL code.

Tip

Actually, not all .NET applications use IL code! Some use the new .NET Native compiler to generate native code instead of IL code, improving performance and reducing memory footprint, but at the cost of portability.

Disassembling compiled assemblies

Disassembling a compiled assembly is an advanced technique. I will walk you through the process, but do not worry about fully understanding what you are seeing yet!

Start the IL Disassembler by entering the following at the Developer Command Prompt:

ildasm myfirstapp.exe

You will see the IL DASM tool with the compiled EXE assembly loaded:

Double-click on MANIFEST in the tree view to show the metadata version (4.0.30319) of .NET and the Microsoft Core Library (mscorlib) assembly version (4.0.0.0) that this assembly needs to run. The following screenshot tells us that to run this assembly, we would need .NET Framework 4.0 or later installed:

Close the MANIFEST window, expand Program, and then double-click on the Main method. Note the IL instructions: ldstr (load string), nop (no operation), and ret (return). Remember that IL is an assembly language that is executed by the .NET CLR:

Anyone can use this tool to see any .NET assembly's IL code. Don't panic! This is not a reason to avoid C#.

All applications are lists of instructions that must be visible to the machine that runs it. If the machine can read these instructions, so can anything else. Therefore, all software can be reverse-engineered. It's just a matter of the effort required. .NET just happens to make it very easy!

Tip

ILSpy is a popular open source tool that does everything IL DASM does and can also reverse-engineer the IL code into C# or Visual Basic .NET source code. I used this tool for a client who had lost the source code for an assembly and needed to recover it!

Targeting the .NET Core

For 15 years, .NET programmers have been targeting the .NET Framework, so there are many projects that may need to move from Windows-only to cross-platform by retargeting to the .NET Core.

Understanding the .NET Portability Analyzer

To ensure