Net cli что это
Перейти к содержимому

Net cli что это

  • автор:

Net cli что это

Создадим первую программу на языке C#. Что для этого нужно? Прежде всего для написания кода программы нам понадобится текстовый редактор. В принципе можно выбрать любой понравившийся текстовый редактор, например, встроенный в Windows по умолчанию блокнот. Но я в данном случае буду ориентироваться на более изощренный текстовый редактор Visual Studio Code . Данный текстовый редактор доступен для всех основных операционных систем: Windows, MacOS, Linux. Он доступен по ссылке загрузить Visual Studio Code

C# в Visual Studio Code

Второй необходимый компонент для создания программ — компилятор. Для компиляции, построения, запуска и ряда других задач Microsoft предоставляет набор инструментов, который называется .NET SDK . Загрузим его со страницы https://dotnet.microsoft.com/en-us/download.

C# в Visual Studio Code

На странице https://dotnet.microsoft.com/en-us/download/dotnet/7.0 при необходимости можно найти все возможные варианты SDK под различные архитектуры и системы.

После загрузки запустим установщик .NET SDK:

Установка .NET SDK для программирования на C# Установка среды .NET SDK для программирования на C#

И после установки .NET SDK мы можем начать свою славную поступь в прекрасный мир программирования на C#.

Создадим первый проект. Для этого определим какую-нибудь новую папку для проекта. Например, пусть мы создали для проекта папку C:\dotnet\helloapp . Откроем терминал/командную строку и с помощью команды cd перейдем к этой папке.

Для создания проекта в .NET CLI применяется команда dotnet new , которой передается тип проекта. Мы будем создавать консольное приложение, поэтому будем использовать тип console . Итак, в введем в терминале следующую команду:

В данном случае мы указываем, что создаваемый проект будет представлять консольное приложение.

Создание проекта C# 11 и .NET 7 в консоли

После выполнения этой команды в папке helloapp будет создан проект с минимальным набором стандартных файлов и папок.

.NET CLI Создание проекта

В частности, мы можем найти в папке проекта файл helloapp.csproj . Это главный файл проекта, который определяет его конфигурацию. Мы можем открыть его в любом текстовом редакторе, просмотреть и при необходимости изменить.

И, кроме того, по умолчанию создается главный файл программы Program.cs со следующим содержимым:

Соответственно, если нам надо внести изменения в исходный код программы, то мы будем изменять содержимое именно этого файла.

В принципе этот минимальный проект уже можно запускать. Для запуска проекта введем в командной строке следующую команду:

Компиляция программы на C# из командной строки

После выполнения команды в проекте в папке bin\Debug\net7.0 появятся файлы программы helloapp.dll и helloapp.exe, которые можно вручную запустить на компьютере, где установлен .NET 7.

Компиляция программы C# с помощью .NET CLI

Теперь изменим весь код программы. Для этого откроем файл Program.cs в каком-нибудь текстовом редакторе и изменим его код на следующий:

Изменение кода программы на C# и .NET

По сравнению с автоматически сгенерированным кодом я внес несколько изменений. Теперь первой строкой выводится приглашение к вводу.

Метод Console.Write() выводит на консоль некоторую строка. В данном случае это строка «Введите свое имя: «.

На второй строке определяется строковая переменная name, в которую пользователь вводит информацию с консоли:

Ключевое слово var указывает на определение переменной. В данном случае переменная называется name . И ей присваивается результат метода Console.ReadLine() , который позволяет считать с консоли введенную строку. То есть мы введем в консоли строку (точнее имя), и эта строка окажется в переменой name .

Затем введенное имя выводится на консоль:

Чтобы ввести значение переменной name внутрь выводимой на консоль строки, применяются фигурные скобки <>. То есть при выводе строки на консоль выражение будет заменяться на значение переменной name — введенное имя.

Однако чтобы можно было вводить таким образом значения переменных внутрь строки, перед строкой указывается знак доллара $.

A Quick Tour of the .NET CLI

