Читать книгу Professional C# 6 and .NET Core 1.0 - Christian Nagel - Страница 8
Introduction
ОглавлениеIF YOU WERE TO DESCRIBE THE C# LANGUAGE and .NET as the most significant technology for developers available, you would not be exaggerating.NET is designed to provide an environment within which you can develop almost any application to run on Windows. Runs on Windows– wait, I would have said that with previous versions of the .NET Framework. The new version,NET Core 1.0 not only runs on Windows, but it also runs on Linux and Mac systems. The C# programming language is designed specifically to work with .NET. By using C#, you can, for example, write a web page, a Windows Presentation Foundation (WPF) application, a REST web service, a component of a distributed application, a database access component, a classic Windows desktop application, or even a Universal Windows Platform (UWP) app that enables online and offline capabilities. This book covers .NET Core 1.0 and also the full .NET Framework stack,NET Framework 4.6. If you code using any of the prior versions, there may be sections of the book that will not work for you.
Where possible, samples of this book make use of .NET Core 1.0. The book code is built on a Windows system, but you can run the samples on other platforms as well; small changes might be needed to run them on Linux. Read Chapter 1, “.NET Application Architectures,” to see how to build the applications for the Linux platform. What’s not possible to run on Linux? WPF applications still need the full .NET Framework and run only on Windows. UWP apps are using .NET Core, but also require the Windows Runtime. These apps require Windows as well. These UI technologies are covered in Part III of the book, “Core Apps.”
So what’s the big deal about .NET and C#?
The Significance of .NET Core
To understand the significance of .NET Core, you must consider the long-lived .NET Framework. The .NET Framework 1.0 was released in the year 2002. Since then about every two years a new major release has been made available. With Visual Studio 2013 we had C# 5 and .NET 4.5. The .NET Framework 4.5 is huge, with more than 20,000 classes.
NOTE Get into more details of the releases of the .NET Framework and C# in Chapter 1.
What are the problems with this huge framework? How is this solved with .NET Core?
For new developers, getting into this huge framework is not easy. Many things exist that are important for legacy applications, but they’re not really important for new applications. For experienced developers it’s not that easy to decide between these technologies to select the best one. You have to decide between ASP.NET Web Forms and ASP.NET MVC for web applications, decide between Windows Forms and WPF or the Universal Windows Platform for client applications, decide between the Entity Framework and LINQ to SQL for data access, decide between ArrayList and List<T> for storing collections… For some experienced developers the choice is obvious; for most it’s not that easy. It’s even more difficult for developers just starting with .NET.
.NET Core is based on smaller units, small NuGet packages. The Console class is only needed with console applications. With the .NET Framework, the Console class is available with mscorlib, an assembly that’s referenced by every .NET application. Using .NET Core, you have to explicitly decide to use the System.Console NuGet package. Otherwise, the Console class is not available.
Smaller packages also allow you to get rid of parts of the framework more easily. In case you need older collection classes for legacy applications, they are available with the NuGet package System.Collections.NonGeneric. With new applications you can define a list of packages that can be used, and System.Collections.NonGeneric can be excluded from this list.
Nowadays, development is going a lot faster. With many products, customers receive ongoing updates of products instead of receiving new versions every 2 years. Even Windows, with Windows 10, is on this fast pace. Customers receive smaller features with each update, but they receive them at a faster pace. Having 2-year release cycles with the .NET Framework nowadays is not fast enough. Some technologies, like the Entity Framework, already circumvented the problem by offering new features via NuGet packages that can be released independently of the .NET Framework.
Updating smaller pieces allows for faster innovation.NET Core, which is based on many small NuGet packages, can be changed more easily.NET Core and ASP.NET are now open source. You can find the source code for .NET Core at http://www.github.com/dotnet and for ASP.NET at http://www.github.com/aspnet.
When .NET was released, Windows had a big market share both on the client and on the server. Now the world is more fragmented. Companies decided against running server-side code with ASP.NET because it didn’t run on Linux. ASP.NET Core 1.0 with .NET Core can run on Linux.
.NET Core is platform-independent and supports Windows, Linux, and Mac systems. For client applications, you can use .NET with Xamarin on iPhone and Android.
The .NET Framework required having the same version of the .NET runtime that was used during development to be installed on the target system. Many application developments have been restricted by the version of the .NET Framework to use based on client needs. This is not only an issue for client-based application development but also for the server. I had to switch back to older .NET runtime versions because my provider didn’t support the newest one. With .NET Core, the runtime is delivered with the application.
When ASP.NET was built, compatibility with the predecessor technology Active Server Pages (ASP) that was built with JavaScript or VBScript code running on the server was an important aspect. Nowadays this is not needed anymore. ASP.NET Web Forms was built with the idea that the developer doesn’t need to know anything about JavaScript and HTML, and everything could be done with server-side code. Now, because of the huge number of JavaScript frameworks and enhancements in HTML, more control on JavaScript and HTML is needed.
With the new version of ASP.NET, performance has a big role in the framework architecture. You only have performance impacts for the things you really need. In case you don’t have static files with your web application, you have to explicitly decide on using it, otherwise you don’t pay a performance impact for this. With fine-grained control you can decide what features you need.
To get an even bigger performance improvement,NET Core can be built to native code. This is possible not only on Windows but also on Linux and Mac systems. With this you can get performance improvement especially on program startup, and you use less memory.
Now there’s an issue with legacy applications. Most applications can’t switch that easily to .NET Core. The full .NET Framework – running just on Windows – is evolving as well. It’s not evolving in such big steps as .NET Core, but it is a mature framework. At the time of this writing,NET 4.6.1 is released, with small updates compared to the previous versions. Applications that have been written with Windows Forms or ASP.NET Web Forms still need to use the full framework, but they can take advantage of the enhancements of .NET 4.6.1. Using .NET 4.6.1, you can also use NuGet packages built for .NET Core. Many new NuGet packages are built in a portable manner. With ASP.NET MVC 5 web applications you can also decide to change to ASP.NET MVC 6 running on ASP.NET Core 1.0. ASP.NET Core 1.0 allows using either .NET Core or .NET 4.6. This can make the switch easier. However, for running ASP.NET MVC on Linux, you need to migrate the ASP.NET MVC application to use .NET Core, but running on Linux wasn’t available previously as well.
Here’s a summary of some of the features of .NET Core:
• .NET Core is open source.
• Smaller NuGet packages allow for faster innovation.
• .NET Core supports multiple platforms.
• .NET Core can compile to native code.
• ASP.NET can run on Windows and Linux.
• Existing applications still run and can evolve into the future.
As you can see with the features of .NET Core, this technology made the biggest change for .NET in the history since the first version of .NET. This is a new start. From here we can continue our journey on new developments in a fast pace.
The Significance of C#
When C# was released in the year 2002, it was a language developed for the .NET Framework. C# was designed with ideas from C++, Java, and Pascal. Anders Hejlsberg had come to Microsoft from Borland and brought experience with language development of Delphi. At Microsoft, Hejlsberg worked on Microsoft’s version of Java, named J++, before creating C#.
C# started not only as an object-oriented general purpose programming language but was a component-based programming language that supported properties, events, attributes (annotations), and building assemblies (binaries including metadata).
Over time, C# was enhanced with generics, Language Integrated Query (LINQ), lambda expressions, dynamic features, and easier asynchronous programming. C# is not an easy programming language because of the many features it offers, but it’s continuously evolving with features that are practical to use. With this, C# is more than an object-oriented or component-based language; it also includes ideas of functional programming – things that are of practical use for a general-purpose language developing all kind of applications.
What’s New in C# 6
With C# 6 a new C# compiler is available. It’s not only that a source code cleanup was done; the features of the compiler pipeline can now be used from custom programs, and are used by many features of Visual Studio.
This new compiler platform made it possible to enhance C# with many new features. Although there’s not a feature with such an impact as LINQ or the async keyword, the many enhancements increase developer productivity. What are the changes of C# 6?
static using
The static using declaration allows invoking static methods without the class name:
In C# 5
In C# 6
The using static keyword is covered in Chapter 2, “Core C#.”
Expression-Bodied Methods
With expression-bodied methods, a method that includes just one statement can be written with the lambda syntax:
In C# 5
In C# 6
Expression-bodied methods are covered in Chapter 3, “Objects and Types.”
Expression-Bodied Properties
Similar to expression-bodied methods, one-line properties with only a get accessor can be written with the lambda syntax:
In C# 5
In C# 6
Expression-bodied properties are covered in Chapter 3.
Auto-Implemented Property Intializers
Auto-implemented properties can be initialized with a property initializer:
In C# 5
In C# 6
Auto-implemented property initializers are covered in Chapter 3.
Read-Only Auto Properties
To implement read-only properties, C# 5 requires the full property syntax. With C# 6, you can do this using auto-implemented properties:
In C# 5
In C# 6
Read-only auto properties are covered in Chapter 3.
nameof Operator
With the new nameof operator, names of fields, properties, methods, or types can be accessed. With this, name changes are not missed with refactoring:
In C# 5
In C# 6
The nameof operator is covered in Chapter 8, “Operators and Casts.”
Null Propagation Operator
The null propagation operator simplifies null checks:
In C# 5
In C# 6
The new syntax also has an advantage for firing events:
In C# 5
In C# 6
The null propagation operator is covered in Chapter 8.
String Interpolation
The string interpolation removes calls to string.Format. Instead of using numbered format placeholders in the string, the placeholders can include expressions:
In C# 5
In C# 6
The C# 6 sample is reduced that much compared to the C# 5 syntax because it uses not only string interpolation but also an expression-bodied method.
String interpolation can also use string formats and get special features on assigning it to a FormattableString. String interpolation is covered in Chapter 10, “Strings and Regular Expressions.”
Dictionary Initializers
Dictionaries can now be initialized with a dictionary initializer – similar to the collection initializer.
In C# 5
In C# 6
Dictionary initializers are covered in Chapter 11, “Collections.”
Exception Filters
Exception filters allow you to filter exceptions before catching them.
In C# 5
In C# 6
A big advantage of the new syntax is not only that it reduces the code length but also that the stack trace is not changed – which happens with the C# 5 variant. Exception filters are covered in Chapter 14, “Errors and Exceptions.”
Await in Catch
await can now be used in the catch clause. C# 5 required a workaround.
In C# 5
In C# 6
This feature doesn’t need an enhancement of the C# syntax; it’s functionality that’s working now. This enhancement required a lot of investment from Microsoft to make it work, but that really doesn’t matter to you using this platform. For you, it means less code is needed – just compare the two versions.
NOTE The new C# 6 language features are covered in the mentioned chapters, and in all chapters of this book the new C# syntax is used.
What’s New with the Universal Windows Platform
Windows 8 introduced a new programming API, the Windows Runtime. Applications using the Windows Runtime could be made available via the Microsoft Store and were known with many different names. It started with Metro apps or Metro style apps, and they are also known as Modern apps, Windows Store apps (although they can also be installed with PowerShell scripts without using the store), and Universal apps. Probably there are some names I missed. Nowadays, these are just Windows apps, running on the Universal Windows Platform (UWP).
The idea of these apps was to allow end users to find them easily via the Microsoft store and to offer a touch-friendly environment, a modern user interface that looks nice and smooth and allows fluid interactions, and apps that can be trusted. More than that, the users who already know the Windows user interfaces should be attracted to using the new environment.
The first version of the design guidelines was very restrictive and had some flaws. How can I search for stuff in the app? Many users didn’t find the charms bar on the right side, and found out it allowed searching in many apps. Windows 8.1 moved the search to a search box directly on the desktop. Also, users often didn’t find the app bar located at the top or bottom if they didn’t perform a touch gesture from top to bottom or bottom to top.
Windows 10 made the design much more open. You can use the things that are useful for your apps and can decide on the user interface as it best matches your users and apps. Of course, it’s still best to create a nice looking, smooth, and fluid design. It’s better for having users happily interacting with the app, and they should not have a hard time finding out how things can be done.
The new Windows Runtime, Windows Runtime 3.0, steps on the predecessor versions to define an XAML user interface, implements an application lifecycle, and allows background functionality, sharing of data between applications, and more. Indeed, the new version of the runtime offers more features in all the areas.
Windows apps now make use of .NET Core. You can use the same .NET libraries available via NuGet packages with Windows apps. Finally, native code gets compiled for a faster app startup and less memory consumption.
What might be even more important than the additional features offered is the universality that’s now available. The first update of Visual Studio 2013 included a new project type for Windows 8 apps: Universal apps. Here, Universal apps have been done with three projects: one project for the Windows app, one project for the Windows phone app, and a shared code project. It was possible to even share XAML code between these platforms. The new Universal project template consists of one project. You can use the same binary not only for Windows and Windows Phone, but also for the Xbox, Internet of Things (IoT) devices, the HoloLens, and more. Of course, these different platforms offer features that are not available everywhere, but using this differing feature you can still create one binary image that runs on every Windows 10 device.
What You Need to Write and Run C# Code
.NET Core runs on Windows, Linux, and Mac operating systems. You can create and build your programs on any of these operating systems using Visual Studio Code (https://code.visualstudio.com). The best developer tool to use, and the tool used with this book, is Visual Studio 2015. You can use Visual Studio Community 2015 edition (https://www.visualstudio.com), but some features shown are available only with the Enterprise edition of Visual Studio. It will be mentioned where the Enterprise edition is needed. Visual Studio 2015 requires the Windows operating system. Windows 8.1 or later is required.
To build and run WPF applications shown in this book, you need a Windows platform. Running WPF applications is still supported on Windows 7.
For building Universal Windows apps, you can use Windows 8.1 with Visual Studio, but for testing and running these apps, you need a Windows 10 device.
What This Book Covers
This book starts by reviewing the overall architecture of .NET in Chapter 1 to give you the background you need to write managed code. You’ll get an overview about the different application types and learn how to compile with the new development environment CLI. After that, the book is divided into a number of sections that cover both the C# language and its application in a variety of areas.
Part I: The C# Language
This section gives a good grounding in the C# language. This section doesn’t presume knowledge of any particular language, although it does assume you are an experienced programmer. You start by looking at C#’s basic syntax and data types and then explore the object-oriented features of C# before looking at more advanced C# programming topics like delegates, lambda expressions, Language Integrated Query (LINQ), reflection, and asynchronous programming.
Part II: .NET Core and Windows Runtime
This section starts with tools, and it looks at the main integrated development environment (IDE) utilized by C# developers worldwide: Visual Studio 2015. You’ll learn about the tools available with the Enterprise edition of Visual Studio in Chapter 17, “Visual Studio 2015.”
You also learn what’s behind the C# compiler and how you can use the .NET Compiler Platform to change your code programmatically in Chapter 18, “.NET Compiler Platform.”
When you’re creating functionality with C# code, don’t skip the step of creating unit tests. It takes more time in the beginning, but over time you’ll see advantages when you add functionality and maintain code. Chapter 19, “Testing,” covers creating unit tests, web tests, and coded UI tests.
Chapters 20 to 28 cover topics from .NET Core and the Windows Runtime that are independent of application types. In Chapter 20, “Diagnostics and Application Insights,” you’ll learn writing diagnostic information from the application that can also be used in the production environment. Chapters 21, “Tasks and Parallel Programming,” and 22, “Task Synchronization,” cover parallel programming using the Task Parallel Library (TPL) as well as various objects for synchronization. In Chapter 23, “Files and Streams,” you’ll read about accessing the file system and reading files and directories. Using streams, you’ll learn using both streams from the System.IO namespace and streams from the Windows Runtime for programming Windows apps. Chapter 24, “Security,” makes use of streams when you learn about security and how to encrypt data and allow for secure conversion. You’ll also learn the core foundation of networking using sockets, as well as using higher-level abstractions like the HttpClient (Chapter 25, “Networking”). Chapter 26, “Composition,” covers Microsoft Composition that allows creating independence between containers and parts. In Chapter 27, “XML and JSON,” you learn about serializing objects into XML and JSON, as well as different techniques for reading and writing XML. Finally, in Chapter 28, “Localization,” you learn to localize applications using techniques for localizations that are important both for Windows and web applications.
Part III: Windows Apps
This section is about building applications with XAML – both Universal Windows apps and WPF. You’ll learn about the foundation of XAML in Chapter 29, “Core XAML,” with the XAML syntax, dependency properties, and also markup extensions where you can create your own XAML syntax. In Chapter 30, “XAML Styles and Resources,” you learn about styling your XAML-based apps. A big focus on the MVVM (model-view-view model) pattern is in Chapter 31, “Patterns with XAML Apps.” Here you learn to take advantage of the data-binding features of XAML-based applications, which allow sharing a lot of code between UWP apps and WPF applications. You can also share a lot of code for developing for the iPhone and Android platforms using Xamarin. However, developing with Xamarin is not covered in this book. After the introductory chapters covering both UWP apps and WPF applications, two chapters cover the specific features of UWP apps, and two chapters cover WPF applications. In Chapters 32, “Windows Apps: User Interfaces,” and 33, “Advanced Windows Apps,” you learn about specific XAML controls with UWP apps such as the RelativePanel and AdaptiveTrigger, the new compiled binding, and the application life cycle, sharing data, and creating background tasks. Chapters 34, “Windows Desktop Applications with WPF,” and 35, “Creating Documents with WPF,” go into WPF-specific features such as the Ribbon control, TreeView to show hierarchical data, WPF-specific data binding features, creating flow and fixed documents, and creating XML Paper Specification (XPS) files.
This section is concluded with deployment in Chapter 36 to deploy WPF applications using ClickOnce, and information to get UWP apps in the store.
Part IV: Web Applications and Services
In this section you look at web applications and services. You’ll find two chapters about ADO.NET in this section as well. Although you can use ADO.NET (Chapter 37, “ADO.NET”) and the Entity Framework (Chapter 38, “Entity Framework Core”) from client applications as well, typically these technologies are used on the server, and you invoke services from the client.
In Chapter 39, “Windows Services,” you can read how to create your own Windows services that run when the operating system is started.
The new version of ASP.NET, ASP.NET Core 1.0, is covered in Chapter 40. Here you can read the foundation of ASP.NET and get ideas on how ASP.NET MVC 6 is built using these foundations. The features of ASP.NET MVC 6 are covered in Chapter 41.
NOTE ASP.NET Web Forms are not covered in this book, although ASP.NET 4.6 offers new features for ASP.NET Web Forms. This book fully concentrates on the new version of ASP.NET technologies using ASP.NET Core 1.0. For information about ASP.NET Web Forms and ASP.NET MVC 5 you should read Professional C# 5 and .NET 4.5.1.
Chapter 42 covers the REST service features of ASP.NET MVC 6: ASP.NET Web API. Publish and subscribe technologies for web applications, in the form of using the ASP.NET technologies WebHooks and SignalR, are covered in Chapter 43. Chapter 44 discusses an older technology for communication with services using SOAP and WCF.
Again, like the previous section, this section concludes with deployment – deployment of websites running on Internet Information Server (IIS) or using Microsoft Azure to host websites.
Conventions
To help you get the most from the text and keep track of what’s happening, a number of conventions are used throughout the book.
WARNINGS Warnings hold important, not-to-be-forgotten information that is directly relevant to the surrounding text.
NOTE Notes indicate notes, tips, hints, tricks, and/or asides to the current discussion.
As for styles in the text:
• We highlight new terms and important words when we introduce them.
• We show keyboard strokes like this: Ctrl+A.
• We show filenames, URLs, and code within the text like so: persistence.properties.
• We present code in two different ways:
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All the source code used in this book is available for download at www.wrox.com/go/professionalcsharp6. When at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.
NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-1-119-09660-3.
After you download the code, just decompress it with your favorite compression tool. Alternatively, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
With the fast pace of updates with .NET Core, the source code of the book is also available at http://www .github.com/ProfessionalCSharp. Be aware that the source code on GitHub offers living source files that will be updated with minor update versions of Visual Studio, as well as new experimental C# features. For updates to the source code and additional samples done after the release of the book, check the GitHub site. The stable version of the source code that corresponds to the content of the printed book is available from the Wrox site.
Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be grateful for your feedback. By sending in errata you may save another reader hours of frustration, and at the same time you can help provide even higher-quality information.
To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list including links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml.
If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.
At http://p2p.wrox.com you can find a number of different forums to help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:
1. Go to p2p.wrox.com and click the Register link.
2. Read the terms of use and click Agree.
3. Complete the required information to join and any optional information you want to provide, and click Submit.
4. You will receive an e-mail with information describing how to verify your account and complete the joining process.
NOTE You can read messages in the forums without joining P2P but to post your own messages, you must join.
After you join, you can post new messages and respond to messages other users post. You can read messages at any time on the web. If you want to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.