1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional c# 7 and net core 2 0 ( pdfdrive )

1,4K 0 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Professional C# 7 and .NET Core 2.0
Chuyên ngành Computer Science
Thể loại Textbook
Định dạng
Số trang 1.408
Dung lượng 39,83 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Cấu trúc

  • ChAPTER 1 NET Applications and Tools (64)
  • ChAPTER 2 Core C# (64)
  • ChAPTER 3 Objects and Types (64)
  • ChAPTER 4 Object-Oriented Programming with C# (64)
  • ChAPTER 5 Generics (64)
  • ChAPTER 6 Operators and Casts (64)
  • ChAPTER 7 Arrays (64)
  • ChAPTER 8 Delegates, Lambdas, and Events (64)
  • ChAPTER 9 Strings and Regular Expressions (64)
  • ChAPTER 10 Collections (64)
  • ChAPTER 11 Special Collections (64)
  • ChAPTER 12 Language Integrated Query (64)
  • ChAPTER 13 Functional Programming with C# (64)
  • ChAPTER 14 Errors and Exceptions (64)
  • ChAPTER 15 Asynchronous Programming (65)
  • ChAPTER 16 Reflection, Metadata, and Dynamic Programming (65)
  • ChAPTER 17 Managed and Unmanaged Memory (65)
  • ChAPTER 18 Visual Studio 2017 (65)
  • ChAPTER 19 Libraries, Assemblies, Packages, and NuGet (592)
  • ChAPTER 20 Dependency Injection (592)
  • ChAPTER 21 Tasks and Parallel Programming (592)
  • ChAPTER 22 Files and Streams (592)
  • ChAPTER 23 Networking (592)
  • ChAPTER 24 Security (592)
  • ChAPTER 25 ADO.NET and Transactions (592)
  • ChAPTER 26 Entity Framework Core (592)
  • ChAPTER 27 Localization (592)
  • ChAPTER 28 Testing (592)
  • ChAPTER 29 Tracing, Logging, and Analytics (592)
  • ChAPTER 30 ASP.NET Core (968)
  • ChAPTER 31 ASP.NET Core MVC (968)
  • ChAPTER 32 Web API (0)
  • ChAPTER 33 Windows Apps (1126)
  • ChAPTER 34 Patterns with XAML Apps (1126)
  • ChAPTER 35 Styling Windows Apps (1126)
  • ChAPTER 36 Advanced Windows Apps (1126)
  • ChAPTER 37 Xamarin.Forms (1126)

Nội dung

*"Professional C# 7 and .NET Core 2.0"* là cuốn sách toàn diện dành cho các lập trình viên muốn khai thác tối đa sức mạnh của ngôn ngữ C# phiên bản 7 và nền tảng .NET Core 2.0. Sách bao gồm hướng dẫn từ cơ bản đến nâng cao về lập trình C#, tập trung vào cách áp dụng công nghệ .NET Core 2.0 để xây dựng các ứng dụng hiện đại, hiệu quả và đa nền tảng. Nội dung chính của sách bao gồm: - **Giới thiệu C# 7 và .NET Core 2.0**: Tổng quan về những tính năng mới trong C# 7, như các kiểu giá trị tuple, pattern matching, expression-bodied members, và local functions. Phần này cũng giải thích về kiến trúc và lợi ích của .NET Core 2.0, cùng cách thiết lập môi trường phát triển. - **Ngôn ngữ C# nâng cao**: Khám phá các tính năng lập trình hướng đối tượng nâng cao của C# như generic, LINQ (Language-Integrated Query), lambda expressions, async/await, và cách quản lý bộ nhớ trong .NET. - **Xây dựng ứng dụng với .NET Core 2.0**: Hướng dẫn từng bước xây dựng ứng dụng console, ứng dụng web với ASP.NET Core, và các dịch vụ RESTful API trên nền tảng .NET Core 2.0. - **Quản lý và thao tác dữ liệu**: Tích hợp với các cơ sở dữ liệu sử dụng Entity Framework Core, bao gồm cả việc sử dụng các truy vấn LINQ để xử lý dữ liệu một cách hiệu quả và linh hoạt. - **Xây dựng ứng dụng đa nền tảng**: Cách triển khai ứng dụng .NET Core 2.0 trên các nền tảng Windows, Linux, và macOS, cho phép các lập trình viên tạo ra các ứng dụng có thể chạy ở bất kỳ môi trường nào. - **An ninh và bảo mật ứng dụng**: Hướng dẫn bảo mật các ứng dụng .NET với các phương pháp như xác thực và phân quyền, sử dụng ASP.NET Identity, và bảo vệ dữ liệu người dùng. - **Triển khai và phân phối ứng dụng**: Hướng dẫn cách đóng gói và triển khai ứng dụng, tận dụng Docker và các công nghệ cloud như Microsoft Azure, cũng như các quy trình CI/CD (Continuous Integration/Continuous Deployment) để tự động hóa triển khai. Với các ví dụ minh họa rõ ràng và bài tập thực hành, *"Professional C# 7 and .NET Core 2.0"* là tài liệu không thể thiếu dành cho các lập trình viên muốn làm chủ C# 7 và .NET Core 2.0, và áp dụng chúng trong các dự án thực tiễn. Cuốn sách giúp bạn phát triển những kỹ năng cần thiết để xây dựng các ứng dụng mạnh mẽ, linh hoạt và dễ mở rộng.