With the release of .NET Core 2.0, Microsoft has the next major version of the general purpose, modular, cross-platform and open source platform that was initially released in 2016. .NET Core has been created to have many of the APIs that are available in the current release of .NET Framework. It was initially created to allow for the next generation of ASP.NET solutions but now drives and is the basis for many other scenarios including IoT, cloud and next generation mobile solutions. In this second series covering .NET Core, we will explore some more the benefits of .NET Core and how it can benefit not only traditional .NET developers but all technologists that need to bring robust, performant and economical solutions to market.

This InfoQ article is part of the series ".NET Core". You can subscribe to receive notifications via RSS.

Related Sponsored Content
Related Sponsor

Code, deploy, and scale Java your way.
Microsoft Azure supports your workload with abundant choices, whether you're working on a Java app, app server, or framework. Learn more.

Recently I’ve been asked what the advantages are in moving to .NET Core from folks who have either been hesitant or unable to switch off the older, full .NET framework. As a reply, I’ll mention the better performance, the improved csproj file format, the improved testability of ASP.NET Core, and that is cross platform.

As the author of several OSS tools (Marten, StructureMap, and Alba is referenced in this project as examples), the biggest advantage to me personally has possibly been the advent of the dotnet cli. Used in conjunction with the new .NET SDK csproj file format, the dotnet cli tooling has made it far easier for me personally to create and maintain build scripts for my projects. It’s easier to run tests in build scripts, easier to both consume and publish Nuget packages, and the cli extensibility mechanism is fantastic for incorporating custom executables distributed through Nuget packages into automated builds.

To get started with the dotnet cli, first install the .NET SDK on your development machine. Once that’s done, there’s a couple of helpful things to remember:

  • The “dotnet” tools are globally installed in your PATH and available anywhere in your command line prompts
  • The dotnet cli uses the Linux style of command syntax using “—word [value]” for optional flags in longhand or “-w [value]” as a shorthand. If you’re used to the Git or Node.js command line tools, you’ll feel right at home with the dotnet cli
  • “dotnet —help” will list the installed commands and some basic syntax usage
  • “dotnet —info” will tell you what version of the dotnet cli you are using. It’s probably a good idea to call this command in your continuous integration build for later troubleshooting when something works locally and fails on the build server or vice versa
  • Even though I’m talking about .NET Core in this article, do note that you can use the new SDK project format and the dotnet cli with previous versions of the full .NET Framework

Hello World from the Command Line

To take a little bit of a guided tour through some of the highlights of the dotnet cli, let’s say we want to build a simple “Hello, World” ASP.NET Core application. Just for fun though, let’s add a couple twists:

  1. There’ll be an automated test for our web service in a separate project
  2. We’ll deploy our service via a Docker container because that’s what all the cool kids do (and it shows off more of the dotnet cli)
  3. And of course, we’ll try to utilize the dotnet cli as much as possible

If you want to see the final product of this code, check out this GitHub repository.

First off, let’s start with an empty directory named “DotNetCliArticle” and open your favorite command line tool to that directory. We’re going to start by using the “dotnet new” command to generate a solution file and new projects. The .NET SDK comes with several common templates to create common project types or files, with other templates available as add-ons (more on this in a later section). To see what templates are available on your machine, start by using this command dotnet new –help, which should give you some output like this:

As you’ll notice above, one of the available templates is “sln” for an empty solution file. We’ll use that template to get started by typing the command dotnet new sln which will generate this output:

The template "Solution File" was created successfully.

By default, this command will name the solution file after the containing directory. Because I called my root directory “DotNetCliArticle,” the generated solution file is “DotNetCliArticle.sln.”

Going farther, let’s add the actual project for our “Hello, World” with this command:

dotnet new webapi —output HeyWorld

The command above executes the “webapi” template to the directory “HeyWorld” that we specified through the optional “output” flag. This template will generate a slimmed down MVC Core project structure suitable for headless APIs. Again, the default behavior is to name the project file after the containing directory, so we get a file named “HeyWorld.csproj” in that directory, along with all the basic files for a minimal ASP.NET MVC Core API project. The template also sets up all the necessary Nuget references to ASP.NET Core that we need in our new project to get started.

Since I just happened to be building this in a small Git repository, after adding any new files with git add ., I use git status to see what has been newly created:

