Dotnet Core 简明教程

.NET Core - Quick Guide

.NET Core - Overview

NET Core is the latest general purpose development platform maintained by Microsoft. It works across different platforms and has been redesigned in a way that makes .NET fast, flexible and modern. This happens to be one of the major contributions by Microsoft. Developers can now build Android, iOS, Linux, Mac, and Windows applications with .NET, all in Open Source.

在本教程中,我们涵盖了 .NET Core 和几项创新,包括 .NET Framework 更新、.NET Standard、通用 Windows 平台更新等。

NET Core is the latest general purpose development platform maintained by Microsoft. It works across different platforms and has been redesigned in a way that makes .NET fast, flexible and modern. This happens to be one of the major contributions by Microsoft. Developers can now build Android, iOS, Linux, Mac, and Windows applications with .NET, all in Open Source.

In this tutorial, we will cover .NET Core and a few new innovations including the .NET Framework updates, .NET Standard, and Universal Windows Platform updates, etc.

Characteristics of .NET Core

以下是 .NET Core 的主要特征:

The following are the major characteristics of .NET Core −

Open source

  1. .NET Core is an open source implementation, using MIT and Apache 2 licenses.

  2. .NET Core is a .NET Foundation project and is available on GitHub.

  3. As an open source project, it promotes a more transparent development process and promotes an active and engaged community.

Cross-platform

  1. Application implemented in .NET Core can be run and its code can be reused regardless of your platform target.

  2. It currently supports three main operating systems (OS) Windows Linux MacOS

  3. The supported Operating Systems (OS), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.

Flexible deployment

  1. There can be two types of deployments for .NET Core applications − Framework-dependent deployment Self-contained deployment

  2. With framework-dependent deployment, your app depends on a system-wide version of .NET Core on which your app and third-party dependencies are installed.

  3. With self-contained deployment, the .NET Core version used to build your application is also deployed along with your app and third-party dependencies and can run side-by-side with other versions.

Command-line tools

  1. All product scenarios can be exercised at the command-line.

Compatible

  1. .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library

Modular

  1. .NET Core is released through NuGet in smaller assembly packages.

  2. .NET Framework is one large assembly that contains most of the core functionalities.

  3. .NET Core is made available as smaller feature-centric packages.

  4. This modular approach enables the developers to optimize their app by including just those NuGet packages which they need in their app.

  5. The benefits of a smaller app surface area include tighter security, reduced servicing, improved performance, and decreased costs in a pay-for-what-you-use model.

The .NET Core Platform

NET Core Platform contains the following main parts −
  1. .NET Runtime − It provides a type system, assembly loading, a garbage collector, native interop and other basic services.

  2. Fundamental Libraries − A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities.

  3. SDK & Compiler − A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.

  4. ‘dotnet’ app host − It is used to launch .NET Core apps. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.

.NET Core - Prerequisites

在本章中,我们将讨论在部署和运行时您需要存在的各种依赖关系。其中包括在 Windows 机器上使用 Visual Studio 开发的 .NET Core 应用程序。

In this chapter, we will discuss the various dependencies that you need to deploy and run. These include the .NET Core applications on Windows machines that are developed using Visual Studio.

Supported Windows Versions

NET Core is supported on the following versions of Windows −
  1. Windows 7 SP1

  2. Windows 8.1

  3. Windows 10

  4. Windows Server 2008 R2 SP1 (Full Server or Server Core)

  5. Windows Server 2012 SP1 (Full Server or Server Core)

  6. Windows Server 2012 R2 SP1 (Full Server or Server Core)

  7. Windows Server 2016 (Full Server, Server Core or Nano Server)

Dependencies

  1. If you are running your .NET Core application on Windows versions earlier than Windows 10 and Windows Server 2016, then it will also require the Visual C++ Redistributable.

  2. This dependency is automatically installed for you if you use the .NET Core installer.

  3. You need to manually install the Visual C++ Redistributable for Visual Studio 2015 if you are installing .NET Core via the installer script or deploying a self-contained .NET Core application.

  4. For Windows 7 and Windows Server 2008 machines, you need to make sure that your Windows installation is up-to-date and also includes hotfix KB2533623 installed through Windows Update.

Prerequisites with Visual Studio

  1. To develop .NET Core applications using the .NET Core SDK, you can use any editor of your choice.

  2. However, if you want to develop .NET Core applications on Windows using Visual Studio, you can use the following two versions − Visual Studio 2015 Visual Studio 2017 RC

  3. Projects created with Visual Studio 2015 will be project.json-based by default while projects created with Visual Studio 2017 RC will always be MSBuild-based.

.NET Core - Environment Setup

在本章中,我们将讨论 .NET Core 的环境设置。它对 .NET Framework 进行了重大重新设计。要在您的应用程序中使用 .NET Core,您可以使用两个版本:

In this chapter, we will discuss the Environment Setup of .NET Core. It is a significant redesign of the .NET Framework. To use .NET Core in your application, there are two versions you can use −

  1. Visual Studio 2015

  2. Visual Studio 2017 RC

Visual Studio 2015

要使用 Visual Studio 2015,您必须安装以下内容:

To use Visual Studio 2015, you must have installed the following −

  1. Microsoft Visual Studio 2015 Update 3

  2. Microsoft .NET Core 1.0.1 - VS 2015 Tooling Preview 2

Microsoft 提供了一个visual studio的免费版本,其中还包含 SQL Server,可以从 https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx 下载,而 Microsoft .NET Core 1.0.1 - VS 2015 Tooling Preview 2可以从 https://www.visualstudio.com/downloads/ 下载

Microsoft provides a free version of visual studio which also contains the SQL Server and can be downloaded from https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx and Microsoft .NET Core 1.0.1 - VS 2015 Tooling Preview 2 can be downloaded from https://www.visualstudio.com/downloads/

你也可以在以下网址上查看安装指南 https://www.microsoft.com/net/core/#windowsvs2017

You can also follow the installation guidelines on the following Url https://www.microsoft.com/net/core/#windowsvs2017

Installation of Visual Studio 2015

按照以下步骤安装 Visual Studio 2015:

Follow these steps to install Visual Studio 2015 −

Step 1 - 下载完成后,运行安装程序。将显示以下对话框。

Step 1 − Once the downloading completes, then run the installer. The following dialog box will be displayed.

download

Step 2 - 单击 Install 以开始安装过程。

Step 2 − Click Install to start the installation process.

install

Step 3 - 安装完成后,您将看到以下对话框。

Step 3 − Once the installation completes, you will see the following dialog box.

complete

Step 4 - 关闭此对话框并在需要时重新启动计算机。

Step 4 − Close this dialog and restart your computer if required.

Step 5 - 从“开始”菜单中打开 Visual Studio;你将收到以下对话框。首次加载并最终使用可能需要几分钟。

Step 5 − Open Visual Studio from the Start Menu; you will receive the following dialog box. It may take a few minutes to load and finally be used for the first time.

open

Step 6 - 加载后,你将看到以下屏幕。

Step 6 − Once it is loaded, you will see the following screen.

loading

Step 7 - Visual Studio 安装完成后,关闭 Visual Studio 并启动 Microsoft .NET Core - VS 2015 Tooling Preview 2。

Step 7 − Once Visual Studio installation is finished, then close Visual Studio and launch Microsoft .NET Core - VS 2015 Tooling Preview 2.

launch

Step 8 − 勾选复选框,然后单击安装。

Step 8 − Check the checkbox and click Install.

checkbox

Step 9 - 安装完成后,你将看到以下对话框。

Step 9 − Once the installation completes, you will see the following dialog box.

application ready

你现在已可以使用 .NET Core 启动应用程序。

You are now ready to start your application using .NET Core.

Visual Studio 2017

在本教程中,我们将使用 Visual Studio 2015,但如果你想使用 Visual Studio 2017,Visual Studio 2017 RC 中包括一个 Visual Studio 的 .NET Core 工具试用版,你可以在这里查看安装指南 https://www.microsoft.com/net/core/#windowsvs2017

In this tutorial, we will be using Visual Studio 2015, but if you want to use Visual Studio 2017, an experimental release of .NET Core tools for Visual Studio is included in Visual Studio 2017 RC and you can see the installation guidelines here https://www.microsoft.com/net/core/#windowsvs2017

.NET Core - Getting Started

Visual Studio 2015 为 .NET Core 应用程序开发提供了一个全功能的开发环境。在本章中,我们将在 Visual Studio 中创建一个新项目。安装 Visual Studio 2015 工具后,便可开始构建新的 .NET Core 应用程序。

Visual Studio 2015 provides a full-featured development environment for developing .NET Core applications. In this chapter, we will be creating a new project inside Visual Studio. Once you have installed the Visual Studio 2015 tooling, you can start building a new .NET Core Application.

core application

New Project 对话框中,在“模板”列表中,展开 Visual C# 节点并选择 .NET Core,你应该会看到以下三个新项目模板

In the New Project dialog box, in the Templates list, expand the Visual C# node and select .NET Core and you should see the following three new project templates

  1. Class Library (.NET Core)

  2. Console Application (.NET Core)

  3. ASP.NET Core Web Application (.NET Core)

在“新建项目”对话框的中间窗格中,选择“控制台应用程序(.NET Core)”,并将其命名为“FirstApp”,然后单击“确定”。

In the middle pane on the New Project dialog box, select Console Application (.NET Core) and name it "FirstApp", then click OK.

first app

Visual Studio 将打开新创建的项目,你将在“解决方案资源管理器”窗口中看到此项目中的所有文件。

Visual Studio will open the newly created project, and you will see in the Solution Explorer window all of the files that are in this project.

要测试 .NET Core 控制台应用程序是否正常运行,我们添加以下行。

To test that .NET core console application is working, let us add the following line.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstApp {
   public class Program {
      public static void Main(string[] args) {
         Console.WriteLine("Hello guys, welcome to .NET Core world!");
      }
   }
}

现在,运行该应用程序。你应看到以下输出。

Now, run the application. You should see the following output.

output

.NET Core - Numerics

NET Core supports the standard numeric integral and floating-point primitives. It also supports the following types −
  1. System.Numerics.BigInteger which is an integral type with no upper or lower bound.

  2. System.Numerics.Complex is a type that represents complex numbers.

  3. A set of Single Instruction Multiple Data (SIMD)-enabled vector types in the System.Numerics namespace.

Integral types

NET Core supports both signed and unsigned integers of different ranges from one byte to eight bytes in length. All integers are value types.

下表表示整数类型及其大小;

NET Core supports both signed and unsigned integers of different ranges from one byte to eight bytes in length. All integers are value types.

The following table represents the integral types and their size;

Type

Signed/ Unsigned

Size (bytes)

Minimum Value

Maximum Value

Byte

Unsigned

1

0

255

Int16

Signed

2

−32,768

32,767

Int32

Signed

4

−2,147,483,648

2,147,483,647

Int64

Signed

8

−9,223,372,036,854,775,808

9,223,372,036,854,775,807

SByte

Signed

1

-128

127

UInt16

Unsigned

2

0

65,535

UInt32

Unsigned

4

0

4,294,967,295

UInt64

Unsigned

8

0

18,446,744,073,709,551,615

每种整数类型都支持一组标准术语,包括算术、比较、相等性、显式转换和隐式转换运算符。

Each integral type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators.

你还可以使用 System.BitConverter 类通过整数值中的单独位进行操作。

You can also work with the individual bits in an integer value by using the System.BitConverter class.

Floating-point types

Table 1. NET Core includes three primitive floating point types, which are shown in the following table.

Type

Size (bytes)

Minimum Value

Maximum Value

Double

8

−1.79769313486232e308

1.79769313486232e308

Single

4

−3.402823e38

3.402823e38

Decimal

16

−79,228,162,514,264,337,593,5 43,950,335

79,228,162,514,264,337,593,543,9 50,335

  1. Each floating-point type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators.

  2. You can also work with the individual bits in Double and Single values by using the BitConverter class.

  3. The Decimal structure has its own methods, Decimal.GetBits and Decimal.Decimal(Int32()), for working with a decimal value’s individual bits, as well as its own set of methods for performing some additional mathematical operations.

