3) create, test, release the first NET CORE program

Tools: Visual Studio Code or Visual Studio

Environment: .NET CORE 2.0

VS Code of course, support the development of netcore very strong, but I still choose a more familiar and more powerful VS.

vs2017 or latest 2019 comes with netcore, if not the version you want, you can manually download their own, address: https://dotnet.microsoft.com/download

Create a project:

1) Start Visual Studio 2017. Select "File"> "New"> "Project" from the menu bar. In the "New Project" * dialog box, select "Visual C #" and ".NET Core" nodes. Then, select "Console Application (.NET Core)" project template. In the "Name" text box, type "HelloWorld". Select "OK" button.

 

2) Visual Studio use a template to create a project. C # .NET Core Console Application template automatically define classes Program and will need a  String  array of methods used as an argument Main. Main is the application entry point, but also the method when the application starts automatically invoked by the runtime. args  array contains all commands provided in the application startup line arguments.

 

In addition to comparative framework dependencies (references) a bit other differences are similar.

3) To pause before the application closes the console window, please call  Console.WriteLine (String)  Add the following code immediately after the method:

Console.Write("Press any key to continue..."); Console.ReadKey(true);

This code will prompt the user to press any key, then pause the program before the user presses a key.

  1. In the menu bar, select "Build"> "Build Solution." This will program is compiled into an intermediate language (IL), and then converted by time (JIT) compiler into a binary code.
  2. With the green arrow on the toolbar, select "HelloWorld" button, which run the program.

Improved "Hello World" application

Improved application prompts the user to enter a name, and display it along with the date and time. To modify and test the program, do the following:

  1. In the code window, between the back of the static void Main (string [] args) line left bracket and a right bracket, enter the following C # code:
Console.WriteLine("\nWhat is your name? "); var name = Console.ReadLine(); var date = DateTime.Now; Console.WriteLine($"\nHello, {name}, on {date:d} at {date:t}!"); Console.Write("\nPress any key to exit..."); Console.ReadKey(true);

Replace the contents of the Main method. 

This code is displayed in the console "What is your name?", And then wait for user input string and press Enter. It is to this string is stored in a variable named name. It also retrieves  DateTime.Now  value of the attribute (which contains the current local time), and this value is assigned to the variable date. Finally, the use of interpolation string within these values are displayed in the console window.

  1. Select  " generate"  >  " Build Solution"  , compiled this program.
  2. Select the green arrow on the toolbar, or press F5 to select "Debug"> "Start Debug" menu item, run the program in Visual Studio debug mode. When prompted, enter a name and press Enter.

 

Create a class library NET STANDARD:

  1. In the "Solution Explorer", right-click "ClassLibraryProjects" solution file, then select "Add"> "New Project" from the context menu.
  2. In the "Add New Project" dialog box, expand "Visual C #" node and select ".NET Standard" node and the "Class Library (.NET Standard)" project template. In the "Name" text box, enter the project name "StringLibrary". Select "OK" to create the class library project.

 

Then, open the code window in Visual Studio development environment.

 

  1. Check to make sure the correct version of the library of a given target to .NET Standard. Right-click the "Solution Explorer" window library project, and then select "Properties." "Target frame" text box to display a given target .NET Standard 2.0. 

4. The code in the code window with the following code, and save the file:

 1 using System;
 2 
 3 namespace StringLibrary
 4 {
 5     public static class StringExt
 6     {
 7         public static bool StartsWithUpper(this String str)
 8         {
 9             if (String.IsNullOrWhiteSpace(str))
10                 return false;
11 
12             Char ch = str[0];
13             return Char.IsUpper(ch);
14         }
15     }
16 }
View Code

4. Right-class library, generated, no errors should generate success.

 

Distributed in the form of class libraries NuGet package:

Using NuGet package issued in the form library, let the caller to use the library for more

  1. Open the console window. For example, in the Windows taskbar "There are questions just ask me" text box, type Command Prompt (or abbreviation cmd), and then select the "Command Prompt" desktop application, or press Enter (if it is selected in the search results window console ), open a console window.
  2. Go to the library project directory. Unless reconfigured typical file locations, as this file is typically located in 2017 \ Projects \ ClassLibraryProjects \ StringLibrary directory Documents \ Visual Studio. This directory contains the source code and project files StringLibrary.csproj.
  3. Issue the command dotnet pack --no-build. At this point, dotnet utility generates an extension .nupkg package.

 