Now, to add the new project to our empty solution file, you can use the “dotnet sln” command like this:

dotnet sln DotNetCliArticle.sln add HeyWorld/HeyWorld.csproj

Alright, now we’ve got the shell of a new ASP.NET Core API service without ever having to open Visual Studio.NET (or JetBrains Rider in my case). To go a little farther and start our testing project before we write any actual code, I issue these commands:

dotnet new xunit —output HeyWorld.Tests

dotnet sln DotNetCliArticle.sln add HeyWorld.Tests/HeyWorld.Tests.csproj

The commands above create a new project using xUnit.NET as the test library and adds that new project to our solution file. The test project needs a project reference to the “HeyWorld” project, and fortunately we can add a project reference with the nifty “dotnet add” tool like so:

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

dotnet add HeyWorld.Tests/HeyWorld.Tests.csproj reference HeyWorld/HeyWorld.csproj

Before opening up the solution, I know upfront there’s a couple other Nuget references that I’d like to use in the testing project. Shouldly is my assertion tool of choice, so I’ll add a reference to the latest version of Shouldly by issuing another call to the command line:

dotnet add HeyWorld.Tests/HeyWorld.Tests.csproj package Shouldly

Which will give me some command line output like this:

Next, I want to add at least one more Nuget reference to the testing project called Alba.AspNetCore2 that I’ll use to author HTTP contract tests against the new web application:

dotnet add HeyWorld.Tests/HeyWorld.Tests.csproj package Alba.AspNetCore2

Now, just to check things out a little bit before working with the code, I’ll make sure everything compiles just fine by issuing this command to build all the projects in our solution at the command line:

dotnet build DotNetCliArticle.sln

And ugh, that didn’t compile because of a diamond dependency version conflict between Alba.AspNetCore2 and the versions of the ASP.NET Core Nuget references in the HeyWorld project. No worries though, because that’s easily addressed by fixing the version dependency of the M icrosoft.AspNetCore.All Nuget in the testing project like this:

dotnet add HeyWorld.Tests/HeyWorld.Tests.csproj package Microsoft.AspNetCore.All —version 2.1.2

In the example above, using the “—version” flag with the value “2.1.2” will fix the reference to exactly that version instead of just using the latest version found from your Nuget feeds.

To double check that our Nuget dependency problems have all gone away, we can use the commands shown below to do a quicker check than recompiling everything:

dotnet clean && dotnet restore DotNetCliArticle.sln

As an experienced .NET developer, I’m paranoid about lingering files in the temporary /obj and /bin folders. Because of that, I use the “Clean Solution” command in Visual Studio.NET any time I try to change references just in case something is left behind. The “dotnet clean” command does the exact same thing from a command line.

Likewise, the “dotnet restore” command will try to resolve all known Nuget dependencies of the solution file I specified. In this case, using “dotnet restore” will let us spot any potential conflicts or missing Nuget references quickly without having to do a complete compilation – and that’s the main way I use this command in my own work. In the latest versions of the dotnet cli, Nuget resolution is done for you automatically (that behavior can be overridden with a flag though) in calls to "dotnet build/test/pack/etc” that would require Nugets first.

Our call to “dotnet restore DotNetCliArticle.sln” ran cleanly with no errors, so we’re finally ready to write some code. Let’s open up the C# editor of your choice and add a code file to the HeyWorld.Tests project that contains a very simple HTTP contract test that will specify the behavior we want from the “GET: /” route in our new HeyWorld application:

The resulting file should be saved in the HeyWorld.Tests directory with an appropriate name such as verify_the_endpoints.cs.

Without getting too much into the Alba mechanics, this just specifies that the home route of our new HeyWorld application should write out text saying “Hey, world.” We haven’t actually coded anything real in our HeyWorld application, but let’s still run this test to see if it’s wired up correctly and fails for the “right reason.”

Back in the command line, I can run all of the tests in the testing project with this command:

Which with our one test that will fail because nothing has actually been implemented yet, gives us this output:

To sum up that output, one test was executed and it failed. We also see the standard xUnit output that gives us some information about why the test failed. It’s important to note here that the “dotnet test” command will return an exit code of zero denoting success if all the tests pass and a non-zero exit code denoting failure if any of the tests fail. This is important for continuous integration (CI) scripting where most CI tools use the exit code of any commands to know when the build has failed.