Visual Studio 2017

➤ Reviewing the history of NET

➤ Understanding differences between NET Framework and NET Core

➤ Features of the Windows Runtime

➤ NET Core Command-Line Interface

➤ Technologies for creating Windows apps

➤ Technologies for creating Web apps

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at www.wrox.com on the Download Code tab The source code is also available at https://github.com/ProfessionalCSharp/

ProfessionalCSharp7 in the directory HelloWorld.

The code for this chapter is divided into the following major examples:

.NET has been a great technology for creating applications on the Windows platform Now NET is a great technology for creating applications on Windows, Linux, and the Mac.

4 ❘ CHAPTER 1 NET ApplicATioNs ANd Tools

The creation of NET Core has been the biggest change for NET since its invention Now NET code is open-source code, you can create apps for other platforms, and NET uses modern patterns .NET Core and NuGet packages allow Microsoft to provide faster update cycles for delivering new features It’s not easy to decide what technology should be used for creating applications This chapter helps you with that It gives you information about the different technologies available for creating Windows and web apps and services, offers guidance on what to choose for database access, and highlights the differences between the NET Framework and NET Core.

To better understand what is available with NET and C#, it is best to know something about its history The following table shows the version of the NET Framework in relation to the Common Language Runtime (CLR), the version of C#, and the Visual Studio edition that gives some idea about the year when the corresponding versions have been released Besides knowing what technology to use, it’s also good to know what technology is not recommended because there’s a replacement.

NET FRAMEWORK CLR C# VISUAL STUDIO

When you create applications with NET Core, it’s important to know the timeframe for the support level

LTS (Long Time Support) has a longer support length than Current, but Current gets new features faster

LTS is supported for three years after the release or 12 months after the next LTS version, whichever is shorter So, NET Core 1.0 is supported until June 27, 2019 if the next LTS version is not released before June 27, 2018 In case the next LTS version is released earlier, NET Core 1.0 is supported one year after the release of the next LTS.

.NET Core 1.1 originally was a Current release, but it changed to LTS with the same support length as NET Core 1.0.

.NET Core 2.0 is a release with the support level Current This means it is supported for 3 years, 12 months after the next LTS, or 3 months after the next Current release—whichever is shorter It can be assumed that the last option will be the case, and NET Core 2.0 will be supported 3 months after NET Core 2.1 is available.

The next table lists NET Core versions, their release dates, and the support level.

NET CORE VERSION RELEASE DATE SUPPORT LEVEL

The following sections cover the details of these tables and the progress of C# and NET.

C# 1.0 was a completely new programming language designed for the NET Framework At the time it was developed, the NET Framework consisted of about 3,000 classes and the CLR.

After Microsoft was not allowed by a court order (filed by Sun, the company that created Java) to make changes to the Java code, Anders Hejlsberg designed C# Before working for Microsoft, Hejlsberg had his roots at Borland where he designed the Delphi programming language (an Object Pascal dialect) At Microsoft he was responsible for J++ (Microsoft’s version of the Java programming language) Given

Hejlsberg’s background, the C# programming language was mainly influenced by C++, Java, and Pascal.

