How to Create and Publish a NuGet Package Using Visual Studio
In the previous article, we’ve learned How to Create and Publish a NuGet Package with .NET CLI. In this article, we are going to discuss how to create and publish a NuGet package using Visual Studio. Along with that, we’ll explore a few additional options like how to provide a readme file, a license file, a package icon, etc. Additionally, we are going to require the users to accept the license agreement before installing and using our package.
So let’s get going.
Prerequisites
For this article, we are going to use:
- Visual Studio with .NET Core related workload
- The .NET CLI – Starting with Visual Studio 2017, once we choose any .NET Core-related workloads, it installs the CLI as well. Another option to get the .NET CLI is to install the .NET Core SDK
- A NuGet account– We can easily register for a NuGet account in case we do not have one already
Once we have all these in place, we can start building the app.
Preparing the Class Library
Let’s start by preparing a class library which we can package into a NuGet. We can use the same class library example that we created in the How to Create and Publish a NuGet Package with .NET CLI article. Once the project is ready, let’s proceed to configure the package properties.
For configuring the NuGet Package using Visual Studio, we can:
- Right-click on the project in the solution explorer
- Select the properties menu
- And then navigate to the Package/General menu
There, we need to provide a few details.
Package Properties
Now let’s configure the properties of the NuGet Package using Visual Studio:
Generate NuGet package on build– Once we check this checkbox, it will produce a package file every time we build the project. Let’s enable this option.
Package ID – NuGet uses this value to identify a package and hence this should be unique across the host. This is case insensitive and follows the naming rules for the .NET namespace. eg: CodeMaze.Utilities.TemperatureConverter .
Package Version – We can provide the version of our package using this option. NuGet supports the standard major.minor.patch pattern as well as the pre-release suffix. eg: 1.0.1 .
Authors – Here we can provide a list of package authors separated by a comma. We should match the profile name on nuget.org so that it will cross-reference packages by the same author.
Company – We can provide the company name using this option.
Description– Here we can describe our package. It is good to give a brief explanation of what functionality this package provides.
Copyright– We can provide the copyright information here.
Project URL – We can provide a URL for our package’s home page.
Icon – Using this option, we can provide an icon for our package by uploading an image file. NuGet supports JPEG or PNG file formats with a size limit of 1 MB. Also, an image resolution of 128*128 is recommended. We are going to upload an image file that complies with these rules.
There are a few additional properties, but we can skip those as they are less important. However, we are going to see how to configure a readme file and license information in the following sections.
Adding a Readme File for NuGet Package
While configuring the package properties, there is an option to upload a readme document for the package. This should be a markdown (.md) text file.
So, let’s create a readme.md file:
Markdown is a lightweight markup language and we can use it to create formatted text using any text editor. For learning more about markdown, we can visit Markdown Tutorial.
Once the readme file is ready, we can choose it in the readme section of the Package/General tab.
License File – We can upload a license file using this option. Even though NuGet supports any text file, it is always good to follow standard license agreements as provided by MIT, Apache, etc.
Require License Acceptance – A check box that determines whether we should prompt the user to accept the license while installing this package. Let’s enable this option.
Creating the NuGet Package Using Visual Studio
For packaging a project, we can
- Right-click on the project in the Solution Explorer
- And select the Pack option
This will generate the NuGet package in the specified output folder. By default, the output folder will be bin\debug or bin\release based on the release configuration that we choose. However, there is an option to customize the output folder in the output tab of the project properties. The NuGet package will have the .nupkg extension, which is a zip file that contains the compiled assembly, all its dependencies, and other packaged files.
Also note that if we have enabled the option to generate the NuGet package on the build in the previous section, it will generate a new NuGet package every time we build the project.
Publishing the NuGet Package Using Visual Studio
Once we pack our class library into the .nupkg file, we can publish it to a host using either the .NET CLI or the nuget CLI tool. Microsoft recommends using .NET CLI over nuget CLI for publishing the NuGet packages. In this example, we are going to publish our package to the public NuGet host (nuget.org) using .NET CLI .
dotnet nuget push CodeMaze.Utilities.TemperatureConverter.1.0.1.nupkg —api-key PASTE_YOUR_API_KEY_HERE —source https://api.nuget.org/v3/index.json
This will display the result of publishing action:
Even after completing this step, it will take some time for our package to be indexed and appear in the search results. Meanwhile, NuGet will perform a virus scan on the package as well.
If we want to publish our package to a private feed, we just need to change the source and API Key accordingly.
While publishing NuGet packages, we may encounter errors in some scenarios. We have discussed the most common error scenarios and how to fix those in the Handling Publish Errors article section.
Managing the NuGet Package
Once we publish a package to NuGet, we can manage it from the Manage Packages part of our profile section in the portal. For instance, if we don’t wish to list the package in search results anymore, we can unlist the package from the Manage Package section in the NuGet portal.
Additionally, we can find all the information about the package including the readme file and license agreement in the portal.
Examining the NuGet Package using Visual Studio
After publishing the NuGet package, we can search for it in the NuGet Package Manager from Visual Studio.
While examining the NuGet package using visual studio, we can see all the details that we provided for the package. Notice that it displays the package icon that we uploaded. Similarly, we can see the links for viewing license and readme files. Additionally, when someone tries to install the package, they would be required to accept the license as we have enabled that option.
Conclusion
In this article, we looked at how to create and publish a NuGet package using Visual Studio. Additionally, we learned how to provide a readme file, license file, package icon and require the users to accept the license agreement before installing the package.
Creating NuGet package using Visual Studio 2019 and publishing it to Nuget.org
ByAnkush Jain | Last Updated On Friday, Mar 06, 2020
In this post, we will understand how can we create a NuGet package using Visual Studio 2019. Also, we will understand, how to deploy this package to Nuget.org to make it available to the rest of the world.
Step 1: Open Visual Studio 2019 and create a Class Library (.NET Standard) project.
Note: We should choose .NET Standard for creating Class Library projects. The reason being, libraries created using .NET Standard can be used by all major platforms such as .NET Framework, .NET Core, Mono, Xamarin or Unity.
Step 2: Provide a name for your project. My project name is CoderJony.Utilities.Logger . Try to keep this project name the same as your NuGet package name just for consistency.
Step 3: Now I create a public Logger class and define some public methods inside that class.
Step 4: Go to the properties of the project and select the package tab.
Step 5: This is the most useful step. In this step, I will tell you about the properties that you need to take care of the most.
- Package id — This should be the unique name for your NuGet package. This should not conflict with any other package available on the NuGet server.
- Package version — This is the version displayed on NuGet.org for your NuGet package.
- Authors — This could be your company name or your name if you are an individual.
- Company — This should be your company name.
- Product — This is the product name. You can keep it the same as the package id.
- Description — This should be the description of your package.
- Licensing — This field is required. Either you have to provide some expression here OR you can also upload a local licensing file here. I am using MIT as a license expression. Click here for more information about License Expressions.
- Repository Url — This is optional, but you can provide your public repository URL here such as GitHub.
- Tags — You should provide comma-separated values here. This helps in indexing your package on NuGet. So that NuGet can show your package as a search result when someone searches for it.
- Assembly Version & Assembly File Version — This should be the Assembly Version of the project. But it is advised to keep it the same as Package Version to avoid confusion at a later stage.
The more information you provide here, the more informative your package will look in the search results.
Step 6 — Below, you can see, that I have provided all the information that is required for the NuGet package.
Step 7 — Just mark these two checkboxes that are highlighted below.
- Generate NuGet package on build — This will generate a NuGet package every time you build the project.
- Require license acceptance — This will ensure that users have to accept the license while installing the package.
Step 8 — Now select Release mode and build the application. You can see a .nupkg file has been generated inside
Step 9 — Here you can see the generated .nupkg file.
Step 10 — Now login to nuget.org with your Microsoft account and click on Upload Package link.
Step11 — Drag and drop the generated .nupkg file here. As you can see I have dropped my .nupkg file here.
Step 12 — Verify the provided information and press the submit button at the end of the page. After submitting the information, you will be redirected to your package’s page.
Note: NuGet takes some time to validate your package after upload. After around 5 minutes, you will find that this warning is removed automatically.
Step 13 — After a few minutes, you can see — your package is available for use.
Step 14 — Now we can install this NuGet package in any of our .NET projects.
Congratulations . We have created a NuGet package in less than 30 minutes. Please let me know your feedback and suggestions in below comment box.
Name already in use
docs.microsoft.com-nuget.ru-ru / docs / quickstart / create-and-publish-a-package-using-visual-studio.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Краткое руководство. Создание и публикация пакета NuGet с помощью Visual Studio (.NET Standard, только для Windows)
Создание пакета NuGet из библиотеки классов .NET Standard в Visual Studio в Windows и его публикация на сайте nuget.org с помощью средства интерфейса командной строки выполняются очень просто.
[!Note] Если вы используете Visual Studio для Mac, ознакомьтесь с этими сведениями о создании пакета NuGet или примените средства CLI dotnet.
Установите любой выпуск Visual Studio 2019 со страницы visualstudio.com с помощью рабочей нагрузки, связанной с .NET Core.
При необходимости установите CLI dotnet .
Для CLI dotnet начиная с версии Visual Studio 2017 CLI dotnet автоматически устанавливается вместе с любыми рабочими нагрузками, связанными с .NET Core. При использовании другой версии установите пакет SDK для .NET Core, чтобы получить CLI dotnet . CLI dotnet является обязательным для проектов .NET Standard с форматом в стиле пакета SDK (атрибут SDK). Шаблон библиотеки классов .NET Standard по умолчанию в Visual Studio 2017 и более поздних версий, который применяется в рамках этой статьи, использует атрибут пакета SDK.
[!Important] Если вы работаете с проектом не в стиле SDK, выполните инструкции по созданию и публикации пакета .NET Framework (Visual Studio). В рамках этой статьи рекомендуем использовать CLI dotnet . Любой пакет NuGet можно опубликовать с помощью CLI nuget.exe . Но некоторые действия, описанные в этой статье, относятся к проектам в стиле пакета SDK и CLI dotnet. CLI nuget.exe используется для проектов не в стиле пакета SDK (в основном для проектов .NET Framework).
Зарегистрируйтесь для получения бесплатной учетной записи на nuget.org, если вы не сделали этого ранее. При создании учетной записи вам направляется сообщение электронной почты с подтверждением. Перед отправкой пакета вам нужно подтвердить учетную запись.
Создание проекта библиотеки классов
Вы можете использовать имеющийся проект библиотеки классов .NET Standard для кода, который нужно упаковать, или же создать простой проект, как показано ниже.
В Visual Studio выберите Файл > Создать > Проект, разверните узел Visual C# > .NET Standard, выберите шаблон «Библиотека классов (.NET Standard)», назовите проект AppLogger и нажмите кнопку ОК.
[!Tip] Для пакетов NuGet мы рекомендуем использовать целевой объект .NET Standard (если нет причин использовать другое), так как он обеспечивает совместимость с рядом потребляющих проектов.
Щелкните правой кнопкой мыши полученный файл проекта и выберите пункт Сборка, чтобы убедиться, что проект создан правильно. Библиотека DLL находится в папке Debug (или папке Release, если вы используете конфигурацию выпуска для сборки).
В реальном пакете NuGet вы можете реализовать множество полезных возможностей, с помощью которых другие пользователи могут создавать приложения. Однако в этом пошаговом руководстве вы не будете писать дополнительный код, так как библиотеки классов из шаблона достаточно для создания пакета. Тем не менее, вы можете использовать функциональный код для пакета:
Настройка свойств пакета
Щелкните правой кнопкой мыши проект в обозреватель решений и выберите команду меню Свойства, а затем выберите вкладку Пакет.
Вкладка Пакет отображается только для проектов в стиле SDK в Visual Studio, в основном для проектов .NET Standard или библиотеки классов .NET Core. Если вы используете проект не в стиле SDK (например, проект .NET Framework), перенесите проект или ознакомьтесь с пошаговыми инструкциями по созданию и публикации пакета .NET Framework.
[!Note] Если пакет будет общедоступным, обратите особое внимание на свойство Теги, так как они помогают найти ваш пакет и понять его назначение.
Присвойте пакету уникальный идентификатор и заполните нужные свойства. Сведения о сопоставлении свойств MSBuild (проект в стиле SDK) со свойствами в NUSPEC-файле см. в разделе о целевых объектах пакета. Описание свойств см. в справочнике по NUSPEC-файлу. Все свойства добавляются в манифест .nuspec , который Visual Studio создает для проекта.
[!Important] Необходимо присвоить пакету идентификатор, который будет уникальным на сайте nuget.org или другом используемом узле. При работе с этим руководством мы рекомендуем добавить к имени слово «Sample» или «Test», так как позже, после публикации, пакет станет общедоступным (хотя маловероятно, что кто-то будет его использовать).
При попытке опубликовать пакет с именем, которое уже занято, появится сообщение об ошибке.
Необязательно. Чтобы просматривать свойства непосредственно в файле проекта, щелкните правой кнопкой мыши проект в обозревателе решений и выберите Edit AppLogger.csproj (Изменить AppLogger.csproj).
Этот параметр доступен для проектов, использующих атрибут стиля пакета SDK, только в версиях начиная с Visual Studio 2017. Если у вас другой сценарий, щелкните проект правой кнопкой мыши и выберите пункт Выгрузить проект. Затем щелкните правой кнопкой мыши выгруженный проект и выберите команду изменения AppLogger.csproj.
Выполнение команды pack
Выберите конфигурацию Выпуск.
Щелкните проект правой кнопкой мыши в окне обозревателя решений и выберите команду Паковать:
Если команда Pack не отображается, проект, скорее всего, не разработан в стиле SDK. В таком случае нужно использовать CLI nuget.exe . Перенесите проект и используйте CLI dotnet , или ознакомьтесь с пошаговыми инструкциями по созданию и публикации пакета .NET Framework.
Visual Studio создаст проект и файл .nupkg . Ознакомьтесь с результатами в окне выходных данных (пример приведен ниже), где содержится путь к файлу пакета. Обратите внимание, что созданная сборка находится в папке bin\Release\netstandard2.0 , которая является целевой для .NET Standard 2.0.
(Необязательно) Создание пакета при сборке
Вы можете настроить в Visual Studio автоматическое создание пакета NuGet при сборке проекта.
В обозревателе решений щелкните правой кнопкой мыши проект и выберите пункт Свойства.
На вкладке Пакет выберите Создать пакет NuGet при сборке.
[!NOTE] При автоматическом создании пакета время на упаковку увеличивает время сборки проекта.
(Необязательно) Упаковка с помощью MSBuild
В качестве альтернативы команде меню Pack в NuGet 4.x+ и MSBuild 15.1+ можно использовать целевой объект pack , когда проект содержит необходимые данные о пакете. Откройте командную строку, перейдите в папку проекта и запустите приведенную ниже команду. (В общем случае следует запустить Командную строку разработчика для Visual Studio из меню «Пуск», так как в этом случае настраиваются все необходимые пути для MSBuild.)
Дополнительные сведения см. в разделе Создание пакета с помощью MSBuild.
Получив файл .nupkg , опубликуйте его на сайте nuget.org, используя интерфейс командной строки nuget.exe или dotnet.exe , а также ключ API, полученный на этом сайте.
Получение ключа API
Публикация с помощью CLI dotnet или CLI nuget.exe
Выберите вкладку для своего инструмента CLI: .NET Core CLI (для CLI dotnet) или NuGet (для CLI nuget.exe).
Этот шаг — рекомендуемая альтернатива использования nuget.exe .
Перед публикацией пакета сначала нужно открыть командную строку.
Эту команду можно использовать вместо dotnet.exe .
Откройте командную строку и перейдите к папке с файлом .nupkg .
Выполните следующую команду, указав имя пакета (уникальный идентификатор пакета) и заменив значение ключа ключом API:
nuget.exe отображает результаты публикации:
Ознакомьтесь со сведениями о команде nuget push.
Управление опубликованным пакетом
Добавление файла сведений и других файлов
Чтобы напрямую указать файлы, включаемые в пакет, измените файл проекта и используйте свойство content :
Nupkg как добавить в visual studio
Вместо создания своих собственных библиотек и определения своего собственного функционала мы можем использовать уже ранее созданные другими разработчиками библиотеки и добавить их свой проект. Для управления внешними библиотеками в виде отдельных пакетов Microsoft предоставляет специальный менеджер пакетов под названием Nuget .
Физически NuGet-пакет представляет единый архивный файл с расширением .nupkg, который содержит скомпилированный код в виде библиотек dll и других файлов, используемых в коде. Также пакет включает некоторое описание в виде номера версии и вспомогательной информации.
Для упрощения работы с пакетами, их распространенния Microsoft организовал глобальный репозиторий пакетов в виде сервиса nuget.org . И если разработчик хочет поделиться своими наработками, он может загрузить свой код в виде Nuget-пакета в этот репозиторий, а другие разработчики могут скачать этот пакет и использовать его в свой программе. Посмотрим, как устанавливать Nuget-пакеты и использовать их в своем проекте. Прежде всего стоит отметить, что есть различные способы установки пакетов. В данном случае рассмотрим установку пакетов с помощью .NET CLI и в Visual Studio.
Установка nuget-пакетов с помощью .NET CLI
Если мы компилируем приложение непосредственно с помощью .NET CLI без каких-нибудь сред разработки типа Visual Studio, то мы можем воспользоваться встроенными инструментами, которые имеются в .NET SDK.
Для примера создадим с помощью .NET CLI новый проект консольного приложения:
Для примера возьмем такой популярный Nuget-пакет как Newtonsoft.Json , который предназначен для работы с кодом json. Для этого перейдем в терминале к расположению проекта и выполним команду:
После команды dotnet add package указывается имя пакета:
если после этого мы откроем файл конфигурации проекта с расширением csproj , то встретим там элемент PackageReference , который представляет добавленный пакет
Здесь мы видим атрибут Include , который указывает на название пакета для включения в проект, и атрибут Version — версию пакета.
Пакет добавили, теперь используем его. Для этого определим следующий код программы:
С помощью вызова статического метода JsonConvert.SerializeObject(tom) сериализуем объект tom в код json и потом этот код выводим на консоль.
Запустим проект командой dotnet run и посмотрим на результат программы:
Таким образом, мы установили в проект Nuget-пакет и использовали его функциональность в своей программе. Если впоследствии пакет станет не нужен, то его можно удалить командой:
После команды dotnet remove package указывается название удаляемого пакета.
Установка пакета в Visual Studio
Visual Studio обладает богатым функционалом в плане работы с nuget-пакетами. Так, возьмем также простейший проект консольного приложения и добавим в него тот же пакет Newtonsoft.Json . Для этого нажмем правой кнопкой на название проекта и в контекстном меню выберем Manage NuGet Packages. :
Нам откроется встроенный менеджер пакетов Nuget:
Для упрощения поиска нужного пакета введем название пакета в поле поиска. После этого список пакетов обновится. И обычно первый пакет в этом списке тот, который нужен. При необходимости в правой части мы можем посмотреть информацию о пакете.
Итак, нажмем на кнопку Install для его установки. Далее может отобразиться дополнительное окно для просмотра пакетов, которые непосредственно будут установлены:
После установки в структуре проекта появится узел Packages с установленным пакетом, и соответствующая запись будет внесена в файл конфигурации проекта:
И теперь мы также сможем использовать функциональность пакета в программе.
В качестве альтернативы для добавления пакетов можно использовать Package Manager Console . Для этого в меню Visual Studio перейдем к пункту Tools -> NuGet Package Manager -> Package Manager Console . И в открывшемся внизу в Visual Studio окне Package Manager Console введем команду:
Формат: после команды Install-Package указывается название устанавливаемого пакета.