I’m going to argue that the test above failed for the “right reason,” meaning that the test harness seems to be able to bootstrap the real application and I expected a 404 response because nothing has been coded yet. Moving on, let’s implement an MVC Core endpoint for the expected behavior:

(Note that the previous code should be appended as an additional class in your HeyWorld\startup.cs file.)

Returning to the command line again, let’s run the previous “ dotnet test HeyWorld.Tests/HeyWorld.Tests.csproj ” command again and hopefully see results like this:

Alright then, now that the test passes let’s run the actual application. Since the “dotnet new webapi” template uses the in-process Kestrel web server to handle HTTP requests, literally the only thing we need to do to run our new HeyWorld application is to launch it from the command line with this command:

dotnet run —project HeyWorld/HeyWorld.csproj

Running the command above should give you some output like this:

To test out our new application now that it’s running, just navigate in your browser like so:

Dealing with HTTPS set up is outside the scope of this article

Do note again that I’m assuming all commands are being executed with the current directory set to the solution root folder. If your current directory is a project directory and there is only one *.csproj file in that directory, you can just type “dotnet run.”

Now that we have a tested web api application, let’s take the next step and put HeyWorld into a Docker image. Using the standard template for dockerizing a .NET Core application, we’ll add a Dockerfile to our HeyWorld project with this content:

(Note that the previous text should be saved to a text file called Dockerfile in the project directory—in this case HeyWorld\Dockerfile.)

As this article is just about the dotnet cli, I just want to focus on the two usages of that within the Dockerfile:

  1. “dotnet restore” — as we learned above, this command will resolve any Nuget dependencies of the application
  2. “dotnet publish –c Release –o out” — the “dotnet publish” command will build the designated project and copy all the files that make up the application to a given location. In our case, “dotnet publish” will copy the compiled assembly for HeyWorld itself, all the assemblies referenced from Nuget dependencies, configuration files, and any files that are referenced in the csproj file

Please note in the usage above that we had to explicitly tell “dotnet publish” to compile with the “Release” configuration through the usage of the “-c Release” flag. Any dotnet cli command that compiles code (“build”, “publish”, “pack” for example) will be default build assemblies with the “Debug” configuration. Watch this behavior and remember to specify the “-c Release” or “—configuration Release” if you are publishing a Nuget or an application that is meant for production usage. You’ve been warned.

Just to complete the circle, we can now build and deploy our little HeyWorld application through Docker with these commands:

The first command builds and locally publishes a Docker image for our application named “heyworld.” The second command actually runs our application as a Docker container named “myapp.” You can verify this by opening your browser to “http://localhost:8080.”

Summary

The dotnet cli makes automating and scripting builds on .NET projects simple, especially compared to the state of the art in .NET a decade or so ago. In many cases you may even eschew any kind of task-based build script tool (Cake, Fake, Rake, Psake, etc.) in favor of simple shell scripts that just delegate to the dotnet cli. Moreover, the dotnet cli extensibility model makes it readily possible to incorporate external .NET authored command line applications distributed via Nuget into your automated builds.

About the Author

When Jeremy Miller was growing up in a farm community in Missouri, there was a “special” breed of folks around called Shade Tree Mechanics. Usually they were not the most reputable people in the world, but they had a knack for fixing mechanical problems and a reckless fearlessness to tinker with anything. A shade tree mechanic can be spotted by finding the pair of legs sticking out from under a beater car on blocks, surrounded by other skeletal vehicles crowding the rest of his scrubby, junk-laden yard. The beaters you see abandoned all around him aren’t useless, they’re fodder. He takes bits and pieces and tweaks and tunes, and comes up with a creative solution to your needs. Reputation notwithstanding, a shade tree mechanic knows how to get things running. While Miller doesn’t have any particular mechanical ability (despite a degree in mechanical engineering), he likes to think that he is the developer equivalent of a shade tree mechanic. His hard drive is certainly littered with the detritus of abandoned open source projects.