BigInteger

  1. System.Numerics.BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.

  2. The methods of the BigInteger type is closely parallel to those of the other integral types.

Complex

  1. The System.Numerics.Complex type represents a complex number, i.e., a number with a real number part and an imaginary number part

  2. It supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators, as well as mathematical, algebraic, and trigonometric methods.

SIMD

  1. The Numerics namespace includes a set of SIMD-enabled vector types for .NET Core.

  2. SIMD allows some operations to be parallelized at the hardware level, which results in huge performance improvements in mathematical, scientific, and graphics apps that perform computations over vectors.

  3. The SIMD-enabled vector types in .NET Core include the following − System.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single. The Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal. Two matrix types, System.Numerics.Matrix3×2, which represents a 3×2 matrix; and System.Numerics.Matrix4×4, which represents a 4×4 matrix. The System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations.

.NET Core - Garbage Collection

在本章中,我们将介绍垃圾回收的概念,它是 .NET 托管代码平台最重要的特性之一。垃圾回收器 (GC) 管理着内存的分配和释放。垃圾回收器充当自动内存管理器。

In this chapter, we will cover the concept of Garbage collection which is one of most important features of the .NET managed code platform. The garbage collector (GC) manages the allocation and release of memory. The garbage collector serves as an automatic memory manager.

  1. You do not need to know how to allocate and release memory or manage the lifetime of the objects that use that memory

  2. An allocation is made any time you declare an object with a “new” keyword or a value type is boxed. Allocations are typically very fast

  3. When there isn’t enough memory to allocate an object, the GC must collect and dispose of garbage memory to make memory available for new allocations.

  4. This process is known as garbage collection.

Advantages of Garbage Collection

垃圾回收提供了以下好处:

Garbage Collection provides the following benefits −

  1. You don’t need to free memory manually while developing your application.

  2. It also allocates objects on the managed heap efficiently.

  3. When objects are no longer used then it will reclaim those objects by clearing their memory, and keeps the memory available for future allocations.

  4. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.

  5. It also provides memory safety by making sure that an object cannot use the content of another object.

Conditions for Garbage Collection

如果下列条件之一为真,则发生垃圾回收。

Garbage collection occurs when one of the following conditions is true.

  1. The system has low physical memory.

  2. The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.

  3. The GC.Collect method is called and in almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

Generations

NET 垃圾回收程序分 3 代且每代都有自己的堆,用于存储已分配的对象。一个基本原则是,大多数对象都是短期的或长时间的。

The .NET Garbage Collector has 3 generations and each generation has its own heap that that is used for the storage of allocated objects. There is a basic principle that most objects are either short-lived or long-lived.

Generation First (0)

  1. In Generation 0, objects are first allocated.

  2. In this generation, objects often don’t live past the first generation, since they are no longer in use (out of scope) by the time the next garbage collection occurs.

  3. Generation 0 is quick to collect because its associated heap is small.

Generation Second (1)

  1. In Generation 1, objects have a second chance space.

  2. Objects that are short-lived but survive the generation 0 collection (often based on coincidental timing) go to generation 1.

  3. Generation 1 collections are also quick because its associated heap is also small.

  4. The first two heaps remain small because objects are either collected or promoted to the next generation heap.

Generation Third (2)

  1. In Generation 2, all long objects are lived and its heap can grow to be very large.

  2. The objects in this generation can survive a long time and there is no next generation heap to further promote objects.

  3. The Garbage Collector has an additional heap for large objects known as Large Object Heap (LOH).

  4. It is reserved for objects that are 85,000 bytes or greater.

  5. Large objects are not allocated to the generational heaps but are allocated directly to the LOH

  6. Generation 2 and LOH collections can take noticeable time for programs that have run for a long time or operate over large amounts of data.

  7. Large server programs are known to have heaps in the 10s of GBs.

  8. The GC employs a variety of techniques to reduce the amount of time that it blocks program execution.

  9. The primary approach is to do as much garbage collection work as possible on a background thread in a way that does not interfere with program execution.

  10. The GC also exposes a few ways for developers to influence its behavior, which can be quite useful to improve performance.

.NET Core - Code Execution

在本章中,我们将了解 .NET Core 的执行过程并将其与 .NET Framework 进行比较。托管执行过程包括以下步骤。

In this chapter, we will understand the execution process of .NET Core and compare it with the .NET Framework. The managed execution process includes the following steps.

  1. Choosing a compiler

  2. Compiling your code to MSIL

  3. Compiling MSIL to native code

  4. Running code

code execution

Choosing a Compiler

  1. It is a multi-language execution environment, the runtime supports a wide variety of data types and language features.

  2. To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime.

Compiling your code to MSIL

  1. Compiling translates your source code into Microsoft Intermediate Language (MSIL) and generates the required metadata.

  2. Metadata describes the types in your code, including the definition of each type, the signatures of each type’s members, the members that your code references, and other data that the runtime uses at execution time.

  3. The runtime locates and extracts the metadata from the file as well as from framework class libraries (FCL) as needed during execution.

Compiling MSIL to Native Code

  1. At execution time, a just-in-time (JIT) compiler translates the MSIL into native code.

  2. During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe.

Running Code

  1. The common language runtime provides the infrastructure that enables the execution to take place and services that can be used during execution.

  2. During execution, managed code receives services such as garbage collection, security, interoperability with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support.

.NET Core Code Execution Process

现在让我们关联一下使用 .NET Framework 和 .NET Core 来执行代码的方法。在 .NET Core 中,有这些组件的许多替代品,这些组件是 .NET Framework 的一部分。

Now let’s relate how code executes with .NET Core as compared to .NET Framework. In .NET Core there are many replacements of these components that are the part of the .NET Framework.

dotnet core code execution
  1. In .NET Core now we have a new series of compilers, like we have Roslyn for C# and VB.

  2. You can also make use of the new F# 4.1 compiler if you want to use F# with .NET Core.

  3. Actually these tools are different and we can use Roslyn with .NET Framework as well if we are using C# 6 or later, because C# compiler can only support up to C# 5.

  4. In .NET Core, we don’t have a framework class libraries (FCL), so a different set of libraries are used and we now have CoreFx.

  5. CoreFx is the reimplementation of the class libraries for .NET Core.

  6. We also have a new run time with .NET Core known as CoreCLR and leverages a JIT Compiler.

  7. Now the question is why do we have the reimplementation of all these components that we already have in .NET framework.

  8. So the answer is the same as why Microsoft implemented .NET Core.

.NET Core - Modularity

这是 .NET Core 构建和实现模块化应用程序的另一个考虑因素。你的应用程序现在可以仅安装必需的内容,而不是安装整个 .NET Framework。我们转到 Visual Studio 并查看模块化性。

It is another consideration of .NET Core to build and implement application that is modular. Instead of installing the entire .NET Framework, your application can now just install what is required. Let us go to the visual studio and see the modularity.

这是我们在解决方案资源管理器中的简单 .NET Core 应用程序。让我们展开“引用”,你将看到对 .NETCoreApp 的引用。

Here is our simple .NET Core application, in Solution Explorer. Let us expand References and you will see reference to .NETCoreApp

dotnet core app

在 .NETCoreApp 中,你将看到对 NuGet 的程序包引用;我们展开它。

Inside .NETCoreApp, you will see package reference to NuGet; let us expand it.

nuget

你将看到一整套 NuGet 程序包引用。如果你使用过 .NET Framework,那么这些命名空间中的许多将会看起来很熟悉,因为你习惯于在 .NET Framework 中使用它。

You will see the whole series of NuGet Package references. If you have worked in .NET Framework, then many of these namespaces will look familiar, because you are used to it by using in .NET Framework.

framework
Figure 1. NET Framework is split into many different pieces and re-implemented with CoreFx; these pieces are further distributed as individual packages.
  1. Now if you expand the NETStandard.Library, you will see addition references. You will even notice System.Console which we are using in this application.

  2. Now you don’t have to bring in everything inside the .NET Framework, but just bring in what you need for your application.

  3. There are some other benefits as well; for example, these modules can be updated individually if desired.

模块化具有性能优势,并且你的应用程序可以更快地运行,尤其是 ASP.NET Core 应用程序。

Modularity leads to performance benefits and your application can run faster, especially ASP.NET Core application.

.NET Core - Project Files

在本章中,我们将讨论 .NET Core 项目文件以及如何在项目中添加现有文件。

In this chapter, we will discuss .NET Core project files and how you can add existing files in your project.

让我们理解一个简单的例子。在该示例中,我们有某些已经创建的文件;我们必须在 FirstApp 项目中添加这些文件。

Let us understand a simple example in which we have some files which are already created; we have to add these files in our FirstApp project.

以下是 Student.cs 文件的实现。

Here is the implementation of the Student.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstApp {
   public class Student {
      public int ID { get; set; }
      public string LastName { get; set; }
      public string FirstMidName { get; set; }
      public DateTime EnrollmentDate { get; set; }
   }
}

以下是 Course.cs 文件的实现。

Here is the implementation of the Course.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstApp {
   public class Course {
      public int CourseID { get; set; }
      public string Title { get; set; }
      public int Credits { get; set; }
   }
}

现在让我们在磁盘和项目的源文件夹中保存这三个文件。

Let us now save these three files in your disk and the source folder of your project.

source folder
  1. Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio.

  2. You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files.

  3. One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project.

  4. We don’t have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio.

现在打开你的项目根目录。

Let us now open the root of your project.

root

将所有三个文件复制到项目根目录。

Let us now copy all of the three files into the root of your project.

project

你可以在根文件夹中看到所有复制的文件。

You can now see all the files copied to the root folder.

现在转到 Visual Studio,你会收到以下对话框。

Let us now go to Visual Studio; you will receive the following dialog box.

visual

单击 Yes to All 重新加载你的项目。

Click Yes to All to reload your project.

yes to all

现在,文件会被自动包含在你的项目中。

You will now that files are automatically included in your project.

.NET Core - Package References

在本章中,我们将讨论如何在 .NET Core 应用程序中添加包以及如何查找特定的包。我们可以直接转到 NuGet 并添加包,不过我们将在其他一些地方看到。

In this chapter, we will discuss how to add packages in your .NET Core application and how to find a specific package. We can directly go to NuGet and add package, but here we will see some other places.

现在让我们转到 .NET Core 的源代码,其位于此处 - https://github.com/dotnet/corefx

Let us now go to the source code of .NET Core which is located here − https://github.com/dotnet/corefx

source code

在 CoreFx 存储库中,打开 src 文件夹 -

In CoreFx repo, open the src folder −

corefx

你将看到一整套与不同程序包相对应的文件夹。我们现在搜索 Json -

And you will see the whole list of folders that correspond to different packages. Let us now search Json −

json

有一种方法可以查找软件包,如果您熟悉 .NET Framework,可能知道各种类型,但是 .NET Core 中的软件包组装完全不同,您不知道其中的软件包位于何处。

There is another way to find your package, you probably know various types if you are familiar with .NET Framework, but the assembling of packages in .NET Core is totally different and you won’t know where that packages in.

如果您知道类型,您可以使用 https://packagesearch.azurewebsites.net/ 搜索反向软件包搜索

If you know the type, you can search to reverse package search by using https://packagesearch.azurewebsites.net/

reverse package

在此处,您可以输入希望查找的任何类型的软件包。然后,此站点将扫描 NuGet 并为您找到相关软件包。

Here you can enter any type of package you would like to find. Then, this site will scan NuGet and find the relevant packages for you.

现在让我们搜索 DataContractJson

Let us now search for DataContractJson.

datacontractjson

您现在会看到,我们得到了相同的软件包;让我们单击软件包。

You will now see that we get the same package; let us click on the package.

package

您现在将看到 NuGet 页面;您需要确认需要此软件包。可以使用一些方法在应用程序中添加此软件包。

You will now see the NuGet page; you need to confirm that you need this package. You can add this in your application using a few methods.

让我们打开 project.json 文件。