Because C# was created later than Java and C++, Microsoft analyzed typical programming errors that happened with the other languages and did some things differently to avoid these errors Some differences include the following:

➤ With if statements, Boolean expressions are required (C++ allows an integer value here as well).

➤ It’s permissible to create value and reference types using the struct and class keywords (Java only allows creating custom reference types; with C++ the distinction between struct and class is only the default for the access modifier).

➤ Virtual and non-virtual methods are allowed (this is like C++; Java always creates virtual methods).

Of course, there are a lot more changes as you’ll see reading this book.

At this time, C# was not only a pure object-oriented programming language with features for inheritance, encapsulation, and polymorphism Instead, C# also offered component-based programming enhancements such as delegates and events.

Before NET and the CLR, every programming language had its own runtime With C++, the C++ Runtime is linked with every C++ program Visual Basic 6 had its own runtime with VBRun The runtime of Java is the Java Virtual Machine—which can be compared to the CLR The CLR is a runtime that is used by every NET programming language At the time the CLR appeared on the scene, Microsoft offered JScript.NET, Visual Basic NET, and Managed C++ in addition to C# JScript.NET was Microsoft’s JavaScript compiler that was to be used with the CLR and NET classes Visual Basic.NET was the name for Visual Basic that offered NET support Nowadays it’s just called Visual Basic again Managed C++ was the name for a lan- guage that mixed native C++ code with Managed NET Code The newer C++ language used today with NET is C++/CLR.

A compiler for a NET programming language generates Intermediate Language (IL) code The IL code looks like object-oriented machine code and can be checked by using the tool ildasm.exe to open DLL or EXE files that contain NET code The CLR contains a just-in-time (JIT) compiler that generates native code out of the IL code when the program starts to run

6 ❘ CHAPTER 1 NET ApplicATioNs ANd Tools

NOTE IL code is also known as managed code.

Other parts of the CLR are a garbage collector (GC), which is responsible for cleaning up managed memory that is no longer referenced; a security mechanism that uses code access security to verify what code is allowed to do; an extension for the debugger to allow a debug session between different programming languages (for example, starting a debug session with Visual Basic and continuing to debug within a C# library); and a threading facility that is responsible for creating threads on the underlying platform.

The NET Framework was already huge with version 1 The classes are organized within namespaces to help facilitate navigating the 3,000 available classes Namespaces are used to group classes and to solve conflicts by allowing the same class name in different namespaces Version 1 of the NET Framework allowed creat- ing Windows desktop applications using Windows Forms (namespace System.Windows.Forms), creating web applications with ASP.NET Web Forms (System.Web), communicating with applications and web ser- vices using ASP.NET Web Services, communicating more quickly between NET applications using NET Remoting, and creating COM+ components for running in an application server using Enterprise Services.

ASP.NET Web Forms was the technology for creating web applications with the goal for the developer to not need to know something about HTML and JavaScript Server-side controls that worked similarly to Windows Forms itself created HTML and JavaScript.

C# 1.2 and NET 1.1 were mainly a bug fix release with minor enhancements

NOTE Inheritance is discussed in Chapter 4, “Object-Oriented Programming with

C#”; delegates and events are covered in Chapter 8, “Delegates, Lambdas, and

NOTE Every new release of NET has been accompanied by a new version of the book Professional C# With NET 1.0, the book was already in the second edition as the first edition had been published with Beta 2 of NET 1.0 You’re holding the 11th edition of this book in your hands.

Tracing, Logging, and Analytics

Libraries, Assemblies, Packages, and NuGet

➤ Differences between libraries, assemblies, packages

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at www.wrox.com on the Download

Code tab The source code is also available at https://github.com/ProfessionalCSharp/

ProfessionalCSharp7 in the directory Libraries.

The code for this chapter is divided into the following major examples:

Libraries make it possible for you to reuse code in multiple applications With Windows, libraries have a long history, and architecture guidelines have taken different directions with newer technologies Before NET, dynamic link libraries (DLLs) could be shared between different applications These DLLs have been installed in a shared directory It wasn’t possible to have multiple versions of these libraries on the same system, but they should have been upward compatible Of course, this wasn’t always the case In addition, there were problems with application installations that did not pay atten- tion to the guidelines and replaced a shared library with an older one This was the DLL Hell.

.NET tried to solve this with assemblies Assemblies are libraries that could be shared In addition to normal DLLs, assemblies contain extensible metadata with information about the library and a version number, and it’s possible to install multiple versions side by side in the global assembly cache Microsoft tried to fix ver- sioning issues, but this added another layer of complexity

Let’s assume you’re using library A and B from your application X (see Figure 19-1) Application X refer- ences version 1.1 from library A and version 1.0 from library B The issue is that library B references library

A as well, but it references a different version—version 1.0 One process can only have one version of a library loaded What version of the library A is loaded into the process? In case library B is used before library A, version 1.0 wins This is a big issue as soon as application X needs to use library A itself

To avoid this issue, you could configure assembly redirects You can define an assembly redirect for applica- tion X to load version 1.1 from library A Library B then needs to use version 1.1 from library A as well In case library A is upward-compatible, this shouldn’t be an issue

Of course, compatibility doesn’t always exist, and issues can be more complex Publishers of components can create a publisher policy to define redirects with the library itself This redirect can be overridden by the application There’s a lot of complexity with this, which resulted in Assembly Hell.

NOTE With NET Core there’s no global sharing of assemblies as it was with the NET Framework Only the NET runtime can be shared between different applications.

NuGet packages add another abstraction layer to libraries A NuGet package can contain multiple versions of one or more assemblies, along with other stuff, such as automatic configuration of assembly redirects.

Instead of waiting for new NET Framework releases, you could add functionality via NuGet packages, which allowed for faster updates of the packages NuGet packages are a great delivery vehicle Some librar- ies like Entity Framework switched to NuGet to allow for faster updates than the NET Framework offered.

However, there are some issues with NuGet Often adding NuGet packages to projects fail NuGet pack- ages might not be compatible with the project When adding packages was successful, it can happen that the package made some incorrect configuration with the project, e.g wrong binding redirects This results in the feeling of the NuGet Package Hell The problems from DLLs moved to different abstraction layers and are indeed different With newer NuGet versions and advancements in NuGet, Microsoft has tried to solve the issues with NuGet.

Directions in the architecture of NET Core also changed With NET Core, packages have been made more granular For example, with the NET Framework, the Console class is inside the mscorlib assembly, which is an assembly needed by every NET Framework application Of course, not every NET application needs the Console class With NET Core 1.0, a separate package System.Console exists that contains the Console class and a few related classes The goal was to make it easier to update and select what packages are really needed With some Beta versions of NET Core 1.0, the project files contained a large list of pack- ages, which didn’t make development easier Just before the release of NET Core 1.0, Microsoft introduced meta-packages (or reference-packages) A meta-package doesn’t include code but instead a list of other packages

With NET Core 2.0 includes another simplification When you created a “Hello, World!” Console applica- tion with NET Core 1.1, the generated project.asset.json file has a size of 313 KB This file (in the obj directory) shows the tree of dependencies With NET Core 2.0, the file size was reduced to 33 KB because of larger packages with fewer references.

This chapter goes into the detail of assemblies and NuGet packages, explains how to share code using NET Standard libraries, and also explains differences with Windows Runtime components.

An assembly is a library or executable that includes additional metadata Using NET Core, the application containing the Main method is created as a library with the file extension dll This DLL needs a hosting process to load this library, which you do using dotnetrun, or just dotnet from a runtime environment When you create standalone applications with NET Core, different executables are created for every plat- form to load the library.

Let’s have a look at a simple “Hello, World!” console application created in the directory ConsoleApp, using the command

After building the application, the DLL can be found in the bin/debug/netcoreapp2.0 directory The netcoreapp2.0 directory depends on the target framework listed in the csproj project file.

Assembly information can be read using the ildasm.exe (IL Disassembler) command-line utility Ildasm.exe shows the types of the assembly with its members, with the additional metadata as shown in Figure 19-2

Clicking MANIFEST (refer to Figure 19-2), opens metadata information for the assembly as shown in Figure 19-3 The assembly which has the name ConsoleApp, references the assem- blies System.Runtime and System.Console You also can see several configured assembly attributes such as AssemblyCompanyNameAttribute, AssemblyConfigurationAttribute,

Assembly metadata that describes the application can be configured using Visual Studio; select Package in the Project Properties (see Figure 19-4).

Of course, you can also directly edit the project file (code file ConsoleApp/ConsoleApp.csproj):

Sample App for Professional C#

Copyright (c) CN innovation

https://github.com/ProfessionalCSharp

https://github.com/ProfessionalCSharp/ProfessionalCSharp7

Wrox Press, Sample, Libraries

NOTE With previous projects, such metadata information was typically added to the file AssemblyInfo.cs by adding this information with global C# attributes You can still do it this way, but then you need to configure the csproj file to not automatically generate the attributes.

You can use shared code by creating libraries With Visual Studio 2017, you’ve many options to create libraries, as shown here:

➤ WPF Custom Control Library (.NET Framework)

➤ WPF User Control Library (.NET Framework)

➤ Windows Forms Control Library (.NET Framework)

The Shared Project listed is not really a class library, but you can use it for sharing code from multiple proj- ects See the section “Using Shared Projects” later in this chapter for more information.

ASP.NET Core MVC

➤ CHAPTER 32: ASP.NET Web API

➤ Understanding ASP.NET Core and web technologies

➤ Working with HTTP request and response

➤ Using dependency injection with ASP.NET

➤ Using sessions for state management

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The Wrox.com code downloads for this chapter are found at http://www.wrox.com on the Download Code tab The source code is also available at https://github.com/

ProfessionalCSharp/ProfessionalCSharp7 in the directory aspnetcore

The code for this chapter contains this example project:

After more than 15 years of ASP.NET, ASP.NET Core was a complete rewrite of ASP.NET ASP.NET Core features modular programming, makes use of modern patterns, is fully open sourced, is light- weight for best use in the cloud, and is available to non-Microsoft platforms.

A full rewrite of ASP.NET gives a lot of advantages, but this also means reworking existing web appli- cations based on older versions of ASP.NET Is it necessary to rewrite existing web applications to ASP.NET Core? Let’s try to answer this question.

ASP.NET Web Forms is no longer part of ASP.NET Core However, having web applications that include this technology does not mean you have to rewrite them It’s still possible to maintain legacy applications written with ASP.NET Web Forms with the full framework ASP.NET Web Forms even received some enhancements with the latest versions of the NET Framework, such as asynchronous model binding.

The ASP.NET MVC variant of ASP.NET is still part of ASP.NET Core, but it’s different from the previ- ous framework with the NET Framework When doing a high-level comparison of ASP.NET MVC and ASP.NET Core MVC, the two technologies look very much alike However, behind the scenes everything is different When you transfer ASP.NET MVC applications to ASP.NET Core MVC, you need to make some changes to the source code to bring it to the new application stack For some applications this might mean making minor changes to namespaces, types, and some methods If the application makes use of more advanced features from ASP.NET MVC, you must do more work to move the application to the new technology.

Converting ASP.NET Web Forms to ASP.NET Core MVC might be a lot of work ASP.NET Web Forms abstracts HTML and JavaScript from the developer Using ASP.NET Web Forms, it’s not necessary to know HTML and JavaScript Instead you use server-side controls with C# code The server-side controls them- selves return HTML and JavaScript This programming model is like the old Windows Forms programming model With ASP.NET MVC, developers need to know HTML and JavaScript ASP.NET MVC is based on the Model-View-Controller (MVC) pattern, which makes unit testing easy Because ASP.NET Web Forms and ASP.NET MVC are based on very different architecture patterns, it can be a huge undertaking to migrate ASP.NET Web Forms applications to ASP.NET MVC Before taking on this task, you should create a checklist of the advantages and the disadvantages of keeping the old technology with your solution and compare this with the advantages and disadvantages of going to the new technology You will still be able to work with ASP.NET Web Forms for many years to come

NOTE My website at http://www.cninnoation.com was originally created with

ASP.NET Web Forms I’ve converted this website with an early version of ASP.NET

MVC to this new technology stack Because my original site already made use of a lot of separate components to abstract the database and service code, it was not really a huge undertaking and was done very fast I was able to use the database and service code directly from ASP.NET MVC On the other hand, if I had used Web Forms con- trols to access the database instead of using my own controls, it would have been a lot more work Nowadays, this web application is implemented with ASP.NET Core.

NOTE This book does not cover the legacy technology ASP.NET Web Forms ASP

NET MVC also is not covered This book has a focus on new technologies; conse- quently, the material about web applications is based on ASP.NET Core and ASP

NET Core MVC You should use these technologies for new web applications In case you need to maintain older applications, you should read older editions of this book, such as Professional C# 5.0 and NET 4.5.1, which covers ASP.NET 4.5, ASP.NET

Web Forms 4.5, and ASP.NET MVC 5.

This chapter covers the foundation of ASP.NET Core 2.0 Chapter 31 covers ASP.NET Core MVC, a framework that is built on top of ASP.NET Core Chapter 32 covers creating a web API with ASP.NET Core MVC.

Before getting into the foundations of ASP.NET Core later in this chapter, this section describes core web technologies that are important to know when creating web applications: HTML, CSS, JavaScript, scripting libraries.

HTML is the markup language that is interpreted by web browsers It defines elements to display various headings, tables, lists, and input elements such as text and combo boxes.

HTML5 has been a W3C recommendation since October 2014 (http://w3.org/TR/html5), and it is offered by all the major browsers You can find lists of work in progress at http://w3.org/TR/html At the time of this writing, HTML 5.2 has been a W3C recommendation since December 2017 With the features of HTML 5, several browser add-ins (such as Flash and Silverlight) are not required anymore because the things the add-ins do can now be done directly with HTML and JavaScript Of course, you might still need Flash and Silverlight because not all websites have moved to the new technologies or your users might still be using older browser versions that don’t support HTML 5.

HTML 5 adds new semantic elements that search engines are better able to use for analyzing the site A canvas element enables the dynamic use of 2D shapes and images, and video and audio elements make the object element obsolete With recent additions to the media source (http://w3c.github.io/media- source), adaptive streaming is also offered by HTML; previously this had been an advantage of Silverlight. HTML 5 also defines JavaScript APIs for drag-and-drop, storage, web sockets, and much more.

Whereas HTML defines the content of web pages, CSS defines the look In the earlier days of HTML, for example, the list item tag

  • defined whether list elements should be displayed with a circle, a disc, or a square Nowadays such information is completely removed from HTML and is instead put into a cascading style sheet (CSS).

    With CSS styles, you can use flexible selectors to select HTML elements, and you can define styles for these elements You can select an element via its ID or its name, and you can define CSS classes that can be ref- erenced from within the HTML code With newer versions of CSS, you can define quite complex rules for selecting specific HTML elements.

    As of Visual Studio 2017, some web project templates make use of Twitter Bootstrap This is a collection of CSS and HTML conventions, and you can easily adapt different looks and download ready-to-use tem- plates Visit www.getbootstrap.com for documentation and basic templates.

    Xamarin.Forms

    WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

    The wrox.com code downloads for this chapter are found at www.wrox.com on the Download Code tab The source code is also available at https://github.com/ProfessionalCSharp/

    ProfessionalCSharp7 in the directory Windows.

    The code for this chapter is divided into the following major examples:

    Windows Apps make use of NET Core, but there’s a big difference with web apps and ASP.NET Core Windows apps run only on the Windows platform, on Windows 10 You can use these apps not only for the desktop, but also for Xbox, HoloLens, and Raspberry PI.

    NOTE For creating apps using XAML on iPhone and Android, you should read

    Chapter 37, “Xamarin.Forms.” However, be sure to read this chapter first, because the Xamarin.Forms chapter only explains the differences.

    Windows apps also make use of the Windows Runtime (WinRT) The Windows Runtime is a platform created using C++ with a new generation of COM objects With this, the Windows Runtime is not only available for NET applications but also for C++ and applications created with JavaScript For accessing the Windows Runtime from these different platforms, a compatibility layer was created: the language projec- tion With language projection, the API offered by the Windows Runtime looks like a NET API.

    That the runtime looks like NET is because of the language projection Metadata of the Windows Runtime is created in the same form as with NET You can use the same tools (for example, ildasm) to read metadata information from the Windows Runtime Dynamically reading metadata already has a history with COM There, metadata was accessible from type libraries This metadata technology was not as powerful as meta- data was when it was implemented with NET With NET, metadata is extensible with custom attributes and can be accessed using reflection (Read more about this in Chapter 16, “Reflection, Metadata, and Dynamic Programming.”) The Windows Runtime is now using the same format for its metadata as NET Thus, you can open the winmd files (metadata files for the Windows Runtime) using the ildasm command line to see the API calls with their parameters You can find the Windows Metadata files in the directory

    Language projection maps Windows Runtime types to NET types For example, in the file Windows. Foundation.FoundationContract.winmd you’ll find the IIterable and IIterator interfaces in the namespace Windows.Foundation.Collections These interfaces look very similar to the NET interfaces IEnumerable and IEnumerator Indeed, they are automatically mapped with language projection.

    The Windows Runtime doesn’t contain any collections Instead, collections are implemented by the different platforms that use the Windows Runtime—for example, C++, JavaScript, and NET.

    Not all the interfaces of the contracts can be directly mapped Chapter 22, “Files and Streams,” showed files and streams with the Windows Runtime from the namespace Windows.Storage.Streams To use the Windows streams together with NET streams, you can use extension methods such as AsStream, AsStreamForRead, and AsStreamForWrite.

    NOTE Creating Windows apps, your app uses NET Core APIs and Windows

    Let’s start creating a new Windows App with Visual Studio 2017 Select the Universal Windows Platform project The first question asked is the target and minimum platform to support (see Figure 33-1) With every newer platform version, you get more features However, you need to pay attention what version of Windows 10 your users have They can’t install and run your Windows 10 app if the platform version is not supported.

    With the target version you select, you specify the API version that can be used by the app With the mini- mum version you specify the build version where the app can be installed to and run If you set the target and minimum version to different values, you need to write adaptive code Before invoking an API, you need

    Introducing Windows Apps ❘ 1085 to make sure the API is available on the supported builds Without the newer API available, you can reduce the features from the app, or you can offer different features based on the build the user is running.

    The following table lists the Windows 10 versions, the build numbers, their release dates, and features from the build From the API documentation you sometimes need the version, and sometimes the build number to know if an API is available for your support requirements This table will help.

    VERSION BUILD BUILD NAME RELEASE

    1507 10240 July 2015 Better adaptive layouts, compiled data bind- ing, declarative incremental rendering of lists (phases), deferred UI loading, RelativePanel, SplitPanel, CalendarDatePicker, Cortana, and app-to-app communication

    Windows Hello, Storage APIs updated, and ORTC (Object Real-Time Communication) for real-time audio/video calls

    July 2016 New ink controls, Cortana APIs, animated GIF with XAML images, composition interactions, and connected animations

    New composition APIs, ink support for pro- tractor and ruler, images on a map, and RadialController (Surface Dial)

    .NET Standard 2.0, Fluent Design, conditional XAML, User Activities, My People, and new UI controls (ColorPicker, NavigationView, PersonPicture, RatingControl)

    NOTE To use NET Standard 2.0 libraries, the app needs to have build version 16299 as minimum build number Most sample apps of the book have both the target and minimum version set to 16299.

    You can change the build target and minimum version numbers with the project properties Windows apps have another important configuration for the packaging The file Package.appxmanifest can be config- ured using the Package Manifest Editor

    With the Application settings (see Figure 33-2), you can configure the display name of the application, the default language, supported rotations of the device, and automatic periodic tile updates

    In the Visual Assets tab, you can configure all the different icons of the application—tile images for different tile sizes, different device resolutions, a splash screen, and a package logo for the Windows Store

    Settings in the Capabilities tab (see Figure 33-3) allow you to select the capabilities needed by the app

    A capability that is by default selected is the Internet (Client) capability In case you need to do network requests to a server, this capability needs to be turned on Other capabilities enable you to access location

    Introducing Windows Apps ❘ 1087 information, access the microphone and the webcam, access different folders on the file system such as the Music Library, the Pictures Library, or the Videos Library.

    With the Declarations settings (see Figure 33-4), you can add features of the application Windows needs to know about For example, when sharing data from one app, Windows shows the apps that accept the shared data For this, the app needs to be registered as Share Target Registering apps as a share target, to be acti- vatable via a protocol or a file type extension, to communicate between app services, and more, settings in declarations are available.

  • Ngày đăng: 11/11/2024, 12:50

    w