Create a unit test project

  1. In the "Solution Explorer", open the "NetCoreSolution" solution node context menu, and then select "Add"> "New Project."
  2. In the "Add New Project" dialog box, select "Visual C #" node. Then, select ".NET Core" nodes and "MSTest test project (.NET Core)" project template. In the "Name" text box, enter the project name "StringLibraryTest". Select "OK" to create a unit test project.

 

 Note: In addition to MSTest test project, you can also use Visual Studio to create xUnit test project for the .NET Core.

At this point, Visual Studio will create a project, and UnitTest1.cs open the file in the code window. 

Source unit test template to create responsible for the following:

  It introduced  Microsoft.VisualStudio.TestTools.UnitTesting  namespace, which comprises means for the type of testing.

  Application to UnitTest1 class  TestClassAttribute  characteristics. Test class labeled with [TestMethod] property test methods are all performed automatically in the unit test run.

  It applies  TestMethodAttribute  attribute, is defined as a test method TestMethod1 automatically performed in the unit test run.

  1. In the "Solution Explorer", right-click "StringLibraryTest" project "dependency" node and select "Add Reference" from the context menu.

 

  1. In the "Reference Manager" dialog box, expand the "Project" node, and check the box next to "StringLibrary". After adding a reference to the StringLibrary assembly, the compiler can find StringLibrary method. Select "OK" button. This adds a reference to the class library project StringLibrary.

 

Is added and run the unit test method

  When you run the unit tests, Visual Studio unit testing class (applied the  TestClassAttribute  class characteristics) have marked  TestMethodAttribute  all method characteristics. When first encountered all tests do not pass the test or test methods have been successfully passed, the test method is terminated.

The most common test call to  Assert  class members. Many assertions comprising at least two parameters, one of which is the expected result of the test, the other is the actual test results. The following table shows some of the most commonly called methods.

Assertion methods

function

Assert.AreEqual

Verify that the two values ​​are equal or objects. If the value is not equal to or object, the assertion fails.

Assert.AreSame

Verify whether the two object variables reference the same object. If these variables refer to different objects, the assertion fails.

Assert.IsFalse

Verify whether a condition is false. If the condition is true, the assertion fails.

Assert.IsNotNull

Verifies whether the object is not null. If the object is null, the assertion fails.

It can also be applied to the test method  ExpectedExceptionAttribute  characteristics. It specifies the test method is expected to lead to the abnormal type. If you do not specify an exception is thrown, the test is not passed.

StringLibrary.StartsWithUpper test method, the need to provide many begin with an uppercase characters. In this case, this method should return true, so you can call  IsTrue  method. Similarly, the need to provide a lot of strings to non-uppercase characters beginning. In this case, this method should return false, so that you can call  IsFalse  method.

The method of treatment as the library is a string, it is also necessary to ensure that it can successfully handle the empty string (String.Empty) (excluding the character and  Length  valid string of 0) and the null character (character string has not been initialized). If  String  call StartsWithUpper examples of the extension method, not to pass to a null string. However, it can also be called as a static method directly and passing a  String  argument.

Define three methods, each of which will call for each element of the string array repeated  Assert  method. Since the test method fails immediately when first encountered the test is not passed, so the calling method overloading to pass a string to specify a string value method used in the call.

Create a test method:

 1 using System;
 2 using Microsoft.VisualStudio.TestTools.UnitTesting;
 3 using StringLibrary;
 4 namespace StringLibraryTest
 5 {
 6     [TestClass]
 7     public class UnitTest1
 8     {
 9         [TestMethod]
10         public void TestStartsWithUpper()
11         {
12             // Tests that we expect to return true.
13             string[] words = { "Alphabet", "Zebra", "ABC", "Αθήνα", "Москва" };
14             foreach (var word in words)
15             {
16                 bool result = word.StartsWithUpper();
17                 Assert.IsTrue(result,
18                        String.Format("Expected for '{0}': true; Actual: {1}",
19                                      word, result));
20             }
21         }
22 
23         [TestMethod]
24         public void TestDoesNotStartWithUpper()
25         {
26             // Tests that we expect to return false.
27             string[] words = { "alphabet", "zebra", "abc", "αυτοκινητοβιομηχανία", "государство",
28                                "1234", ".", ";", " " };
29             foreach (var word in words)
30             {
31                 bool result = word.StartsWithUpper();
32                 Assert.IsFalse(result,
33                        String.Format("Expected for '{0}': false; Actual: {1}",
34                                      word, result));
35             }
36         }
37 
38         [TestMethod]
39         public void DirectCallWithNullOrEmpty()
40         {
41             // Tests that we expect to return false.
42             string[] words = { string.Empty, null };
43             foreach (var word in words)
44             {
45                 bool result = StringExt.StartsWithUpper(word);
46                 Assert.IsFalse(result,
47                        String.Format("Expected for '{0}': false; Actual: {1}",
48                                      word == null ? "<null>" : word, result));
49             }
50         }
51     }
52 }
View Code
  1. Please note that uppercase characters TestStartsWithUpper method of testing include the Greek capital letter alpha (U + 0391) and Cyrillic capital letters EM (U + 041C), lowercase characters TestDoesNotStartWithUpper method of testing include Greek lowercase alpha (U + 03B1) and Cyrillic small letter Ghe (U + 0433).
  2. On the menu bar, select "File"> "Save As UnitTest1.cs will." In the "File Save As" dialog box, select "Save" next to the arrow button, then select "Use the encoding when saving."

 

  1. In the "Confirm Save As" dialog box, select the "Yes" button, save the file.
  2. In the "Advanced Save Options" dialog box "Encoding" drop-down list, select "Unicode (UTF-8 with signature) - code page 65001" and then select "OK."

 