With the release of .NET Core 2.0, Microsoft has the next major version of the general purpose, modular, cross-platform and open source platform that was initially released in 2016. .NET Core has been created to have many of the APIs that are available in the current release of .NET Framework. It was initially created to allow for the next generation of ASP.NET solutions but now drives and is the basis for many other scenarios including IoT, cloud and next generation mobile solutions. In this second series covering .NET Core, we will explore some more the benefits of .NET Core and how it can benefit not only traditional .NET developers but all technologists that need to bring robust, performant and economical solutions to market.

This InfoQ article is part of the series ".NET Core". You can subscribe to receive notifications via RSS.

Обзор интерфейса командной строки .NET .NET CLI overview

Интерфейс командной строки (CLI) .NET — это кроссплатформенная цепочка инструментов для разработки, сборки, запуска и публикации приложений .NET. The .NET command-line interface (CLI) is a cross-platform toolchain for developing, building, running, and publishing .NET applications.

Интерфейс командной строки .NET входит в пакет SDK для .NET. The .NET CLI is included with the .NET SDK. Сведения об установке пакета SDK для .NET см. в статье Установка .NET Core. To learn how to install the .NET SDK, see Install .NET Core.

Команды CLI CLI commands

По умолчанию устанавливаются следующие команды: The following commands are installed by default:

Основные команды Basic commands

Команды для изменения проекта Project modification commands

Расширенные команды Advanced commands

Команды управления средством Tool management commands

Средства — это консольные приложения, которые устанавливаются из пакетов NuGet и вызываются из командной строки. Tools are console applications that are installed from NuGet packages and are invoked from the command prompt. Вы можете писать средства самостоятельно или устанавливать средства, написанные другими. You can write tools yourself or install tools written by third parties. Средства также называются глобальными средствами, средствами пути к средству и локальными средствами. Tools are also known as global tools, tool-path tools, and local tools. Дополнительные сведения см. в обзоре средств .NET. For more information, see .NET tools overview.

Структура команд Command structure

Структура команд CLI состоит из драйвера ("dotnet"), самой команды и ее возможных аргументов и параметров. CLI command structure consists of the driver ("dotnet"), the command, and possibly command arguments and options. Этот шаблон используется в большинстве операций интерфейса командной строки, таких как создание консольного приложения и его запуск из командной строки, как показывают следующие команды при выполнении из каталога my_app: You see this pattern in most CLI operations, such as creating a new console app and running it from the command line as the following commands show when executed from a directory named my_app:

Драйвер Driver

Драйвер называется dotnet и имеет два вида ответственности — выполнение платформозависимого приложения или выполнение команды. The driver is named dotnet and has two responsibilities, either running a framework-dependent app or executing a command.

Для запуска платформозависимого приложения укажите его драйвера, например dotnet /path/to/my_app.dll . To run a framework-dependent app, specify the app after the driver, for example, dotnet /path/to/my_app.dll . При выполнении команды из папки, где находится библиотека DLL приложения, просто выполните dotnet my_app.dll . When executing the command from the folder where the app’s DLL resides, simply execute dotnet my_app.dll . Если вы хотите использовать конкретную версию среды выполнения .NET, используйте параметр —fx-version <VERSION> (см. справку по команде dotnet). If you want to use a specific version of the .NET Runtime, use the —fx-version <VERSION> option (see the dotnet command reference).

При указании команды для драйвера dotnet.exe запускает процесс выполнения команды CLI. When you supply a command to the driver, dotnet.exe starts the CLI command execution process. Пример: For example:

Сначала драйвер определяет нужную версию пакета SDK. First, the driver determines the version of the SDK to use. Если файл global.json отсутствует, используется последняя доступная версия пакета SDK. If there is no global.json file, the latest version of the SDK available is used. Это может быть предварительная или стабильная версия, в зависимости от того, какая версия является последней на компьютере. This might be either a preview or stable version, depending on what is latest on the machine. После определения версии пакета SDK он выполняет команду. Once the SDK version is determined, it executes the command.

Команда Command

Команда выполняет действие. The command performs an action. Например, dotnet build проводит сборку кода. For example, dotnet build builds code. dotnet publish публикует код. dotnet publish publishes code. Команды реализуются как консольное приложение с использованием соглашения dotnet . The commands are implemented as a console application using a dotnet convention.