Let us open the project.json file.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "emitEntryPoint": true
   },
   "dependencies": {
      "Microsoft.NETCore.App": {
         "type": "platform",
         "version": "1.0.1"
      }
   },
   "frameworks": {
      "netcoreapp1.0": {
         "imports": "dnxcore50"
      }
   }
}

这是新的项目格式,此文件内将看到依赖项部分。让我们如下所示添加新的依赖项。

This is the new project format and inside this file you will see the dependencies section. Let us add a new dependency as shown below.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "emitEntryPoint": true
   },
   "dependencies": {
      "Microsoft.NETCore.App": {
         "type": "platform",
         "version": "1.0.1"
      },
      "System.Runtime.Serialization.Json": "4.0.2"
   },
   "frameworks": {
      "netcoreapp1.0": {
         "imports": "dnxcore50"
      }
   }
}

现在,如果您查看引用,您将看到 System.Runtime.Serialization.Json 软件包添加到项目中。

Now if you look at your references, then you will see that System.Runtime.Serialization.Json package is added to your project.

run

另一种方式是转到 NuGet Manager 并浏览您要添加的软件包。

Another way is to go to the NuGet Manager and browse the package you want to add.

browse package

.NET Core - Create UWP App

在本章中,我们将讨论如何使用 .NET Core 创建 UWP 应用程序。UWP 也称为 Windows 10 UWP 应用程序。此应用程序不适用于以前版本的 Windows,只会适用于将来的 Windows 版本。

In this chapter, we will discuss how to create a UWP application using .NET Core. UWP is also known as Windows 10 UWP application. This application does not run on previous versions of Windows but will only run on future version of Windows.

以下是 UWP 将顺畅运行的一些例外情况。

Following are a few exceptions where UWP will run smoothly.

  1. If you want to run it locally you must have Windows 10, you can also develop on Windows 8 and then you will need to run it on Emulator, but it is encouraged to use Windows 10.

  2. For UWP application you will also need Windows 10 SDK. Let us open Visual Studio 2015 setup and then modify Visual Studio.

  3. On select features page, scroll down and you will see Universal Windows App Development Tools, check that option as shown below.

在这里,你可以看到 SDK 的不同版本以及工具的最新更新,单击“下一步”。

Here you can see the different versions of SDK and the latest update on Tools as well, click Next.

professional 2015

现在,单击 Install 按钮。

Now, click the Install button.

install button

安装完成后需要重新启动系统。

Once the installation is finished, you will need to restart your system.

setup completed

现在,让我们按照以下步骤实现 UWP。

Let us now implement the UWP by following these steps.

  1. First, launch Visual Studio 2015.

  2. Click on the File menu and select New → Project; a New Project dialog will show up. You can see the different types of templates on the left pane of the dialog box.

file menu
  1. In the left pane, you can see the tree view, now select Universal template from Templates → Visual C# → Windows.

  2. From the center pane, select the Blank App (Universal Windows) template.

  3. Give a name to the project by typing UWPFirstApp in the Name field and click OK.

uwpfirstapp
  1. The target version/minimum version dialog appears. The default settings are fine for this tutorial, so select OK to create the project.

default settings
  1. Here, we have a single project which can target all Windows 10 Devices, and you will notice that both .NET Core and UWP are simplification of multi-targeting.

  2. When a new project opens, its files are displayed on the right hand side of the Solution Explorer pane. You may need to choose the Solution Explorer tab instead of the Properties tab to see your files.

  3. Although the Blank App (Universal Window) is a minimal template, it still contains a lot of files. These files are essential to all UWP apps using C#. Every project that you create in Visual Studio contains the files.

  4. To see the running example, let us open MainPage.XAML and add the following code.

<Page
   x:Class = "UWPFirstApp.MainPage"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local = "using:UWPFirstApp"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable = "d">

   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <StackPanel HorizontalAlignment = "Center">
         <TextBlock Text = "Hello, world!"
            Margin = "20"
            Width = "200"
            HorizontalAlignment = "Left"/>
         <TextBlock Text = "Write your name."
            Margin = "20"
            Width = "200"
            HorizontalAlignment = "Left"/>
         <TextBox x:Name = "txtbox"
            Width = "280"
            Margin = "20"
            HorizontalAlignment = "Left"/>
         <Button x:Name = "button" Content = "Click Me"
            Margin = "20"
            Click = "button_Click"/>
         <TextBlock x:Name = "txtblock"
            HorizontalAlignment = "Left"
            Margin = "20"/>
      </StackPanel>
   </Grid>

</Page>

以下是 C# 中按钮的单击事件。

Below is the click event of button in C#.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;

using Windows.Foundation;
using Windows.Foundation.Collections;

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at
// http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace UWPHellowWorld {
   /// <summary>
   /// An empty page that can be used on its own or navigated to within a Frame.
   /// </summary>
   public sealed partial class MainPage : Page {
      public MainPage() {
         this.InitializeComponent();
      }
      private void button_Click(object sender, RoutedEventArgs e) {
         if (txtbox.Text != "")
            txtblock.Text = "Hello: " + txtbox.Text;
         else
            txtblock.Text = "You have not write your name";
      }
   }
}

现在让我们在本地机器上运行以上代码,你将看到以下窗口。现在在文本框中输入任意名称,然后按下 Click Me 按钮。

Let us now run the above code on the local machine and you will see the following window. Now type any name in the text box and press the Click Me button.

click me

.NET Core - MSBuild

在本章中,我们将讨论什么是 MSBuild,以及如何使用 .NET Core。MSBuild 是 Microsoft 和 Visual Studio 的构建平台。在 UWP 应用程序中,如果您打开项目文件夹,您将看到 project.json 和 *.csproj 文件。

In this chapter, we will discuss what is MSBuild and how it works with .NET Core. MSBuild is the build platform for Microsoft and Visual Studio. In UWP application if you open the project folder, then you will see both project.json and *.csproj files.

project json

但是,如果您打开我们以前的 .NET Core 控制台应用程序,您将看到 project.json 和 *.xproj 文件。

But if you open our previous .NET Core Console app, then you will see project.json and *.xproj files.

files
  1. The .NET Core build system or the project.json build system is not sufficient for UWP needs; this is why UWP is still using *.csproj (MSBuild) Build system.

  2. But project.json will move out as far as the build system is concerned.

  3. Now if you want to add a few existing files to your UWP application as we have added in the Console app, then you need to add those files in the project folder. Further, you will also need to include in your project in Solution Explorer as well.

现在,让我们考虑以下文件;将这些文件复制到您的项目文件夹。

Let us now consider the following files; copy these files to your project folder.

project folder
projects

让我们回到 Visual Studio 并打开解决方案资源管理器。

Let us go back to Visual Studio and open the Solution Explorer.

solution explorer
  1. You can now see that only copying files is not sufficient in case of UWP applications, because in Solution Explorer, we can’t see those files.

  2. Now we must include those files as well by clicking on the Show All Files icon as highlighted in the above screenshot and you will see now all files in the project folder.

show all files

这两个文件仍然未 включены в наш проект. Чтобы включить эти файлы, выберите эти файлы, щелкните правой кнопкой мыши по любому файлу, а затем выберите Include in Project .

These two files are still not included in our project. To include these files, select these files and right-click on any file and then select Include in Project.

include in project

Теперь эти файлы также включены. Одним из преимуществ, которое можно предвидеть, является подход project.json к удалению файлов для *.csproj в будущей версии инструментов SKD, а также в Visual Studio.

Now these files are also included. One good thing that can be foreseen is the project.json approach of dropping files for *.csproj in the future version of the SKD tools and also to Visual Studio.

.NET Core - Metapackage

В этой главе мы обсудим ссылки между нашим приложением Console и нашим приложением UWP. Если вы посмотрите на ссылки в обозревателе решений вашего приложения Console, вы увидите .NETCoreApp, как показано ниже.

In this chapter, we will discuss the references between our Console app and our UWP app. If you look at the References in Solution Explorer of your Console application, you will see the .NETCoreApp as shown below.

console application
uwp application
Figure 2. NETCoreApp is a new framework that targeted .NET Core application. Now if you look under the References of UWP application, it will look a bit different as shown below.
  1. The main reason for this is because here in UWP we have the *.csproj, so we are back to the old style of references and we can target only one framework with this project type.

  2. The references are similar though. You can now see that in UWP application, the Miscrosoft.NETCore.UniversalWindowsPlatform NuGet Package reference is similar to the Microsoft.NETCore.App NuGet reference in Console application.

  3. Both Miscrosoft.NETCore.UniversalWindowsPlatform and Microsoft.NETCore.App are meta-package which means that they are composed of other packages.

  4. In Console application, we can drill in and see other packages inside Microsoft.NETCore.App, but we can’t do the same Miscrosoft.NETCore.UniversalWindowsPlatform in Solution Explorer.

  5. However, we can use another tool, the NuGet Package Explorer to look at this. Let us now open this url in the browser − https://npe.codeplex.com/downloads/get/clickOnce/NuGetPackageExplorer.application and you will see a small utility downloading.

  6. Once downloading completes, then double-click on that file.

open file
  1. Click Install to start installation on the NuGet Package Explorer.

nuget package explorer
  1. When the installation is finished, you will see the following dialog box.

finished
  1. Let us now click on the Open a package from online feed option.

online feed
  1. By default it will search for the nuget.org feed. Let us now search for Microsoft.NETCore.UniversalWindowsPlatform in the search box and you will see 1 result as shown below.

nuget org feed
  1. Click the open link and it will open the top-level dependencies of this metapackage.

open link
  1. Let us now open the .NETCore meta package for the .NETCore application and meta-package for UWP application side by side.

meta package
  1. You can now see that each meta-package is composed of different set of packages.

  2. .NET Core is a subset of the classes available in .NET Framework at least at this point of time, but is growing and will be as per the base classes of .NET Framework.

  3. The UWP is based on .NET Core, it is a superset of the APIs available for Windows Store development.

Теперь у нас есть больше API, доступных для разработки благодаря .NET Core.

We now have more APIs available for development due to .NET Core.

Windows Runtime and Extension SDKs

Windows 运行时组件是自包含对象,你可以实例化并且能从任何语言使用,包括 C#、Visual Basic、JavaScript 和 C++。除了我们在上一章看到的 .NET Core 元包,UWP 应用程序默认还会引用通用的 Windows SDK。

Windows Runtime components are self-contained objects that you can instantiate and use from any language, including C#, Visual Basic, JavaScript, and C++. In addition to the .NET Core meta-package we saw in the previous chapter, UWP app also has a reference by default to a Universal Windows SDK.

universal windows sdk

通用 Windows 是对 Windows 运行时的引用,并且已分解成一系列 API 协定。

Universal Windows is the reference to Windows Runtime and it has been factored into a series of APIs contracts.

一个设备系列内的 API 集细分为称为 API 协定的子集。你可以在此处找到不同 API 协定的列表 https://msdn.microsoft.com/en-us/library/windows/apps/dn706135.aspx

The set of APIs within a device family is broken down into subdivisions known as API contracts. You can find a list of different API contracts here https://msdn.microsoft.com/en-us/library/windows/apps/dn706135.aspx

api

大多数 Windows 运行时内的 API 都分解到了一个单一的协定中。我们现在在 API 协定页面上搜索 Universal 关键字。

Most of those APIs inside windows runtime are factored into a single contract. Let us now search for the Universal keyword on the API Contracts page.

api contracts page

你可以看到指向各种 API 的链接,你也可以看到 Universal 系列如此庞大,包括 12 页文档。

You can see links to various APIs and you can also see the Universal family is so big that it has 12 pages of documentation.

你也可以在此页面搜索电话 API 协定。

You can also search for phone API contract on this page.

phone api

我们现在点击 Windows.Phone.PhoneContract 并向下滚动,你现在将看到电话或移动设备的电池信息。

Let us now click on the Windows.Phone.PhoneContract and scroll down; you will now see the battery information of phone or the mobile device.

battery information

如果你希望在你已经拥有的信息之上添加此信息,则应该手动添加引用。我们现在转到 Visual Studio,并且在解决方案资源管理器中右键单击引用。

If you want to add this information on top of what you already have, then you should add the references manually. Let us now go to the Visual Studio and right-click on the References in Solution Explorer.

选择 Add References…

Select Add References…

add references

你现在可以查看通用 Windows 的新引用类别,在此类别之下有 Core,它是指核心通用 Windows API 协定

You can now see the new reference category for Universal Windows; under this category there is Core which refers to the core Universal Windows API contracts

api contracts
  1. The Extensions allow us to extend the functionality and you will see different references Mobile, Desktop and other Extensions.

  2. There are different SKD extensions and you can add on top to get more APIs.

  3. You can also see different versions. So, make sure you get the latest version to get the updated APIs and then click OK.

updated apis

你现在可以看 Windows Mobile Extensions for the UWP 已作为引用添加。

You can now see that Windows Mobile Extensions for the UWP is added as reference.

.NET Core - Create .NET Standard Library

一个类库定义类型和方法,这些类型和方法可以从任何应用程序调用。

A class library defines the types and methods that can be called from any application.

  1. A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library.

  2. When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications.

让我们以在我们的控制台应用程序中添加一个类库项目作为开始,在解决方案资源管理器中右键单击 src 文件夹并且选择 Add → New Project…

Let us start by adding a class library project in our Console application; right-click on the src folder in Solution Explorer and select Add → New Project…

new project

Add New Project 对话框中选择 .NET Core 节点,然后选择类库(.NET Core)项目模板。

In the Add New Project dialog box, choose the .NET Core node, then choose the Class Library (.NET Core) project template.

在“名称”文本框中,输入“UtilityLibrary”作为项目名称,如下图所示。

In the Name text box, enter "UtilityLibrary" as the name of the project, as the following figure shows.

utilitylibrary

单击“确定”创建一个类库项目。在创建项目之后,我们添加一个新类。右键单击“解决方案资源管理器”中的 project 并选择 Add → Class…​

Click OK to create the class library project. Once the project is created, let us add a new class. Right-click on project in Solution Explorer and select Add → Class…​

class

在中间窗格中选择类并在“名称”和“字段”中输入StringLib.cs,然后单击 Add 。一旦添加了类,则替换StringLib.cs文件中的以下代码。

Select class in the middle pane and enter StringLib.cs in the name and field and then click Add. Once the class is added, then replace the following code in StringLib.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace UtilityLibrary {
   public static class StringLib {
      public static bool StartsWithUpper(this String str) {
         if (String.IsNullOrWhiteSpace(str))
         return false;
         Char ch = str[0];
         return Char.IsUpper(ch);
      }
      public static bool StartsWithLower(this String str) {
         if (String.IsNullOrWhiteSpace(str))
         return false;
         Char ch = str[0];
         return Char.IsLower(ch);
      }
      public static bool StartsWithNumber(this String str) {
         if (String.IsNullOrWhiteSpace(str))
         return false;
         Char ch = str[0];
         return Char.IsNumber(ch);
      }
   }
}
  1. The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively.

  2. In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric.

  3. On the menu bar, choose Build, Build Solution. The project should compile without error.

  4. Our .NET Core console project doesn’t have access to our class library.

  5. Now to consume this class library we need to add reference of this class library in our console project.

为此,请展开FirstApp,然后右键单击“引用”,最后选择 Add Reference…

To do so, expand FirstApp and right-click on References and select Add Reference…

firstapp

在“引用管理器”对话框中,选择我们的类库项目UtilityLibrary,然后单击 OK

In the Reference Manager dialog box, select UtilityLibrary, our class library project, and then click OK.

现在让我们打开控制台项目的Program.cs文件,并将所有代码替换为以下代码。

Let us now open the Program.cs file of the console project and replace all of the code with the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UtilityLibrary;

namespace FirstApp {
   public class Program {
      public static void Main(string[] args) {
         int rows = Console.WindowHeight;
         Console.Clear();
         do {
            if (Console.CursorTop >= rows || Console.CursorTop == 0) {
               Console.Clear();
               Console.WriteLine("\nPress <Enter> only to exit; otherwise, enter a string and press <Enter>:\n");
            }
            string input = Console.ReadLine();

            if (String.IsNullOrEmpty(input)) break;
            Console.WriteLine("Input: {0} {1,30}: {2}\n", input, "Begins with uppercase? ",
            input.StartsWithUpper() ? "Yes" : "No");
         } while (true);
      }
   }
}

现在让我们运行应用程序,您将看到以下输出。

Let us now run your application and you will see the following output.

application

为了更好地理解,让我们在您的项目中使用您的类库的其他扩展方法。

For better understanding, let us make use of the other extension methods of your class library in your project.

.NET Core - Portable Class Library

在本章中,我们将讨论什么是PCL(可移植类库),以及为什么我们需要PCL。为了理解此概念,让我们打开上一章中创建的类库项目文件夹。

In this chapter, we will discuss what is PCL (Portable Class Library), and also why we need PCL. To understand this concept, let us open the class library project folder which we have created in the previous chapter.

pcl

在该文件夹中,您会看到除了project.json和CS文件之外,我们还有一个*.xproj文件,原因在于Visual Studio将.NET Core项目类型设置为*.xproj,而不是*.csproj。

In this folder, you can see that in addition to project.json and CS files we also have *.xproj file, and that is because Visual Studio setup .NET Core project type as *.xproj instead of *.csproj.

如Microsoft指出的那样,.xproj将逐渐消失,但它仍保留在预览2版本工具中。正如我们所介绍的,UWP应用程序使用.csproj。

As mentioned by Microsoft, *.xproj will be going away, but it is still here in preview 2 tooling. As we have covered that UWP application uses the *.csproj.

tooling

现在实际上不可行的是引用*.xproj,而*.csproj也不会实现该功能,因为*.xproj将被淘汰。

Now it is actually not feasible to get *.csproj to reference and *.xproj and that functionality is not going to be implemented because *.xproj will move out.

所以,我们需要的是可以在控制台应用程序和UWP应用程序之间共享的类库,而PCL正是如此。

So instead, we need a class library which can be shared between the console app and the UWP app and here comes PCL.

What is PCL

现在让我们了解PCL是什么−

Let us now understand what PCL is −

  1. The Portable Class Library project enables you to write and build managed assemblies that work on more than one .NET Framework platform.

  2. You can create classes that contain code you wish to share across many projects, such as shared business logic, and then reference those classes from different types of projects.

  3. It can also help you build cross-platform apps and libraries for Microsoft platforms quickly and easily.

  4. Portable class libraries can help you reduce the time and costs of developing and testing code.

  5. Use this project type to write and build portable .NET Framework assemblies, and then reference those assemblies from apps that target multiple platforms such as Windows and Windows Phone, etc.

让我们现在从“解决方案资源管理器”中删除我们创建的类库。同时,从解决方案文件夹中将其删除,并进一步添加一个新项目项。

Let us now remove the class library which we have created from the Solution Explorer. At the same time, delete it from the Solution folder and further add a new project item.

remove

在左窗格中选择 Visual C# → Windows 模板,在中间窗格中选择“类库(可移植)”。

Select the Visual C# → Windows template in the left pane and select Class Library (Portable) in the middle pane.

在名称字段中输入 StringLibrary,然后单击 OK 以创建此项目。

Enter StringLibrary in the name field and click OK to create this project.

stringlibrary

现在,我们需要选择要引用的目标框架。让我们暂时选择 Windows Universal 和 ASP.NET Core,然后我们将重新定位它。单击 OK

Now we need to select the target frameworks to reference. Let us select Windows Universal and ASP.NET Core for a moment then we will retarget it. Click OK.

retarget

您会看到它已按 PCF 格式创建了一个新项目。让我们现在在“解决方案资源管理器”中右键单击 StringLibrary 项目并选择“属性”。

You can see that it has created a new project in PCF format. Let us now right-click StringLibrary project in the Solution Explorer and select Properties.

properties

单击“目标 .NET 平台标准”。

Click on the Target .NET Platform Standard.

target

单击”是“;现在与一个细微差别相同的类库。不同之处在于它也可以被 UWP 使用,因为它包含 *.csproj 文件,而不是 *.xproj。

Click Yes; it is now the same class library with one minor difference. The difference is that it can be used by UWP as well, because it contains *.csproj file instead of *.xproj.

class library

现在,让我们添加一个新类;为此,您需要右键单击“解决方案资源管理器”中的项目并选择 Add → Class…​

Let us now add a new class; for this, you need to right-click on project in Solution Explorer and select Add → Class…​

add new class

在中间窗格中选择“类”,在名称字段中输入 StringLib.cs ,然后单击 Add 。添加类后,替换 StringLib.cs 文件中的以下代码。

Select class in the middle pane and enter StringLib.cs in the name field and then Click Add. Once the class is added, then replace the following code in StringLib.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringLibrary {
   public static class StringLib {
      public static bool StartsWithUpper(this String str) {
         if (String.IsNullOrWhiteSpace(str))
            return false;
         Char ch = str[0];
         return Char.IsUpper(ch);
      }
      public static bool StartsWithLower(this String str) {
         if (String.IsNullOrWhiteSpace(str))
            return false;
         Char ch = str[0];
         return Char.IsLower(ch);
      }
      public static bool StartsWithNumber(this String str) {
         if (String.IsNullOrWhiteSpace(str))
            return false;
         Char ch = str[0];
         return Char.IsNumber(ch);
      }
   }
}

让我们构建这个可移植类库项目,它应该在没有错误的情况下编译。现在,我们需要在我们的控制台项目中添加这个可移植类库的引用。因此,展开 FirstApp,右键单击“引用”,然后选择 Add Reference…

Let us build this portable class library project and it should compile without error. Now we need to add reference of this portable class library in our console project. So, expand FirstApp and right-click on References and select Add Reference…

references

在“引用管理器”对话框中,选择我们可移植类库项目的 StringLibrary,然后单击 OK

In the Reference Manager dialog box, select StringLibrary which is our portable class library project, and then click OK.

library project

您会看到 StringLibrary 引用已添加到控制台项目中,而且在 project.json 文件中也可以看到。

You can see that the StringLibrary reference is added to the console project and it can be seen in the project.json file as well.

现在,您可以再次运行应用程序,您将看到相同的输出。

You can now run the application again and you will see the same output.

run application

现在让我们在您的项目中使用可移植类库的其他扩展方法。同一个可移植库也将被您的 UWP 应用程序使用。

Let us now use the other extension methods of your portable class library in your project. The same portable library will be consumed in your UWP application as well.

.NET Core - Adding References to Library

在本节中,我们将探讨如何向您的库添加引用。向库添加引用就像向其他项目(如控制台项目和 UWP 项目)添加引用一样。

In this chapter, we will discuss how to add references to your library. Adding references to library is like adding references to your other projects, like console project and UWP project.

uwp project

您现在可以看到,PCL 项目默认会带有一些引用。您也可以根据需要为应用程序添加其他引用。

You can now see that the PCL project has some references by default. You can also add other references as per your application need.

在 PCL 库中,您还可以看到 project.json 文件。

In the PCL library, you can also see the project.json file.

{
   "supports": {},
   "dependencies": {
      "NETStandard.Library": "1.6.0",
      "Microsoft.NETCore.Portable.Compatibility": "1.0.1"
   },
   "frameworks": {
      "netstandard1.3": {}
   }
}

向您的库添加引用的一个方法是直接在 project.json 文件中键入。正如您可以看到的,我们在依赖项部分中添加了一些引用,如下面的代码所示。

One method of adding references to your library is by typing it directly in the project.json file. As you can see that we have added some references under the dependencies section as shown in the following code.

{
   "supports": {},
   "dependencies": {
      "NETStandard.Library": "1.6.0",
      "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
      "System.Runtime.Serialization.Json": "4.0.3",
      "Microsoft.EntityFrameworkCore": "1.1.0"
   },
   "frameworks": {
      "netstandard1.3": {}
   }
}

我们现在保存此文件,您会看到已将引用添加到您的库中。

Let us now save this file and you will see that references are added to your library now.

references added

向您的库添加引用的另一个方法是使用 NuGet 包管理器。现在,让我们右键单击 StringLibrary (Portable) 项目并选择 Mange NuGet Packages…

The other method of adding references to your library is the NuGet Package Manager. Let us now right-click on the StringLibrary (Portable) project and select Mange NuGet Packages…

portable

在“浏览”选项卡上,您可以搜索任何 NuGet 包;就我们而言,我们希望添加“System.Runtime.Serialization.Primitives”包。

On the Browse tab, you can search any NuGet package; let us say we want to add “System.Runtime.Serialization.Primitives” package.

browse tab

单击 Install 按钮,它将显示以下屏幕。

Click the Install button, which will display the following screen.

press install

现在,单击 OK 按钮。

Now, click the OK button.

button

最后,单击 I Accept 按钮以开始安装此 NuGet 包。安装完成后,您会看到“System.Runtime.Serialization.Primitives”NuGet 包已添加到您的库中。

Finally, click the I Accept button to start installation of this NuGet package. Once installation is finished, then you will see that the “System.Runtime.Serialization.Primitives” NuGet package is added to your library.

installation

.NET Core - Sharing Libraries

在本节中,我们将探讨如何将您的库作为 NuGet Package 共享,以便在其他项目中使用。创建包从希望打包并与其他人共享的代码开始,可以通过公用 nuget.org 图库或组织内的专用 图库进行共享。包还可以包括其他文件,例如在安装包时显示的 readme ,并且可以对某些项目文件进行转换。

In this chapter, we will discuss how to share your library as NuGet Package so that it can be consumed within another project. Creating a package starts with the code you want to package and share with others, either through the public nuget.org gallery or a private gallery within your organization. The package can also include additional files such as a readme that is displayed when the package is installed, and can include transformations to certain project files.

现在,让我们考虑一个简单的示例,其中我们将从库中创建一个 NuGet 包。为此,请打开命令提示符并转到库项目的 project.json 文件所在的文件夹。

Let us now consider a simple example in which we will create a NuGet package from our library. To do so, open the command prompt and go to the folder where the project.json file of your library project is located.

example

现在,让我们运行以下命令。

Let us now run the following command.

dotnet help
command

最后,您可以看到诸如 new、restore 和 build 之类的不同命令。

At the end, you can see different commands like new, restore and build, etc.

最后一个命令是 pack; 这将创建一个 NuGet 包。现在,让我们执行以下命令。

The last command is pack; this will create a NuGet package. Let us now execute the following command.

dotnet pack
execute

您现在可以看到 NuGet 包已在 bin 文件夹中生成;让我们打开 bin\Debug 文件夹。

You can now see that the NuGet packages are produced in the bin folder; let us open the bin\Debug folder.

debug folder

现在的问题是 NuGet 包中包含什么内容,要了解这一点,我们可以使用 NuGet 包资源管理器。现在,让我们打开 NuGet 包资源管理器。

Now the question is what is inside the NuGet packages, to see that we can use NuGet Package Explorer. Let us now open the NuGet Package Explorer.

open nuget

选择第一个选项 Open a local package

Select the first option Open a local package.

first option

选择 StringLibrary.1.0.0.nupkg 并单击 Open

Select the StringLibrary.1.0.0.nupkg and click Open.

click ok

你可以在“程序包内容”部分中看到我们只包含了 StringLibrary.dll。在“程序包元数据”部分中,你将看到有关此程序包的一些信息,例如 Id、版本和所有依赖项。

You can see that in the Package contents section we have StringLibrary.dll only. In the Package metadata section, you will see a bit of information about this library like Id, Versions and all the of the dependencies.

我们现在打开 StringLibrary.1.0.0.symbols.nupkg

Let us now open the StringLibrary.1.0.0.symbols.nupkg.

symbols

在此 NuGet 程序包中,你会看到源文件以及 *.pdb 文件。如果你在 StringLib.cs 文件上双击,你还可以看到源代码。

In this NuGet package, you will see the source files and the *.pdb file as well. If you double-click on the StringLib.cs file, you see the source code as well.

stinglib cs

这里的问题是,如何配置元数据(例如版本、作者和描述)等。

Here the question is, how can configure the metadata like version, authors and description, etc.

project.json 文件用于 .NET Core 项目,目的是定义项目元数据、编译信息和依赖项。我们现在打开 project.json 文件,并添加以下额外信息。

The project.json file is used on .NET Core projects to define project metadata, compilation information, and dependencies. Let us now open the project.json file and add the following additional information.

{
   "authors": [ "Mark Junior" ],
   "description": "String Library API",
   "version" : "1.0.1-*",
   "supports": {},

   "dependencies": {
      "Microsoft.EntityFrameworkCore": "1.1.0",
      "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
      "NETStandard.Library": "1.6.0",
      "System.Runtime.Serialization.Json": "4.0.3",
      "System.Runtime.Serialization.Primitives": "4.3.0"
   },
   "frameworks": {
      "netstandard1.3": {}
   }
}

你现在可以看到其他信息,如作者名称、描述和此处添加的版本。我们保存此文件,构建程序包项目,然后再次执行“dotnet pack”命令。

You can now see additional information like author name, description and version added here. Let us save this file, build the library project, then execute the “dotnet pack” command again.

dotnet pack

在 bin\Debug 文件夹中,你可以看到 StringLibrary NuGet 程序包已使用 1.0.1 版本生成;我们已在 NuGet Package Explorer 中将其打开。

Inside the bin\Debug folder, you can see that the StringLibrary NuGet packages are produced with version 1.0.1; let us open it in NuGet Package Explorer.

version

你将看到更新的元数据。现在的问题是,我们如何在另一个程序包中使用它。

You will see the updated metadata. The question now is, how can we use it in another package.

我们需要先在 NuGet 源中发布它,然后我们才能在另一个项目中使用它。

We need to start by publishing somewhere in the NuGet feed and then we can consume it in another project.

发布更新的元数据有两种选择:

There are two options to publish the updated metadata −

  1. Publish it to nuget.org

  2. Push the metadata to private NuGet feed

此处我们将使用私有 NuGet 源,因为它比在 nuget.org 上设置帐户容易得多。要了解如何将包发布到 nuget.org,你可以按照此处 https://docs.microsoft.com/en-us/nuget/create-packages/publish-a-package 指定的所有准则进行操作。

Here we will be using the private NuGet feed because it is a lot easier than to setup an account on nuget.org. To learn how to publish your package to nuget.org, you can follow all the guidelines specified here https://docs.microsoft.com/en-us/nuget/create-packages/publish-a-package.

按照以下步骤将更新的元数据推送到私有 NuGet 源。

Follow these steps to push the updated metadata to private NuGet feed.

Step 1 - 首先,我们需要 nuget 命令行实用工具,并且我们必须将其安装。我们现在打开 NuGet Package Manager,并搜索 nuget.commandline。

Step 1 − To start with, we need the nuget commandline utility and we have to install it. Let us now open the NuGet Package Manager and search for nuget.commandline.

Step 2 - 选择 Nuget.Commandline,然后单击 Install

Step 2 − Select Nuget.Commandline and click Install.

commandline

Step 3 - 单击 OK 以安装 Nuget.Commandline。你还可以通过从以下网址 https://dist.nuget.org/index.html 下载它并设置环境变量来手动安装它。

Step 3 − Click OK to install Nuget.Commandline. You can also manually install it by downloading it from the following Url https://dist.nuget.org/index.html and then set up the environment variable.

manual install

Step 4 - 安装完成后,我们重新打开命令提示符并转到 bin\Debug 文件夹(NuGet 程序包位于此文件夹中),并指定以下命令:

Step 4 − Once the installation is finished, let us open the command prompt again and go to the bin\Debug folder where the NuGet packages are located and specify the following command −

nuget add StringLibrary.1.0.1.nupkg -Source D:\PrivateNugetPackages

Step 5 - 在以上命令中,我们将 StringLibrary.1.0.1.nupkg 程序包添加到我们的私有源,位置为 D:\PrivateNugetPackages , -Source 指定包源。

Step 5 − In the above command, we add the StringLibrary.1.0.1.nupkg package to our private feed and the location is D:\PrivateNugetPackages, -Source specifies the package source.

Step 6 - 你可以看到已安装 StringLibrary ;可以将 StringLibrary 进一步添加到私有源。

Step 6 − You can see that the StringLibrary is installed; the StringLibrary can further be added to the private feed.

private feed

Step 7 − 让我们转到该文件夹。

Step 7 − Let us go to that folder.

folder

Step 8 − 在 stringlibrary 文件夹的内部,你会看到另一个具有版本名称的文件夹,此处为 1.0.1。

Step 8 − Inside the stringlibrary folder, you will see another folder with the version name and here it is 1.0.1.

version name

NuGet 包位于此处。

The NuGet package is located here.

Creating a Xamarin.Forms Project

在本章中,我们将讨论如何使用已创建并发布到私有 NuGet 源的 NuGet 包。因此,我们首先将创建一个 Xamarin.Forms 项目。我们需要先了解什么是 Xamarin.Forms。

In this chapter, we will discuss how to consume the NuGet package which we have created and published to a private NuGet feed. So, first we will create a Xamarin.Forms project. We need to first understand what is Xamarin.Forms.

  1. Xamarin.Forms is a framework that allows developers to rapidly create crossplatform user interfaces.

  2. Xamarin.Forms is a cross-platform natively backed UI toolkit abstraction that allows developers to easily create user interfaces that can be shared across Android, iOS, Windows, and Windows Phone.

  3. The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the appropriate look and feel for each platform.

要启动 Xamarin.Forms,我们需要在 Visual Studio 2015 中一些附加功能。我们修改一下你的 Visual Studio 2015,并确保已选择了以下跨平台移动开发选项。

To start Xamarin.Forms, we need some additional features in Visual Studio 2015. Let us modify your Visual Studio 2015 and make sure the following cross-platform mobile development option is selected.

cross platform

完成安装后,我们通过选择 Tools → Options… 来更新 Xamarin

Once the installation is finished, let us update the Xamarin by selecting Tools → Options…

tools

向下滚动并展开左侧窗格中的 Xamarin,然后选择 Other 。在对话框的右上角,单击 Check Now 以查看是否有可用的更新。

Scroll down and expand Xamarin in the left pane and then select Other. On top right hand corner of the dialog box, click on Check Now to see if updates are available.

check now

你可以看到有可用的更新,我们单击 Download 按钮开始下载。下载完成后,你会收到安装更新的通知。

You can see that updates are available, let us click on the Download button to start downloading. Once downloading is finished, you will be notified to install the updates.

我们现在再次打开 Visual Studio,并选择 File → New → Project… 菜单选项。

Let us now open the Visual studio again and select the File → New → Project… menu option.

updates

在左侧窗格中,选择 Visual C# → Cross-Platform 模板,在中间窗格中,选择 Blank Xaml App (Xamarin.Forms Portable) 。在“名称”字段中输入名称,然后单击“确定”。

In the left pane, select the Visual C# → Cross-Platform template and in the middle pane, select Blank Xaml App (Xamarin.Forms Portable). Enter the name in the Name field and click OK.

blank xaml app

选择目标版本和最低版本并单击“确定”。

Select the Target Version and the Minimum Version and click OK.

target version

你会看到一系列项目;在顶部我们有 PCL 库,该库将在所有平台(如 Android、iOS、UWP、Windows 8.1 和 Windows Phone 8.1)间共享。

You will see a series of projects; at the top we have the PCL library which will be shared among all platforms like Android, iOS, UWP, Windows 8.1, and Windows Phone 8.1.

在此,我们将聚焦于 PCL 库,并将一些代码引入此处。让我们展开代码。

Here, we will focus on the PCL library and will bring some code here. Let us expand the code.

expand the code

在该 Xamarin.Forms 模板中,你可以看到通用 App.xaml 和 MainPage.xaml,它们使用了能在这些平台间工作的 Xamarin.Forms XAML 框架。

In this Xamarin.Forms template, you can see the generic App.xaml and MainPage.xaml, uses Xamarin.Forms XAML framework which works across these platforms.

我们需要导入我们的代码,而且我们还需要我们在上一章中设置的私有 NuGet 提供程序。

We need to import our codes and we also need the private NuGet feed we set up in the last chapter.

我们现在打开 NuGet 包管理器。单击包源下拉列表旁边的齿轮。

Let us now open the NuGet Package Manager. Click on the wheel next to the Package source dropdown list.

source

我们需要在此处添加我们的专用馈送,点按 plus (+) button

We need to add our private feed here, let us click on the plus (+) button.

plus
plus button

您将看到在 Available package sources 部分中添加了另一个复选框,让我们指定一个名称和源路径,然后点按 OK

You will see that another checkbox is added in the Available package sources section, let us specify a name and source path and click OK.

source path

让我们转到“浏览”选项卡,然后从“程序包源”下拉列表中选择“PrivateSource”,您将看到 StringLibrary NuGet 程序包。选择 StringLibrary,然后点按 Install

Let us now go to the Browse tab and select PrivateSource from the Package source dropdown list and you will see the StringLibrary NuGet package. Select StringLibrary and click Install.

select stringlibrary

点按“确定”,您将看到一个错误。

Click OK and you will see one error.

error

我们无法使用 .NETPortable 配置文件版本 259 的库,我们将在下一章中修复此错误。

We can’t use library with .NETPortable profile version 259, we will be fixing this error in the next chapter.

fixing

.NET Core - PCL Troubleshooting

在本章中,我们将修复在 Xamarin.Forms 项目中从我们的专用馈送安装 NuGet 程序包时遇到的错误。

In this chapter, we will be fixing the error we got while installing the NuGet package from our private feed in Xamarin.Forms project.

fixing error

我们将进一步简要了解问题。首先,让我们右键单击 PCL 库并选择“属性”。

We will further understand the problem in brief. To start with, let us right-click on the PCL library and select Properties.

在此页面上,您将看到所有目标框架系列。从错误中,您会看到 .NETPortable 配置文件 259 与我们的 StringLibrary 1.0.1 不兼容。但是,它试图从 .NET Standard 1.1 库获取引用。

On this page, you will see the whole series of frameworks targeted. From the error, you can see that the .NETPortable profile 259 is not compatible with our StringLibrary 1.0.1. However, it is trying to take reference from the .NET Standard 1.1 library.

compatible

现在让我们查看 .NET Standard 库并确定哪个平台与我们的库不兼容。

Let us now see the .NET Standard Library and identify which platform is not compatible with our library.

platform

您可以看到 Windows Phone Silverlight 8 与 .NET Standard 1.0 兼容。如果您打开以下网页,您将看到 Profile259 只能支持 .NET Standard 1.0。

You can see that Windows Phone Silverlight 8 is compatible with .NET Standard 1.0. If you open the following webpage, then you will see that Profile259 can support only .NET Standard 1.0.

profile259

现在让我们取消选中 Windows Phone Silverlight 8。

Let us now uncheck Windows Phone Silverlight 8.

silverlight

单击 OK 按钮。

Click the OK button.

ok button

现在,要修复此问题,请点按“确定”,取消“更改目标”对话框,然后打开程序包管理器控制台,并执行以下命令。

Now to fix this issue click OK and cancel the Change Targets dialog and then open Package Manager Console and execute the following command.

PM > Uninstall-Package Xamarin.Forms
execute command

现在让我们转到 PCL 库的“属性”。点按“更改”按钮。

Let us now go to the Properties of PCL library. Click on the Change button.

pcl library

取消选中 Windows Phone Silverlight 8,然后点按“确定”。

Uncheck Windows Phone Silverlight 8 and Click OK.

uncheck

您现在可以看到,Windows Phone Silverlight 8 不再出现在“目标框架”中了。您还可以看到当前目标的配置文件。要看到此内容,让我们卸载 PCL 库并编辑 XamarinApp.csproj 文件。

You can now see that Windows Phone Silverlight 8 is no longer available in Targeted framework. You can also see the profile that is the target now. To see this, let us unload the PCL library and edit the XamarinApp.csproj file.

unload

您现在可以看到,TargetFrameworkProfile 现在是 Profile111。

You can see now that TargetFrameworkProfile is now Profile111.

targetframeworkprofile

如果您打开文档,您将看到 Profile111 支持 .NET Standard 1.1。

If you open the documentation, then you will see that Profile111 is supporting .NET Standard 1.1.

documentation

现在,让我们重新加载 PCL 并打开 NuGet 程序包管理器,然后尝试从专用馈送安装 StringLibrary 程序包。

Let us now reload the PCL again and open the NuGet Package Manager and try to install the StringLibrary package from private feed.

package private feed

从“依赖关系行为”下拉列表中,选择“忽略依赖关系”,然后点按 Install

From the Dependency behavior dropdown list, select Ignore Dependencies and then click Install.

dependencies

您可看到 StringLibrary 包已从专用源进行安装。如果您展开 PCL 的引用,您将看到 StringLibrary 引用也按以下所示添加进来。

You can see that the StringLibrary package is now installed from the private feed. If you expand the References of PCL, then you will see that the StringLibrary reference is also added as shown below.

pcl reference

我们已针对 Windows Phone Silverlight 8 问题卸载了 Xamarin.Forms。需要重新安装 Xamarin.Forms。建议安装相同版本。

We had uninstalled the Xamarin.Forms for the Windows Phone Silverlight 8 issue. The Xamarin.Forms needs to be installed again. It is recommended that the same version is installed.

same version

一旦完成安装,让我们在您的应用程序中使用 StringLibrary 功能。

Once the installation completes, let us use the StringLibrary functionality in your application.

.NET Core - Create a Testing Project

在本章中,我们将讨论如何使用 .NET Core 创建测试项目。单元测试是一个软件开发过程,其中包括应用程序中最小的可测试部分,即单元。它们会被单独独立地进行检查,以了解操作是否正确。单元测试可以自动化,也可以手动进行。

In this chapter, we will discuss how to create a Testing project using .NET Core. Unit testing is a development process for the software that has the smallest testable parts of an application, which are called units. They are individually and independently scrutinized for any proper operation. Unit testing is can either be automated or done manually as well.

现在打开“新建项目”对话框并选择 Visual C# → .NET Core 模板。

Let us now open the New Project dialog box and select Visual C# → .NET Core template.

visual csharp

在此对话框中,您可以看到没有用于单元测试的项目模板。为了创建单元测试项目,我们应该使用命令行实用工具。我们进入刚才创建的解决方案文件夹;创建一个测试文件夹并在测试文件夹内创建一个新文件夹并将其命名为 StringLibraryTests

On this dialog box, you can see that there is no project template for unit testing. To create a unit test project, we should use the command line utility. Let us go to the Solution folder that we created; create a test folder and inside the test folder create another folder and call it StringLibraryTests.

stringlibrarytests

现在,让我们使用 dotnet 命令行实用工具执行以下命令来新建一个测试项目:

Let us now use the dotnet commandline utility to create a new test project by executing the following command −

dotnet new -t xunittest

您现在可以看见创建了一个新的 C# 项目;让我们执行 v 命令查看此文件夹,您将看到 project.jsonTests.cs 文件,如下图所示。

You can now see that a new C# project is created; let us look into the folder by executing the v command and you will see project.json and Tests.cs files as shown below.

dir command

以下是 project.json 文件中的代码。

Here is the code in project.json file.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "debugType": "portable"
   },
   "dependencies": {
      "System.Runtime.Serialization.Primitives": "4.1.1",
      "xunit": "2.1.0",
      "dotnet-test-xunit": "1.0.0-rc2-192208-24"
   },
   "testRunner": "xunit",
   "frameworks": {
      "netcoreapp1.0": {
         "dependencies": {
            "Microsoft.NETCore.App": {
               "type": "platform",
               "version": "1.0.1"
            }
         },
         "imports": [
            "dotnet5.4",
            "portable-net451+win8"
         ]
      }
   }
}

以下是 Test.cs 文件中的代码。

Following is the code in the Test.cs file.

using System;
using Xunit;
namespace Tests {
   public class Tests {
      [Fact]
      public void Test1() {
         Assert.True(true);
      }
   }
}

要从 NuGet 获取必需的依赖项,让我们执行以下命令:

To fetch the necessary dependencies from NuGet, let us execute the following command −

dotnet restore

当还原必需的依赖项后,我们就可以运行该测试。

We can run the test when the necessary dependencies are restored.

restored

您可看到编译成功;向下看可以看到有关执行的测试的一些信息。

You can see that the compilation succeeded; as you go down you can see some information about the test executed.

test executed

当前,我们执行了 1 个测试,0 个错误,0 个失败,0 个跳过,执行过程耗费的时间也列为信息。

Currently we have 1 test executed, 0 error, 0 failed, 0 skipped and the time taken by the execution process also mentioned as information.

.NET Core - Running Tests in Visual Studio

在本章中,我们将讨论如何在 Visual Studio 中运行测试。.NET Core 的设计考虑了可测试性,因此为应用程序创建单元测试比以往任何时候都更容易。在本章中,我们将在 Visual Studio 中运行和执行我们的测试项目。

In this chapter, we will discuss how to run tests in Visual Studio. The .NET Core has been designed with testability in mind, so that creating unit tests for your applications is easier than ever before. In this chapter, we will run and execute our test project in Visual Studio.

让我们在 Visual Studio 中打开 FirstApp 解决方案。

Let us open the FirstApp solution in Visual Studio.

firstapp solution

您会看到它只有两个项目,并且您将看不到测试项目,因为我们尚未在解决方案中添加该项目。

You can see that it has only two projects and you will not be able to see the test project because we haven’t added that project in our solution.

让我们先添加一个文件夹,并称其为 test

Let us add a folder first and call it test.

test

右键单击 test 文件夹。

Right-click on the test folder.

test folder

选择 project.json 文件,然后单击 Open

Select project.json file and click Open.

project json file

以下屏幕截图显示 Tests.cs 文件中的代码作为输出。

The following screenshot shows the code in Tests.cs file as output.

tests

这是默认实现,它仅仅测试 True 是否等于 true。它基于 xUnit 测试框架,你会看到一个注解和表示测试方法的 Fact 特性。

It is the default implementation and it is just testing that True is equal to true. It is the xUnit testing framework and you will see the Fact attribute that annotates and denotes the test method.

using System;
using Xunit;

namespace Tests {
   public class Tests {
      [Fact]
      public void Test1() {
         Assert.True(true);
      }
   }
}

以下是 project.json 文件的实现。

Following is the implementation of project.json file.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "debugType": "portable"
   },
   "dependencies": {
      "System.Runtime.Serialization.Primitives": "4.1.1",
      "xunit": "2.1.0",
      "dotnet-test-xunit": "1.0.0-rc2-192208-24"
   },
   "testRunner": "xunit",
   "frameworks": {
      "netcoreapp1.0": {
         "dependencies": {
            "Microsoft.NETCore.App": {
               "type": "platform",
               "version": "1.0.1"
            }
         },
         "imports": [
            "dotnet5.4",
            "portable-net451+win8"
         ]
      }
   }
}

project.json 文件中,对测试框架最重要的依赖项是 xunit,该依赖项引入了 Fact 特性。它引入了 xunit 的测试框架和用于测试的 API。

In project.json file, the most important dependency to the testing framework is the xunit, which brings in the Fact attribute. It brings in the testing framework and APIs for testing with xunit.

我们还有 dotnet-test-xunit ,这是一款适配器,以便 xunit 能够与 .NET Core 协同工作,特别是与 dotnet test 命令行实用工具协同工作。接下来,你会看到将运行 xunit 的 testRunner 以及 netcoreapp1.0 框架。

We also have the dotnet-test-xunit, this is an adopter so that xunit can work with .NET Core, specifically with dotnet test command line utility. Then you will see the testRunner which will run xunit and you can also see the netcoreapp1.0 framework.

你将在下面看到 .NETCore.App 依赖项。

You will see the .NETCore.App dependeny below.

若要在 Visual Studio 中运行测试,让我们从 Test → Window → Test Explorer 菜单选项中打开测试浏览器。

To run test in Visual Studio, let us open Test Explorer from the Test → Window → Test Explorer menu option.

test explorer

你可以看到,Visual Studio 会自动检测测试。测试名称包含 namespace.className.TestMethodName 。现在,让我们单击 Run All button in Test Explorer

And you can see that Visual Studio automatically detects the test. The name of the test consists of namespace.className.TestMethodName. Let us now click on Run All button in Test Explorer.

run all button

它会首先构建代码,然后运行测试,并且你会看到测试花费的总时间。让我们更改测试方法,以便测试失败时我们能看到输出。

It will first build the code and the run the test and you will see the total time taken by the test. Let us change the test method so that we can see the output when the test fails.

using System;
using Xunit;

namespace Tests {
   public class Tests {
      [Fact]
      public void Test1() {
         Assert.True(false);
      }
   }
}

让我们通过单击 Run All 按钮链接再次执行测试。

Let us execute the test again by clicking on the Run All button link.

run all

你现在可以看到 test 故障。

You can now see the test failure.

.NET Core - Testing Library

在本章中,我们将测试 StringLibrary,为此,我们需要重新排列我们的项目,以便按照默认惯例进行。

In this chapter, we will test our StringLibrary and to do so, we need to rearrange our projects so that we can follow the default convention.

打开 global.json 文件。

Let us open the global.json file.

{
   "projects": [ "src", "test" ],
   "sdk": {
      "version": "1.0.0-preview2-003131"
   }
}

你将在该文件的顶部看到项目设置,它默认设置了一些文件夹,例如 srctest

At the top of this file you will see the project settings and it sets up some folder such as src and test by default.

按照惯例,我们必须在这些文件夹中保存项目,这是新惯例,将用作 .NET Core 的一部分。

As by convention we must have projects in these folders, this is the new convention and that is going to be used as part of .NET Core.

在解决方案资源管理器中,你可以看到控制台项目和库项目都在 src 文件夹中,而测试项目在 test 文件夹中。

In the Solution Explorer, you can see that both the console project and the library project are inside the src folder while the Testing project is inside test folder.

src folder

解决方案资源管理器中的项目结构不代表项目在磁盘上的实际位置。打开解决方案文件夹,你会看到 StringLibrary 项目不在 src 文件夹中。

And the projects structure in Solution Explorer doesn’t represent where the projects physically exist on the disk. Let us now open the Solution folder and you will see that StringLibrary project is not inside the src folder.

stringlibrary project

你可以看到 srctest 文件夹都映射到 global.json 文件中指定的惯例。但是,我们有一个 StringLibrary 项目不符合惯例。现在将 StringLibrary 项目添加到 src 文件夹中。

You can see that both src and test folders map to the convention specified in the global.json file. However, we have one project StringLibrary which is out of convention. Let us now add the StringLibrary project inside the src folder.

在 src 文件夹中,我们有两个项目,我们需要修复问题,以便我们可以正确使用所有项目。回到 Visual Studio,右键单击 StringLibrary 项目,并选择“删除”选项。它不会删除它,只会删除项目。

In the src folder, we have two projects and we need to fix the problem so that we can use all the projects properly. Let us go back to the Visual Studio and right-click on the StringLibrary project and select the Remove option. It won’t delete it, but it will only remove the project.

remove project

现在,右键单击 src 文件夹,并选择 Add → Existing Project…

Now right-click on the src folder and select Add → Existing Project…

src

浏览到 StringLibrary 项目,该项目现位于 src 文件夹内,选择 StringLibrary.csproj 文件并单击 Open

Browse to the StringLibrary project which is now inside the src folder, select the StringLibrary.csproj file and click Open.

stringlibrary csproj

现在我们必须移除 StringLibrary 的引用,该引用来自控制台应用程序的 project.json 文件。

We now have to remove the reference of StringLibrary from the project.json file of the console app.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "emitEntryPoint": true
   },
   "dependencies": {
      "Microsoft.NETCore.App": {
         "type": "platform",
         "version": "1.0.1"
      },
      "NuGet.CommandLine": "3.5.0",
      "System.Runtime.Serialization.Json": "4.0.3"
   },
   "frameworks": {
      "netcoreapp1.0": {
         "dependencies": { },
         "imports": "dnxcore50"
      }
   }
}

保存更改,然后再次在控制台项目中添加 StringLibrary 的引用。

Save the changes and then add a reference of StringLibrary again in your console project.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "emitEntryPoint": true
   },
   "dependencies": {
      "Microsoft.NETCore.App": {
         "type": "platform",
         "version": "1.0.1"
      },
   "NuGet.CommandLine": "3.5.0",
      "System.Runtime.Serialization.Json": "4.0.3"
   },
   "frameworks": {
      "netcoreapp1.0": {
         "dependencies": {
            "StringLibrary": {
               "target": "project"
            }
         },
         "imports": "dnxcore50"
      }
   }
}

现在一切应该恢复正常,你可以构建 StringLibrary ,然后构建 FirstApp (控制台项目),而不会出现任何错误。现在让我们使用 xunit 来测试 StringLibrary 功能。我们需要将 StringLibrary 引用添加到我们的测试项目中。右键单击 StringLibraryTests 项目的引用,然后选择添加引用…

Now everything should be working again and you can build StringLibrary and then FirstApp (console project) without any error. Let us now test the StringLibrary functionality using xunit. We need to add reference of StringLibrary into our testing project. Right-click on the References of StringLibraryTests project and select Add Reference…

add

单击 OK ,这会向我们的测试项目添加 StringLibrary 的引用。现在让我们替换 Tests.cs 文件中的以下代码。

Click OK which will add a reference of StringLibrary to our testing project. Let us now replace the following code in the Tests.cs file.

using System;
using Xunit;
using StringLibrary;

namespace Tests {
   public class Tests {
      [Fact]
      public void StartsWithUpperCaseTest() {
         string input = "Mark";
         Assert.True(input.StartsWithUpper());
      }
      [Fact]
      public void StartsWithLowerCaseTest() {
         string input = "mark";
         Assert.True(input.StartsWithLower());
      }
      [Fact]
      public void StartsWithNumberCaseTest() {
         string input = "123";
         Assert.True(input.StartsWithNumber());
      }
   }
}

你可以看到我们有三个测试方法,它们会测试 StringLibrary 的功能。让我们单击 Run All 链接,你将在测试资源管理器中看到以下输出。

You can see that we have three test methods which will test the functionality of StringLibrary. Let us click the Run All link and you will see the following output in Test Explorer.

run all link

你还可以从命令行运行测试。让我们打开命令提示符并执行 dotnet test 命令。

You can also run the tests from the command line. Let us open the command prompt and execute the dotnet test command.

dotnet test

Managed Extensibility Framework

在本章中,我们将讨论可托管扩展框架 (MEF)。MEF 可用于第三方插件扩展,或者它可以为常规应用程序带来松散耦合的插件式架构的优势。

In this chapter, we will discuss the Managed Extensibility Framework (MEF). MEF can be used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to regular applications.

  1. MEF is a library for creating lightweight, extensible applications.

  2. It allows application developers to discover and use extensions with no configuration required.

  3. MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used that improves the flexibility, maintainability and testability of large applications.

  4. You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET.

  5. MEF has been ported as Microsoft.Composition to .NET Core as well but partially.

  6. Only System.Composition is ported, and System.ComponentModel.Composition is not available yet. This means, we don’t have the catalogs which can load types from assemblies in a directory.

在本章中,我们将仅了解如何在 .NET Core 应用程序中使用 MEF。

In this chapter, we will only learn how we can use MEF in .NET Core application.

让我们了解一个简单的示例,其中我们将在 .NET Core 控制台应用程序中使用 MEF。现在,让我们创建一个新的 .NET Core 控制台项目。

Let us understand a simple example in which we will use MEF in .NET Core console application. Let us now create a new .NET Core console project.

在左窗格中,选择 Templates → Visual C# → .NET Core,然后在中间窗格中,选择控制台应用程序 (.NET Core)。

In the left pane, select Templates → Visual C# → .NET Core and then in the middle pane, select Console Application (.NET Core).

在名称字段中输入项目的名称,然后单击确定。

Enter the name of the project in the Name field and click OK.

name field

创建项目后,我们需要添加对 Microsoft.Composition 的引用,以便我们能够使用 MEF。为此,让我们在解决方案资源管理器中右键单击该项目并 Manage NuGet Packages…

Once the project is created, we need to add reference of Microsoft.Composition so that we can use MEF. To do so, let us right-click on the project in Solution Explorer and Manage NuGet Packages…

搜索 Microsoft.Composition ,然后单击 Install

Search for Microsoft.Composition and click Install.

manage

单击 OK 按钮。

Click the OK button.

click the button

单击 I Accept 按钮。

Click the I Accept button.

accept

当安装完成后,您将在“引用”中发现一个错误。

When the installation completes, you will find an error in References.

error references

让我们打开 project.json 文件。

Let us open the project.json file.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "emitEntryPoint": true
   },

   "dependencies": {
      "Microsoft.Composition": "1.0.30",
      "Microsoft.NETCore.App": {
         "type": "platform",
         "version": "1.0.1"
      }
   },

   "frameworks": {
      "netcoreapp1.0": {
         "imports": "dnxcore50"
      }
   }
}

您会看到已添加了 Microsoft.Composition 依赖项,但问题是此程序包与 dnxcore50 不兼容。因此,我们需要导入 portablenet45+win8+wp8+wpa81 。现在,让我们用以下代码替换 project.json 文件。

You can see that the Microsoft.Composition dependency is added, but the problem is that this package is not compatible with dnxcore50. So we need to import portablenet45+win8+wp8+wpa81. Let us now replace your project.json file with the following code.

{
   "version": "1.0.0-*",
   "buildOptions": {
      "emitEntryPoint": true
   },
   "dependencies": {
      "Microsoft.Composition": "1.0.30",
      "Microsoft.NETCore.App": {
         "type": "platform",
         "version": "1.0.1"
      }
   },
   "frameworks": {
      "netcoreapp1.0": {
         "imports": "portable-net45+win8+wp8+wpa81"
      }
   }
}

保存此文件,您将看到该错误已纠正。

Save this file and you will see that the error is rectified.

rectified

如果您展开“引用”,就会看到 Microsoft.Composition 的一个引用。

If you expand the References, then you will see a reference of Microsoft.Composition.

microsoft composition

首先,我们需要创建一个要导出的接口,然后实现该接口并将该类装饰为导出属性。现在,让我们添加一个新类。

First we need to create an interface that is to be exported and implement the interface and decorate the class with the export attribute. Let us now add a new class.

在“名称”字段中输入您类的名称,然后单击 Add

Enter the name for your class in the Name field and click Add.

click add

让我们在 PrintData.cs 文件中添加以下代码。

Let us add the following code in the PrintData.cs file.

using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;

namespace MEFDemo {
   public interface IPrintData {
      void Send(string message);
   }
   [Export(typeof(IPrintData))]
   public class PrintData : IPrintData {
      public void Send(string message) {
         Console.WriteLine(message);
      }
   }
}

如上所述,在 Microsoft.Composition 命名空间中不提供目录。因此,它会加载装配中具有导出属性的所有类型,并将它们附加到导入属性中,如 Program.cs 文件中的 Compose 方法中所示。

As mentioned above, Catalogs are not available in Microsoft.Composition namespace. So, it will load all the types from the Assembly with export attribute and attach to the import attribute as shown in the Compose method in the Program.cs file.

using System;
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace MEFDemo {
   public class Program {
      public static void Main(string[] args) {
         Program p = new Program();
         p.Run();
      }
      public void Run() {
         Compose();
         PrintData.Send("Hello,this is MEF demo");
      }
      [Import]
      public IPrintData PrintData { get; set; }

      private void Compose() {
         var assemblies = new[] { typeof(Program).GetTypeInfo().Assembly };
         var configuration = new ContainerConfiguration()
            .WithAssembly(typeof(Program).GetTypeInfo().Assembly);

         using (var container = configuration.CreateContainer()) {
            PrintData = container.GetExport<IPrintData>();
         }
      }
   }
}

现在,让我们运行您的应用程序,您将看到它正在通过实例化 PrintData 类来运行。

Let us now run your application and you will see that it is running by instantiating the PrintData class.

printdata

要详细了解 MEF,让我们访问以下网址 https://msdn.microsoft.com/en-us/library/dd460648%28v=vs.110%29.aspx ,了解更多详情。

To learn more about MEF, let us visit the following Url https://msdn.microsoft.com/en-us/library/dd460648%28v=vs.110%29.aspx for more details.

.NET Core - SDK

在本章中,我们将了解 .NET Core 中的即将推出的功能。我们将通过在浏览器中打开以下网址来开始使用 .NET 命令行工具 https://github.com/dotnet/cli

In this chapter, we will understand the upcoming features in .NET Core. We will start with the .NET command line tools by opening the following Url in browser https://github.com/dotnet/cli

url

如需了解有关进度的更多信息,您可以向下滚动并下载最新版本的 .NET Core SDK,您将看到安装器和二进制文件部分。

To know more about the progress, you can download the latest version of .NET Core SDK by scrolling down and you will see the Installer and Binaries section.

binaries section

您可以看到针对不同操作系统的最新预览工具版本,让我们根据您的操作系统选择安装器。

You can see the latest version of preview tools for different operating systems, let us select the Installer as per your operating system.

我们正在研究 .NET Core 2.0 的预览 1。

We are working on preview 1 of .NET Core 2.0.

现在,让我们查看我们的当前工具,为此打开命令提示符并执行以下命令。

Let us now look at our current tooling by opening the command prompt and execute the following command.

dotnet --info

您将在您的系统中看到有关当前安装的 .NET 命令行工具版本的如下信息。

You will see information about the currently installed version of .NET Command Line Tools on your system as shown below.

command line tools

您能看到当前我们有 preview2 工具。我们现在运行以下命令,以查看 new 命令。

You can see that currently we have preview 2 tooling. Let us now run the following command to see about the new command.

dotnet help new

对于项目的新的命令语言,您可以选择如 C# 和 F# 以及项目的类型等。

For new command language of project, you can select like C# and F# and the type of project, etc.

project type

我们现在来看一下 .NET Core 最新版本的更改。一旦下载了安装程序,双击以安装它。单击“安装”。

Let us now see the changes in the latest version of .NET Core. Once the installer is downloaded, double-click on it to install it. Click on Install.

installer

以下屏幕截图显示了安装过程。

The following screenshot shows the installation process.

process

它将会开始安装过程。一旦安装完成,关闭此对话。

It will start the installation process. One the installation is finished, Close this dialog.

installation finished

打开命令提示符并执行以下命令。

Open the command prompt and execute the following command.

dotnet --info

您将会看到如下所示您的系统中当前安装的 .NET 命令行工具的版本信息。

You will see information of currently installed version of .NET Command Line Tools on your system as shown below.

tools on system

您现在能看到我们有 .NET Core 2 的 preview1 工具。我们现在在命令提示符中运行以下代码,以了解 .NET Core 2 preview1 中的新命令。

You can now see that we have preview1 tooling of .NET Core 2. Let us now run the following code in the command prompt to see about the new command in .NET Core 2 preview1.

dotnet help new

该命令会帮助您将包以及包缓存下载到中。

The command helps you download packages as well to the package cache.

package cache

该命令打开以下网页,其中包含 .NET Core 2 preview1 中有关新命令的信息。

The command opens the following webpage which contains information about the new command in .NET Core 2 preview1.

preview1

我们向下滚动,您现在可以看到我们可以使用更多的模板创建 .NET Core 应用程序。

Let us scroll down, you can now see that we can create the .NET Core application with more templates.

templates

我们现在可以使用命令行来创建 mstest, web, mvcwebapi 项目。

We can now create mstest, web, mvc and webapi projects as well using the command line.

.NET Core - MSBuild and project.json

NET Core 已经决定放弃 project.json 而返回到 MSBuild 和 *.csproj。这是已经发生在刚刚发布的 .Net Core 2.0 preview1 工具中。这样做多少有些令人失望,因为 project.json 带来了一股清新的空气。但这是可以理解的,并且也拥有许多优势。

The .NET Core has decided to drop project.json and go back to MSBuild and *.csproj. This is something that’s already happened in the just released .Net Core 2.0 preview1 tooling. This is fairly disappointing, because the project.json was a breath of fresh air. However, it is understandable and have many advantages as well.

我们现在来讨论这一变更带来的优势 −

Let us now discuss the advantages that the change brings in −

  1. It would make the transition of the existing Visual Studio solutions to .NET Core straightforward.

  2. It is a huge change and it will also enable leveraging existing investment in CI/RM based around MSBuild.

  3. During build in MSBuild, we can think of incremental compilation, resolving buildtime dependencies, configuration management, etc.

  4. A lot of work is required to ship dotnet cli on time, because it is no longer just about ASP.NET Core, but also console apps, UWP apps, etc.

以下是 MSBuild 和 *.csproj 中的更改 −

Following are the changes in MSBuild and *.csproj −

  1. Project.json file (.xproj) will be replaced by MSBuild (.csproj).

  2. Features in project.json will start getting merged back into the the *.csproj.

  3. It is not yet clear what they are going to do about the packages list, but it was mentioned they might keep it as json under nuget.json or merge it into the *.csproj.

  4. Supposedly that transition should be smooth and potentially automatic if using Visual Studio.

Advantages of MSBuild

  1. MSBuild is open source and available on GitHub and is bound to become fully crossplatform.

  2. MSBuild will dramatically simplify and trim the structure of the *.csproj.

  3. Microsoft is also introducing a new project system which will enable a lot of scenarios without the need for Visual Studio and the details are given on the this Url https://github.com/dotnet/roslyn-project-system/.

  4. The goal is that even with the MSBuild setup, working with builds and project will be as seamless in Visual Studio IDE as outside of it.

MSBuild vs project.json

现在通过执行以下命令使用 .NET Core preview2 工具包创建新的控制台项目。

Let us now create a new console project with .NET Core preview2 tooling by executing the following command.

dotnet new -t console

要查看在此项目中创建的所有文件,请运行 dir 命令。

To see all the files created within this project, run the dir command.

run dir

你可以看到创建了两个文件,即 Program.csproject.json 文件。

You can see that two files are created, Program.cs and project.json file.

现在通过执行以下命令使用 .NET Core 2 preview1 工具包创建一个控制台应用程序。

Let us now create a console app with .NET Core 2 preview1 tooling by executing the following command.

dotnet new console

要查看在此项目中创建的所有文件,请运行 dir 命令。你可以看到创建了三个文件,即 Program.cs, NuGet.configMSBuild.csproj ,而不是 project.json 文件。

To see all the files created within this project, run the dir command. You can see that three files are created, Program.cs, NuGet.config and MSBuild.csproj instead of the project.json file.

console

现在让我们并排比较 project.jsonMSBuild.csproj 文件。

Let us now compare project.json and MSBuild.csproj files side by side.

compare

在左边,我们以 json 格式的文件,而在右边,文件是 XML 格式。你可以在 project.json 文件,在依赖关系部分,里面的 netcoreapp1.0 ,而在 MSBuild.csproj 文件,你将看到 netcoreapp2.0

To the left, we have the file in json format while on the right, the file is in XML format. You can see that in the project.json file, inside the dependencies section, there is netcoreapp1.0, while in MSBuild.csproj file, you will see the netcoreapp2.0.

Restoring and Building with MSBuild

在本章,我们将讨论如何使用命令行实用程序来还原和构建你的 MSBuild (*.csproj) 文件。要查看 .NET Core 2.0 预览版 1 中的命令,让我们运行以下命令。

In this chapter, we will discuss how to restore and build your MSBuild (*.csproj) file using the command line utility. To see what commands are available in .NET Core 2.0 preview 1, let us run the following command.

dotnet help

你将看到所有像 new、restore、build 等命令。

You will see all the commands like new, restore, build, etc.

restore

以下是 Program.cs 文件中的默认实现。

Following is the default implementation in Program.cs file.

using System;
namespace MSBuild {
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Hello World!");
      }
   }
}

现在让我们执行以下命令以查看进度。

Let us now execute the following command to see the progress.

dotnet build

你将会看到许多错误。这些错误需要更正。

You will see a lot of errors. These errors need to be rectified.

lot of errors

现在,让我们运行以下命令。

Let us now run the following command.

dotnet restore

你可以看到所有软件包已还原。还生成了一些新文件夹和文件。

You can see that all the packages are restored. Some new folders and files have also been generated.

generated

要查看目录结构,让我们运行以下命令。

To see the directory structure, let us run the following command.

tree /f

以下是目录结构 -

Following is the directory structure −

directory structure

现在让我们再次运行以下命令重新生成项目。

Let us now rebuild the project running the following command again.

dotnet build

现在你的项目将成功构建,不会有任何错误,也会创建 MSBuild.dll。

Now you project will build successfully without any error(s) and MSBuild.dll is also created.

msbuild dll

要查看输出,让我们运行以下命令 -

To see the output, let us run the following command −

dotnet run

你可以在控制台上看到以下输出。

You can see the following output on your console.

console output

.NET Core - Migrations

在本章中,我们将迁移包含 ` project.json ` 文件构建系统而不是 ` MSBuild ( .csproj` 的控制台应用程序。因此,我们有一个旧项目,其中包含以下文件。

In this chapter, we will migrate the console application which contains the project.json file build system instead of MSBuild (.csproj)*. So, we have an old project which contains the following files.

following files

现在的问题是,我们为什么需要迁移?此项目是使用 .NET Core 1.0 Preview 2 工具创建的,现在我们已经安装了 .NET Core 2.0 Preview 1 工具。现在,当你使用 .NET Core 2.0 命令行实用工具构建此应用程序时,你将看到以下错误。

Now the question is, why do we need migration? This project is created using .NET Core 1.0 preview 2 tooling and now we have installed .NET Core 2.0 preview 1 tooling. Now when you build this application using .NET Core 2.0 command line utility, then you will see the following error.

following error

这是因为 ` project.json ` 构建系统在 .NET Core 2.0 中不再可用,所以我们需要迁移才能正常工作。要查看可用命令,让我们运行以下命令。

This is because the project.json build system is no longer available in .NET Core 2.0, so we need migration so that it can work properly. To see the available commands, let us run the following command.

dotnet help

在命令部分,你可以看到不同的命令,你还可以看到 ` migrate ` 命令,它将基于 project.json 的项目迁移到基于 MSBuild 的项目。

In the commands section, you can see the different commands and you can also see the migrate command which will migrate a project.json based project to a MSBuild based project.

migrate

现在,让我们运行以下命令。

Let us now run the following command.

dotnet migrate

你将看到迁移过程的摘要,在这里你还可以看到项目已成功迁移。

You will see a summary of the migration process and here you can also see that a project is migrated successfully.

migrate sucessfull

现在让我们使用以下命令查看目录结构。

Let us now see the directory structure by using the following command.

tree /f

你现在将在项目根目录中看到 *.csproj 文件以及 Program.cs 文件,而 project.json 已移动到备份文件夹。

You will now see the *.csproj file along with Program.cs file in the project root directory and project.json is moved to the backup folder.

backup folder

让我们打开 ` console.csproj ` 文件。现在,你可以通过运行以下命令使用 MSBuild 系统还原并构建此项目。

Let us open the console.csproj file. Now you can restore and build this project using the MSBuild system by running the following command.

dotnet restore

你现在可以看到所有软件包已还原。

You can now see that all the packages are restored.

dotnet restore

你现在可以使用以下命令构建你的项目。

You can now build your project with the following command.

dotnet build

现在你可以看到项目已使用 MSBuild 成功构建,且 ..\bin\Debug\netcoreapp1.0 文件夹中也生成了 console.dll。

You can now see that the project is built successfully using MSBuild and console.dll is also generated in ..\bin\Debug\netcoreapp1.0 folder.

msbuild

以下屏幕截图显示了目录结构和文件。

The following screenshot shows the directory structure and files.

screenshot