If you can not save the source code for the UTF8 encoded file, Visual Studio might save it as an ASCII file. In this case, it will not be able to decode UTF8 characters outside the ASCII range of accurate run-time, and the test results will be inaccurate.

  1. On the menu bar, select "Test"> "Run"> "all the tests." At this point, "Test Explorer" window opens and displays the test has been run successfully. "By testing" section lists the three tests, the "Summary" section reports the results of the test run.

 

Treatment did not pass the test

Since the tests are run through, thus the need for a small amount of change, so a test method fails wherein:

  1. By modifying the array of words TestDoesNotStartWithUpper methods to contain the string "Error". Since Visual Studio will automatically save open files when generating a test run of the solution, so no need to save manually.

string[] words = { "alphabet", "Error", "zebra", "abc", "αυτοκινητοβιομηχανία", "государство",                    "1234", ".", ";", " " };

  1. Select the "Test"> "Run"> "All Test", run the tests. From the menu bar "Test Explorer" window indicates that there are two tests are successful, there is a failure.

 

  1. In the "test failed" section, select TestDoesNotStartWith test did not pass. ". Assert.IsFalse failed": "Test Resource Manager" window displays messages generated assertion Error "should return false; the actual return True". Because of this failure, the array of all the strings after "Error" none of the test.

 

  1. Undo edits performed in step 1 and remove the string "Error". Re-run the test, the test will pass.

  Issued:

After a successful test library, we can use our library written in console applications. Right - Add a reference StringLibrary project;

We convert the output console output character code:

1  static void Main(string[] args)
2 {
3 Console.WriteLine("\nWhat is your name? ");
4 var name = Console.ReadLine();
5 var date = DateTime.Now;
6 Console.WriteLine($"\nHello,{name} 是否大写开始:{name.StartsWithUpper()}, on {date:d} at {date:t}!");
7 Console.Write("\nPress any key to exit...");
8 Console.ReadKey(true);
9 }
View Code

Generates configuration settings on the toolbar "Change Debug" From Release ".

Right-click the "MyConsoleApp" project (rather than NetCoreSolution solution), and then select the menu "release." You can also choose  " generate"  Visual Studio main menu  " release  MyConsoleApp" .

  

  1. Open the console window. For example, in the Windows taskbar "here typing to search for" text box, type "Command Prompt" (or abbreviated "cmd"), and then select the "Command Prompt" desktop application, or press Enter (if select in the search results), open a console window.
  2. Navigate to the published application, which is located in the application project directory bin \ Release \ netcoreapp2.2 \ publish \ subdirectory. As shown below, published output comprises the following four documents:

1.  MyConsoleApp.deps.json

Run the application dependency file. It defines .NET Core components and libraries required to run applications (including dynamic link library that contains the application). For more information, see the configuration file is run .

2.  MyConsoleApp.dll

It contains the file for the application. It is a dynamic link library, dotnet MyConsoleApp.dll by entering the command in a console window to perform.

3. MyConsoleApp.pdb (for deployment is optional)

File contains debugging symbols. Although this file should be saved when you need to debug an application published version, but without the need to deploy this file with your application.

4.  MyConsoleApp.runtimeconfig.json

Configuration file when running the application. It identifies the Core version for running .NET applications. For more information, see the configuration file is run .

 

Publishing process will generate depends on the deployment framework, if the .NET Core installed on the system, the published application can run on any platform supported by the .NET Core In this deployment. Users can run the application by issuing dotnet MyConsoleApp.dll command in the console window.

  

Guess you like

Origin www.cnblogs.com/rbsky/p/11431805.html