Аргументы Arguments

Аргументы, указываемые в командной строке, передаются непосредственно в вызываемую команду. The arguments you pass on the command line are the arguments to the command invoked. Например, если выполнить dotnet publish my_app.csproj , аргумент my_app.csproj указывает публикуемый проект и передается в команду publish . For example, when you execute dotnet publish my_app.csproj , the my_app.csproj argument indicates the project to publish and is passed to the publish command.

Параметры Options

Параметры, указываемые в командной строке, передаются непосредственно в вызываемую команду. The options you pass on the command line are the options to the command invoked. Например, при выполнении dotnet publish —output /build_output параметр —output и его значение передаются в команду publish . For example, when you execute dotnet publish —output /build_output , the —output option and its value are passed to the publish command.

Create and Run a .NET Core Application Using CLI Tools: .NET Core CLI Part I

Join the DZone community and get the full member experience.

.NET Core provides a new cross-platform toolchain for developing .NET applications which are nothing but the .NET CLI tools.

CLI tools are really powerful and easy to use, so, as a developer, we should know how to use these commands.

These commands are very useful if you are looking to create Continuous Integration(CI) and\or Continuous Deployment(CD).

In this post, I will explain how to create, restore, clean, build, and run .NET Core applications using the latest CLI commands.

What Are CLI tools?

The .NET Core command-line interface (CLI) is a new cross-platform toolchain for developing .NET applications. The CLI is a foundation upon which higher-level tools, such as Integrated Development Environments (IDEs), editors, and build orchestrators, can rest.

CLI tools are cross-platform tools and can be used in Windows, Mac, or Linux. Visual Studio internally uses this CLI to restore, build, and publish an application.

.NET CLI tools are generally shipped with the .NET Core installation so if you have installed .NET Core, you can use CLI tools.

If you do not have .NET Core installed, you can download .NET Core from here.

Check Whether You Have the Dotnet CLI Installed

Open the command prompt and type dotnet . If everything is installed correctly, it should give logs as shown below:

Dotnet CLI Syntax

The DotNet CLI commands are really easy to use.

The command syntax generally has 3 parts:

For example, if you wish to create the project in the C# language, you can write below command:

Here:

  • dotnet is the driver.
  • new is the command
  • console is the argument
  • -lang is the option

List of Available Commands

Before you start writing the commands, you should have a look at all available commands. You can write a help command to list the details, as shown below:

Create New Project Using CLI

Create a folder under anywhere in the C drive and change the directory to that path in the Command prompt:

Run the dotnet new command to create a new .NET Core application; we will create an MVC project, so we will run below command:

This will create brand new .NET Core MVC project in the mentioned location:

Note: You can use the command dotnet new -l to list out all available template options.

Restore Command

Once the application is created, let us run the restore command which will restore the packages if they are not available on your local machine:

The restore command internally calls Nuget.exe to restore the tree of dependencies.

This sample application is very small but for a big application, restore plays a big role.

Clean and Build

Once the packages are restored, let us clean and build our project using CLI.

For cleaning, use the clean command as shown below:

Important Note: dotnet clean will clear everything under the folder bin\Debug\netcoreapp2.x, it will not clear everything under bin and/or the obj folder. More details here: https://github.com/dotnet/cli/issues/7240

For building the project, use the build command, as shown below:

This will build the project and will put dlls and other build files under bin\Debug\netcoreapp2.x

Run the Application

We can run the application by running the run command, as shown below:

The run command first calls build to make sure the targets are built and then runs the target application.

As you can see in the logs, the application is running on https://localhost:5001

Dotnet Help for Command Details

We have already seen the help command above, but if you need help with specific commands then you can use -h .

For example, if you want to see all arguments/options available for the command build , then write the below command:

You can find all details for all commands with -h .

In a future post, I will explain how to manage Nuget packages along with creating and publishing our own Nuget packages using CLI commands.

We will also use the commands which we used above in a Jenkins pipeline to create the CI.

Hope this helps!

Published at DZone with permission of Neel Bhatt , DZone MVB . See the original article here.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *