Giter Site home page Giter Site logo

dnt's Introduction

DNT (DotNetTools)

Command line tools to manage .NET Core, Standard and SDK-style projects and solutions

NuGet Version npm

Command and parameter names may improve or change over time. Please create issues or PRs if you'd like to fix, change or add a command.

Installation

.NET Core global tool

Requires .NET Core 2.2+ and Visual Studio 2019

Install .NET Core global tool:

dotnet tool install -g dnt

Update the global tool:

dotnet tool update -g dnt

Uninstall the tool:

dotnet tool uninstall -g dnt

NPM CLI package

Requires .NET Core 2.2+ or NetFX 4.7.2 and Visual Studio 2019

Globally install/update via NPM (.NET 4.6.2+ and .NET Core 2.1+):

npm i -g dotnettools

Uninstall global package:

npm uninstall -g dotnettools

Usage

By default, all commands search in the current directory for all *.csproj files and apply the command to all of them. The targeted projects or solutions can be changed with the /path:MyProject.csproj parameter.

To list all currently selected projects, call:

dnt list-projects

dnt list-projects /path:MySolution.sln

Available commands:

Possible scenarios to use the tools:

Package Commands

install-packages

Installs a NuGet package in the selected projects.

Command:

dnt install-packages PackageToInstall [TargetPackageVersion] [/path:ProjectDirectoryPath]

Parameters:

  • PackageToInstall
  • TargetPackageVersion
  • ProjectDirectoryPath

update-packages

Updates NuGet packages in the selected projects.

Command:

dnt update-packages PackagesToUpdate [TargetPackageVersion] [/path:ProjectDirectoryPath]

Parameters:

  • PackagesToUpdate: The package ID to update, also supports * wildcards
  • TargetPacketVersion: The targeted package version (default: latest)
  • ProjectDirectoryPath

Samples:

Update all packages in the selected projects to the latest version:

dnt update-packages *

Update the Newtonsoft.Json packages in the selected projects to version 10.0.1:

dnt update-packages Newtonsoft.Json 10.0.1

Update all packages which start with MyPackages. to version 2.1.0 in the selected projects:

dnt update-packages MyPackages.* 2.1.0

bump-versions

Increases or changes the package version of the selected projects.

Command:

dnt bump-versions major|minor|patch|revision [number]

Parameters:

  • Action: Specifies the version segment to bump (major|minor|patch|revision) by 1 or by the specified number
  • Number: The version to bump up to (if not specified: Increase by 1)

Samples:

Bump the minor version of all selected projects by 1:

dnt bump-versions minor

Set the patch version of all selected projects to 18:

dnt bump-versions patch 18

switch-to-projects

This command switches NuGet assembly references to project references and vice-versa. This is useful when developing applications/libraries which reference own NuGet packages: When developing an application, switch to project references so that all code is editable and debuggable. After finishing the development, create new NuGet package versions, switch back to NuGet references and upgrade to the new NuGet versions.

This command supports .csproj, .vbproj, legacy and SDK-style projects (.NET Core/Standard). Previously it was implemented as a Visual Studio extension: NuGetReferenceSwitcher.

Usage

Create a switcher.json file and specify the solution to look for projects, and the NuGet packages to replace with actual projects. The involved projects are only specified by the solution path in the settings file.

The command supports switching to project references where the NuGet package is built from a single project or when it is built from multiple projects, i.e. the package contains multiple libraries.

Sample - single project per package: Here we create a switcher file for NSwag which references libraries of NJsonSchema to work on both projects in a single solution:

{
  "solution": "NSwag.sln",
  "mappings": {
    "NJsonSchema": "../../NJsonSchema/src/NJsonSchema/NJsonSchema.csproj",
    "NJsonSchema.CodeGeneration": "../../NJsonSchema/src/NJsonSchema.CodeGeneration/NJsonSchema.CodeGeneration.csproj",
    "NJsonSchema.CodeGeneration.CSharp": "../../NJsonSchema/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj",
    "NJsonSchema.CodeGeneration.TypeScript": "../../NJsonSchema/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj"
  }
}

Sample - multiple projects per package: Here we create a switcher file for a sample solution which references multiple libraries included (as dependencies) in the UA-.NETStandard OPCFoundation.NetStandard.Opc.Ua package in order to work on all the projects in a single solution.

{
  "solution": "MyOpcUaApp.sln",
  "mappings": {
    "OPCFoundation.NetStandard.Opc.Ua": [
      "../UA-.NETStandard/Stack/Opc.Ua.Core/Opc.Ua.Core.csproj",
      "../UA-.NETStandard/Stack/Opc.Ua.Bindings.Https/Opc.Ua.Bindings.Https.csproj",
      "../UA-.NETStandard/Libraries/Opc.Ua.Security.Certificates/Opc.Ua.Security.Certificates.csproj",
      "../UA-.NETStandard/Libraries/Opc.Ua.Configuration/Opc.Ua.Configuration.csproj",
      "../UA-.NETStandard/Libraries/Opc.Ua.Client/Opc.Ua.Client.csproj",
      "../UA-.NETStandard/Libraries/Opc.Ua.Server/Opc.Ua.Server.csproj",
      "../UA-.NETStandard/Libraries/Opc.Ua.Gds.Client.Common/Opc.Ua.Gds.Client.Common.csproj",
      "../UA-.NETStandard/Libraries/Opc.Ua.Gds.Server.Common/Opc.Ua.Gds.Server.Common.csproj",
    ]
  }
}

Then switch to projects in the solution:

dnt switch-to-projects

The command looks for switcher.json configuration file by default, but you can specify your own file:

dnt switch-to-projects switch-config.json

Now all NJsonSchema, or UA-.NETStandard, package references in the NSwag, or MyOpcUaApp, solution are replaced by local project references and the NJsonSchema, or UA-.NETStandard, projects are added to the solution.

Optional switcher.json Flags:

  • removeProjects: (Default: true) Removes mapped projects from the solution and ignores mapped projects when using switch-to-packages.

switch-to-packages

After implementing and testing, switch back to NuGet references and update to the latest version:

dnt switch-to-packages
dnt update-packages NJsonSchema*
# or
dnt update-packages OPCFoundation.NetStandard.Opc.Ua.*

used-packages

Lists all used packages, transitive packages in the projects and their licenses.

Parameters:

  • ExcludeMicrosoft (default: true): Exclude packages which start with Microsoft.*
  • ExcludeSystem (default: true): Exclude packages which start with System.*
  • IncludeTransitiveDependencies (default: true): Also analyze transitive dependencies (i.e. indirectly referenced packages)

Sample output for NJsonSchema:

Package                              Version   #   License   License URL
BenchmarkDotNet                      0.10.14   1   MIT       https://github.com/dotnet/BenchmarkDotNet/blob/master/LICENSE.md
BenchmarkDotNet.Core                 0.10.14   4   MIT       https://github.com/dotnet/BenchmarkDotNet/blob/master/LICENSE.md
BenchmarkDotNet.Toolchains.Roslyn    0.10.14   1   MIT       https://github.com/dotnet/BenchmarkDotNet/blob/master/LICENSE.md
DotLiquid                            2.0.254   1   Apache    http://www.apache.org/licenses/LICENSE-2.0
NBench                               1.0.4     2   Apache    https://github.com/petabridge/NBench/blob/master/LICENSE
Newtonsoft.Json                      9.0.1     4   MIT       https://raw.github.com/JamesNK/Newtonsoft.Json/master/LICENSE.md
NodaTime                             2.2.0     2   Apache    http://www.apache.org/licenses/LICENSE-2.0
Pro.NBench.xUnit                     1.0.4     1   MIT       https://raw.githubusercontent.com/Pro-Coded/Pro.NBench.xUnit/master/LICENSE
xunit                                2.3.1     7   Apache    https://raw.githubusercontent.com/xunit/xunit/master/license.txt
xunit.abstractions                   2.0.1     2   Apache    https://raw.githubusercontent.com/xunit/xunit/master/license.txt
xunit.analyzers                      0.7.0     1   Apache    https://raw.githubusercontent.com/xunit/xunit.analyzers/master/LICENSE
xunit.assert                         2.3.1     1   Apache    https://raw.githubusercontent.com/xunit/xunit/master/license.txt
xunit.core                           2.3.1     1   Apache    https://raw.githubusercontent.com/xunit/xunit/master/license.txt
xunit.extensibility.core             2.3.1     3   Apache    https://raw.githubusercontent.com/xunit/xunit/master/license.txt
xunit.extensibility.execution        2.3.1     1   Apache    https://raw.githubusercontent.com/xunit/xunit/master/license.txt
xunit.runner.visualstudio            2.3.1     6   Apache    https://raw.githubusercontent.com/xunit/xunit/master/license.txt
YamlDotNet.Signed                    5.0.1     1   MIT       https://github.com/aaubry/YamlDotNet/blob/master/LICENSE

switch-assemblies-to-projects

Looks through all the projects for assembly/DLL references that could instead be project references in the same solution.

The command does make the assumption that the assembly output of a project has the same name as the project.

dnt switch-assemblies-to-projects

Looks for references like

<Reference Include="ProjectA">
  <HintPath>..\ProjectA\bin\ProjectA.dll</HintPath>
</Reference>

And replaces with

<ProjectReference Include="..\ProjectA\ProjectA.csproj">
  <Project>{B12406B0-0468-4809-91E3-7991800E3ECD}</Project>
  <Name>ProjectA</Name>
</ProjectReference>

Project Commands

enable

Enables a project feature in all selected projects.

Command:

dnt enable warnaserror|xmldocs

Parameters:

  • Action: Specifies the feature to enable (warnaserror|xmldocs)

Samples:

Handle all warnings as errors in all selected projects:

dnt enable warnaserror

nowarn

Adds a diagnostic id to the <NoWarn> tag (supports muliple ids, semicolon separated).

Samples:

Disable "Missing XML comment for publicly visible type or member" warnings in all selected projects:

dnt nowarn CS1591

add-target-framework

Add another target framework to the selected projects.

Command:

dnt add-target-framework TargetFramework

Parameters:

  • TargetFramework: Specifies the target framework to add

Samples:

Add .NET Standard 2.0 target framework to all projects:

dnt add-target-framework netstandard2.0

clean

Deletes all /bin and /obj directories of the selected projects.

change-versions

Replaces or sets the package version of the selected projects. Projects must have the GeneratePackageOnBuild flag set.

Command:

dnt change-versions version [replace|force]

Parameters:

  • Version: The full version number using the format 'major.minor[.patch][.revision]'. Version will be padded to three parts.
  • Action: Action to perform (replace|force). replace (default) = Only set for projects with an existing version, force = Set for all projects even if version is missing or blank

Samples:

Replace projects with an existing version tag with 1.0.1:

dnt change-versions 1.0.1

Force set all projects to 1.2.0

dnt change-versions 1.2 force

Replace version with a long version:

dnt change-versions 1.2.3.4-PreRelease1 replace

DNT development and testing

It is recommended to add the debug output path "DNT/src/Dnt.NetFx/bin/Debug" to the Path environment variable, or directly start the app with a command.

dnt's People

Contributors

0x15e avatar alex1001xela avatar bvandehey avatar heikiv avatar ian1971 avatar jethas-bennettjones avatar jzabroski avatar kimsey0 avatar lkurzyniec avatar loafingaround avatar maartenbe avatar mikamikem avatar mkrolewicz avatar rgr21 avatar richard-sage avatar ricosuter avatar schlotter avatar shaharprishmsft avatar shaosss avatar tentacule avatar thecontrarycat avatar thystonius avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dnt's Issues

dnt fails to run on macos

When i run dnt I just get:

โžœ dnt
Unhandled exception. System.IO.FileLoadException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
File name: 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

[1] 18864 abort dnt


More Information:

I did install netcore using brew, but i have the same issue if I install from from https://dotnet.microsoft.com/download/dotnet-core/3.1

Then I installed the dnt tool globally with:

$ dotnet tool install --global dnt

Because I use zsh, I added this to my rc file:

export PATH="$PATH:$HOME/.dotnet/tools"

I'm using macos catalina 10.15.7.

dotnet info:


โžœ dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.110
 Commit:    f02c158773

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.15
 OS Platform: Darwin
 RID:         osx.10.15-x64
 Base Path:   /usr/local/Cellar/dotnet/3.1.110/libexec/sdk/3.1.110/

Host (useful for support):
  Version: 3.1.10
  Commit:  2b1abb2399

.NET Core SDKs installed:
  3.1.110 [/usr/local/Cellar/dotnet/3.1.110/libexec/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.App 3.1.10 [/usr/local/Cellar/dotnet/3.1.110/libexec/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 3.1.10 [/usr/local/Cellar/dotnet/3.1.110/libexec/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Is a Demo-Project available?

Validating and debugging dnt is not easy. It needs a complex structure of packages and dlls in multiple solutions to try all variants.

My existing projects are not very useful, when i want to show bugs or suggestions regarding dnt.

I think, someone mentioned it before:
Is there a Demo-Project somewhere on github, that could be used? Just a bunch of solutions for packages, batches for creating local packages and solutions using this packages?
If not, i would help creating such demo, when there is a demand or help from other users.

OTH: what project from github ca be used to debug dnt? It would be easier, if the developers use the same sources. I can't upload part of my programs. They won't work or are too large.

DNT fails with "Could not load file or assembly 'System.Runtime, Version=6.0.0.0'"

Issue: dnt fails with FileNotFoundException, "Could not load file or assembly 'System.Runtime, Version=6.0.0.0'"

Repro:

Run dnt switch-to-projects on a machine with VS 2022 preview 4 installed.

Expected: dnt runs to completion.
Actual: dnt fails with exception

Example:
d:\mse\NSwag\src>dnt switch-to-projects
DNT (DotNetTools, https://github.com/RSuter/DNT, v1.6.4.0)
Binary: C:\Users\maxw.dotnet\tools.store\dnt\1.6.4\dnt\1.6.4\tools\net5.0\any\dnt.dll

System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
File name: 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.AddProjectsToSolutionAsync(ReferenceSwitcherConfiguration configuration, IConsoleHost host)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.AddProjectsToSolutionAsync(ReferenceSwitcherConfiguration configuration, IConsoleHost host)
at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\dnt\src\Dnt.Commands\Packages\SwitchPackagesToProjectsCommand.cs:line 28
at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
at NConsole.CommandLineProcessor.Process(String[] args, Object input)
at Dnt.Program.Main(String[] args) in C:\projects\dnt\src\Dnt\Program.cs:line 33
Elapsed time: 00:00:00.5176615

Workaround:
I was able to work around the issue by building dnt from source with net6.0.

Environment:
Windows, VS 2022 installed
Dotnet version: 6.0.100-rc.1.21463.6

SDK fails to load when running with NET 5 RC2 installed

After installing the latest VS Preview version and thus the latest NET 5 RC2 version, DNT operations now fail (unless pinned back to 3.1 with a global.json) on loading System.Runtime v5.0.0.

My specific case was a simple switch-to-packages with one NuGet defined in teh switcher file.
After pinning back to 3.1 and rerunning same command on the same sln/nuget, works as expected.

Projects themselves or the nuget aren't compiled to NET5 and there's no project in the repository that is targetted that way - only netstandard2.0 and netcoreapp3.x (as well as some netfx 4.7.2 but i imagine that's irrelevant here)

switch-to-projects: does not remove Packages

When i use switch-to-projects, it includes the projects (multiple dlls) of the package, but does not remove the package from my solution.
The projects, where the package has to be removed do not get references to the newly included sources.

the .dnt-File gets a property "restore": [], but it is empty.

I donยดt get any errormessages.

[edit]managed to debug dnt[/edit]
I am using VS 2019 16.7.2

Dependency on cmd.exe prevents usage on non-Windows platforms

I am trying to use this on MacOS and am running into a "No such file or directory error."

After some debugging, it looks like the error occurs at the dotnet sln add command that happens at SwitchPackagesToProjectsCommand.cs:50. Specifically, since there's no cmd.exe on non-Windows platforms, anything using ProcessUtilities.ExecuteAsync will fail. That said, it looks like making calls to dotnet directly (such as in Program.SetMsBuildExePath) works fine.

What do you think would be the best approach to making DNT work on more platforms than Windows? It looks like everywhere ExecuteAsync is used, the first command is a single word so it might be easy enough to split the command argument to find out the real process filename but I'm not sure if that would be the best approach.

I'm happy to help with testing, code, etc.

used-packages error: Can't find Microsoft.Build.Framework

.NET SDK 2.2.401 on Mac
DNT 1.2.5 installed via NPM.

Using dnt used-packages

Output:

DNT (DotNetTools) NPM CLI
Error:
  An assembly specified in the application dependencies manifest (dnt.deps.json) was not found:
    package: 'Microsoft.Build.Framework', version: '16.0.461'
    path: 'lib/netstandard2.0/Microsoft.Build.Framework.dll'
child_process.js:661
    throw err;
    ^

Error: Command failed: dotnet "/usr/local/lib/node_modules/dotnettools/bin/binaries/NetCore22/dnt.dll" used-packages
    at checkExecSyncError (child_process.js:621:11)
    at Object.execSync (child_process.js:658:15)
    at /usr/local/lib/node_modules/dotnettools/bin/dnt.js:52:11
    at ChildProcess.exithandler (child_process.js:285:7)
    at ChildProcess.emit (events.js:200:13)
    at maybeClose (internal/child_process.js:1021:16)
    at Socket.<anonymous> (internal/child_process.js:430:11)
    at Socket.emit (events.js:200:13)
    at Pipe.<anonymous> (net.js:586:12) {
  status: 140,
  signal: null,
  output: [ null, null, null ],
  pid: 70486,
  stdout: null,
  stderr: null
}

Updated .NET SDK to latest, no luck.

problem with special characters in solution name and/or path

I have this project where a ยต is in solution name and path. The switcher.json file shows the characters ok

{
  "solution": "ยตCliMat.Expert.sln",
  "mappings": {
    "c8.IO": "../../c8.core/c8.core-dotnet/src/c8.IO/c8.IO.csproj",
    "c8.Security": "../../c8.core/c8.core-dotnet/src/c8.Security/c8.Security.csproj",
    "c8.Updater": "../../c8.core/c8.core-dotnet/src/c8.Updater/c8.Updater.csproj"
  },
  "removeProjects": true
}

but when running DNT to switch to the project I get this error:

DNT (DotNetTools, https://github.com/RSuter/DNT, v1.7.0.0)
Binary: C:\Users\tomdw\.dotnet\tools\.store\dnt\1.7.0\dnt\1.7.0\tools\net6.0\any\dnt.dll

Microsoft.Build.Exceptions.InvalidProjectFileException: The project file could not be loaded. Could not find file 'D:\Git.Planio\c8.รฆclimat\รฆCliMat.Expert\?CliMat.Expert.sln'.  D:\Git.Planio\c8.รฆclimat\รฆCliMat.Expert\?CliMat.Expert.sln
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, BuildEventFileInfo projectFile, String resourceName, Object[] args)
   at Microsoft.Build.Construction.SolutionFile.ParseSolutionFile()
...

notice how the 'ยต' in the folder name is shown as 'รฆ', where as the 'ยต' in the solution name is show as '?'

Thanks for any help

[solved] Trouble with project / package switcher for old web application projects

In case you want to document it or it helps anyone, I had trouble getting the project / package switching to work on .net framework web application projects.
I fixed it by copying contents of C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\WebApplications to C:\Program Files\dotnet\sdk\2.2.100\Microsoft\VisualStudio\v15.0\WebApplications (actual folders may vary I guess depending on what you have installed).
In particular it was complaining about missing Microsoft.WebApplication.targets

Tool is not finding switcher.json

Using v1.6.1.0

I'm running dnt switch-to-projects from the root of my solution, which is also where switcher.json is located. The tool always prompts me for the name of the config file.

image

switch-to-projects: NuGet package that is built from multiple projects

I am trying to switch between a nuget package that is referenced in my solution and the sources that are in another solution (not maintained by me). The issue is that one nuget dependency is built from several projects. There does not seem to be a way for the switcher to cope with this. I have tried adding an array to my switcher.json:

{
  "solution": "MySolution.sln",
  "mappings": {
    "NameOfNugetReference": [
		"../OtherSolution/Project1.csproj",
		"../OtherSolution/Project2.csproj",
		"../OtherSolution/Project3.csproj",
	]
  }
}

Which gives the result:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: [.

I also tried adding several mappings for the same nuget reference:

{
  "solution": "MySolution.sln",
  "mappings": {
    "NameOfNugetReference": "../OtherSolution/Project1.csproj",
    "NameOfNugetReference": "../OtherSolution/Project2.csproj",
    "NameOfNugetReference": "../OtherSolution/Project3.csproj",
  }
}

But then only Project3 is added to MySolution.

Is there a good way to handle this situation?

dnt install-packages: PackageToInstall should be optional

The signature should be:

dnt install-packages [PackageToInstall] [TargetPackageVersion] [/path:ProjectDirectoryPath]

When run, it should recurse the entire solution, gather all packages, and install all package references across the solution.

Package switcher error finding Microsoft.NET.Sdk

When I run dnt switch-to-projects my-switch-file.dnt, I get an error for each .NET Standard project that says:

The project 'C:\path\my-project.csproj' could not be loaded: The SDK 'Microsoft.NET.Sdk' specified could not be found.  C:\path\my-project.csproj                                                                                   

And the same error for each ASP.NET Core project in the solution, except with Microsoft.NET.Sdk.Web.

The opening tags of each csproj file are as you would expect, <Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk.Web">.

I have found others online who have encountered this error in other contexts but no fixes have worked so far in my case.

This very well may be an issue with my environment rather than DNT, but I would very much like to be able to use this tool, so I wanted to check if this is something you've seen while using DNT and if you know what my issue might be.

Unexpected winfx errors

When running dnt switch-to-projects switcher.json I get for every csproj the following error:

The project '...\TestProject.csproj' could not be loaded: The imported project "E:\Microsoft.WinFx.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk. C:\Program Files (x86)\MSBuild\14.0\Bin\Microsoft.WinFX.targets

This targets file contains the following import statement:

It looks like the variable $(MSBuildFrameworkToolsPath) is not set.

Any why is DNT taking the targets file from the Visual Studio 2015 (14.0) context?

My setup:

  • Visual Studio 2017 15.9.6
  • Visual Studio 2015 aside

ฮป dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 2.1.503
Commit: 4c506e0f35

Runtime Environment:
OS Name: Windows
OS Version: 6.3.9600
OS Platform: Windows
RID: win81-x64
Base Path: C:\Program Files\dotnet\sdk\2.1.503\

Host (useful for support):
Version: 2.1.7
Commit: cca5d72d48

Source code analysis
Potential issue with the following code:
image

This code resolves to a location on C-drive whereas I have the bits residing at D-drive. We need to fix the msbuild resolving logic. Potentially reading from registy location. See https://stackoverflow.com/questions/328017/path-to-msbuild

Or maybe better to leverage the .NET Core SDK using msbuild.dll e.g. in path C:\Program Files\dotnet\sdk\2.1.503. Is there an API? E.g. https://github.com/dotnet/cli/blob/release/2.1.502/src/Microsoft.DotNet.MSBuildSdkResolver/MSBuildSdkResolver.cs

I don't think this will work because the legacy csproj files are referring targets that are not present within the .NET Core context:

  • Microsoft\VisualStudio\v10.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets
  • Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets

Ultimately ToolLocationHelper.GetPathToBuildToolsFile should work in a .NET Core context as well, ref dotnet/msbuild#4013

used-packages: "Not a project" exception when importing custom props file from $(SolutionDir)

It seems using dnt used-packages defines SolutionDir in an unexpected way: Projects which include a custom import of a props file fail with a "Not a project" exception:

<Import Project="$(SolutionDir)Scripts\CommonSettings.props" />

When running dnt used-packages /path:C:\Repos\MyRepo\Build\MySolution.sln, the exception is:

System.InvalidOperationException: Not a Project: C:\Repos\MyRepo\Build\..\Project\Project.csproj
 ---> Microsoft.Build.Exceptions.InvalidProjectFileException: The imported Project "C:\Repos\MyRepo\ProjectScripts\CommonSettings.props" was not found. Confirm that the expression in the Import declaration "C:\Repos\MyRepo\Build\..\ProjectScripts\CommonSettings.props" is correct, and that the file exists on disk.  C:\Repos\MyRepo\Project\Project.csproj

The correct value of SolutionDir is C:\Repos\MyRepo\Build\, so $(SolutionDir)Scripts\CommonSettings.props should resolve to C:\Repos\MyRepo\Build\Scripts\CommonSettings.props. The path of the project file in this example is C:\Repos\MyRepo\Build\..\Project\Project.csproj or C:\Repos\MyRepo\Project\Project.csproj.

Observed behavior

C:\Repos\MyRepo\Project is used as a value for SolutionDir.

Expected behavior

Use C:\Repos\MyRepo\Build\ as value for SolutionDir.

Version info

DNT (DotNetTools, https://github.com/RSuter/DNT, v1.6.1.0)

Minor - PackageReference format

From what I've seen, tools will have the PackageReference node look like this:

<PackageReference Include="SomePackage" Version="1.2.2.2" />

But when using dnt to switch back to project reference, it generates the node like this:

<PackageReference Include="SomePackage">
  <Version>1.2.2.2</Version>
</PackageReference>

Both works. The small problem here is more about code reviews. We end up requiring manually altering back the nodes because of strict code review rules.

There are two solutions:

  • Generate the node in the same format as the other tools (always)
  • Try to infer which to use by interpreting the xml and prefer one of the two.

Support for <Import tag in `switch-to-projects`

Hi,
I started reusing CsProj files by extracting repetative pieces to .proj files. But, if some internal nuget is this common .proj file, it is not switched using the switch-to-projects command, coz it's not traversed recursivelly.

If its ok i'll prepare a PR with that change.

switch-to-packages removing projects under solution folders

I have some projects under a solution folder (the one created by right-click solution > Add > New Solution Folder).

Whenever I invoke switch-to-packages, it modifies the .sln file, removing these projects, which is unexpected (other projects are unaffected).

InvalidCastException when mixing "single project per package" and "multiple projects per package"

When mixing "single project per package" and "multiple projects per package" in switcher.json eg:

{
  "solution": "MySolution.sln",
  "mappings": {
    "SimpleNuget": "../SimpleProject/SimpleProject.csproj",
    "ComplexNuget": [
      "../ComplexProject.PartA/ComplexProject.PartA.csproj",
      "../ComplexProject.PartB/ComplexProject.PartB.csproj"
    ]
  }
}

Calling dnt switch-to-projects will produce a System.InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken.

I helped myself by refactoring switcher.json to the following scheme:

{
  "solution": "MySolution.sln",
  "mappings": {
    "SimpleNuget": [
      "../SimpleProject/SimpleProject.csproj"
    ],
    "ComplexNuget": [
      "../ComplexProject.PartA/ComplexProject.PartA.csproj",
      "../ComplexProject.PartB/ComplexProject.PartB.csproj"
    ]
  }
}

Using arrays with one element did the trick.

However, after replacing the package references, dnt persisted its restore information back into switcher.json. By doing so it also reverted the JArrays with one elemet back to simple JTokens.

Which means, that for the subsequent call dnt switch-to-packages, I again have to manually refactor each single project per package in switcher.json, or otherwise another System.InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken. is produced.

The complete exception stack for both cases:

System.InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken.
   at Newtonsoft.Json.Linq.Extensions.Convert[T,U](T token)
   at Newtonsoft.Json.Linq.Extensions.Value[T,U](IEnumerable`1 value)
   at Newtonsoft.Json.Linq.Extensions.Value[U](IEnumerable`1 value)
   at Dnt.Commands.Packages.Switcher.SingleOrArrayConverter.<>c.<ReadJson>b__1_1(JProperty val) in C:\projects\dnt\
src\Dnt.Commands\Packages\Switcher\SingleOrArrayConvertor.cs:line 25
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 e
lementSelector, IEqualityComparer`1 comparer)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 e
lementSelector)
   at Dnt.Commands.Packages.Switcher.SingleOrArrayConverter.ReadJson(JsonReader reader, Type objectType, Object exi
stingValue, JsonSerializer serializer) in C:\projects\dnt\src\Dnt.Commands\Packages\Switcher\SingleOrArrayConvertor
.cs:line 25
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, Js
onReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConver
ter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader,
Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader
, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, J
sonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, O
bject existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type object
Type, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMe
mber, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Bo
olean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
   at Dnt.Commands.Packages.Switcher.Refe   at Dnt.Commands.Packages.Switcher.ReferenceSwitcherConfiguration.Load(String fileName, IConsoleHost host) in C:\projects\dnt\src
   at Dnt.Commands.Packages.Switcher.Refe   at Dnt.Commands.Packages.Switcher.ReferenceSwitcherConfiguration.Load(String fileName, IConsoleHost host) in C:\projects\dnt\src\Dn
t.Commands\Packages\Switcher\ReferenceSw    at Dnt.Commands.Packages.Switcher.ReferenceSwitcherConfiguration.Load(String fileName, IConsoleHost host) in C:\projects\dnt\src\Dn
   at Dnt.Commands.Packages.Switcher.ReferenceSwitcherConfiguration.Load(String fileName, IConsoleHost host) in C:\projects\dnt\src\Dnt.Commands\Packages\Switcher\ReferenceSwit
cherConfiguration.cs:line 43
   at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\dnt\src\Dnt.Commands\Packages\SwitchPacka
gesToProjectsCommand.cs:line 22
   at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
   at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
   at NConsole.CommandLineProcessor.Process(String[] args, Object input)
   at Dnt.Program.Main(String[] args) in C:\projects\dnt\src\Dnt\Program.cs:line 33

switch-to-packages is flattening solution structure

We have a Visual Studio solution with a set of nested hierarchical folders with items outside solution projects. After running switch-to-packages these nested folders are all flattened.

Expected behavior;
dnt should not touch the hierarchical structure of the sln file.

After some research it appears that the dotnet sln remove command is responsible for this behavior.

dotnet.exe --version
2.1.503

Repro can be found here: https://github.com/cveld/dotnet-cli-sln-remove-issue

NPM version of switch-to-packages and -projects broken after latest VS update

I am using the NPM version due to having full .NET framework projects in my solution.
After updating to the latest version of Visual Studio (16.9.2) all projects are failing to switch with the following error:

The project '{pathTo/myProj.csproj}' could not be loaded: System.InvalidOperationException: Not a project: {pathTo/myProj.csproj} ---> Microsoft.Build.Exceptions.InvalidProjectFileException: Invalid static method invocation syntax: "[MSBuild]::AreFeaturesEnabled('16.8')". Method '[MSBuild]::AreFeaturesEnabled' not found. Static method invocation should be of the form: $([FullTypeName]::Method()), e.g. $([System.IO.Path]::Combine(a, b)). Check that all parameters are defined, are of the correct type, and are specified in the right order. C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets
{stack trace}

This is fixed if I delete the offending "AreFeaturesEnabled" PropertyGroup in Microsoft.Common.CurrentVersion.targets,
any ideas why this problem is occurring?

Support for --interactive switch in dnt update-packages

Hi,

When update-packages is used to update packages from a private feed to their latest versions, the underlying dotnet add package call will return 401 unauthorized if it is called without the --interactive switch. To support updating from both authenticated and unauthenticated feeds, I think extending the update-packages function with an additional optional parameter that toggles the --interactive switch would be very useful.

(I can make a PR with the change if that's okay).

Project (csproj, not sln) based switch-to-packages and -projects

Apologies if this is already being tracked elsewhere.

It's becoming more and more common to have a project that isn't under a solution. Are there any plans to support projects that have no parent solution? I just tried this on my end and got an error (see below). In looking at the dnt source it appears that the tools requiring switcher.json require a solution to exist.

Let me know if you'd like help with this (if this is a functionality you'd be interested in). I will have some time toward the end this month to contribute if desired.

System.ArgumentNullException: Value cannot be null. (Parameter 'path2')
   at System.IO.Path.Combine(String path1, String path2)
   at Dnt.Commands.Infrastructure.PathUtilities.ToAbsolutePath(String relativePath, String relativeTo) in C:\projects\dnt\src\Dnt.Commands\Infrastructure\PathUtilities.cs:line 19
   at Dnt.Commands.Packages.Switcher.ReferenceSwitcherConfiguration.get_ActualSolution() in C:\projects\dnt\src\Dnt.Commands\Packages\Switcher\ReferenceSwitcherConfiguration.cs:line 24
   at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.AddProjectsToSolutionAsync(ReferenceSwitcherConfiguration configuration, IConsoleHost host)
   at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\dnt\src\Dnt.Commands\Packages\SwitchPackagesToProjectsCommand.cs:line 24
   at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
   at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
   at NConsole.CommandLineProcessor.Process(String[] args, Object input)
   at Dnt.Program.Main(String[] args) in C:\projects\dnt\src\Dnt\Program.cs:line 33

Switch-to-projects

When using Multi targeted projects using the new .net standard 2.x format of csproj fails to remove the nuget dependencies but will add and remove the project. In my case the package is only added to the .net standard project as below

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
    <Folder Include="NetStandard20\" />
    <PackageReference Include="Package_to_switch">
      <Version>1.0.2</Version>
    </PackageReference>
  </ItemGroup>

  <PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2.0'">
    <DefineConstants>NETCORE;NETSTANDARD;NETSTANDARD2_0</DefineConstants>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net45'">
    <Folder Include="Net45\" />
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Data.DataSetExtensions" />    
    <Reference Include="System.Xml" />
    <Reference Include="System.Xml.Linq" />    
  </ItemGroup>

  <PropertyGroup Condition=" '$(TargetFramework)' == 'net45'">
    <DefineConstants>NET45;NETFULL</DefineConstants>
  </PropertyGroup>
</Project>

Add command to add target framework

dnt add-target-framework netstandard2.0

Inputs

<TargetFramework>net462</TargetFramework>
<TargetFrameworks>net462;netstandard1.3</TargetFrameworks>

Expected outputs

<TargetFrameworks>net462;netstandard2.0</TargetFrameworks>
<TargetFrameworks>net462;netstandard1.3;netstandard2.0</TargetFrameworks>

InvalidProjectFileException

Firstly, thanks for creating this tool - I think it's going to be really useful for me.

Unfortunately when I try to run it I'm running into an issue when using this on a ASPNET core 2.2 app built with VS 2017

These are the steps I followed.

  1. Installed VS 2019
  2. Installed dnt via npm i -g dotnettools
  3. Created a switcher.json file
  4. Ran dnt switch-to-projects switcher.json

After which I received the followiing error:

Microsoft.Build.Exceptions.InvalidProjectFileException: The imported project "C:\Program Files\dotnet\sdk\2.2.105\Current\Microsoft.Common.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.  C:\Program Files\dotnet\sdk\2.2.105\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props

Although it did add the project to the solution but didn't add a reference to the project or remove the nuget package.

So my questions are:

  1. Is there something else I need to do to stop the error?
  2. Should it have added a reference to the project and removed the nuget package?

Thanks again for your hard work.

Azure Pipeline integration

I want to switch to nuget packages during an Azure Pipeline using the switch-to-packages command. I have used the following script step in my pipeline:

- script: |
    dotnet tool install -g dnt
    dnt switch-to-packages switcher.json
    dnt update-packages Menelabs*

Unfortunately the dnt switch-to-packages switcher.json doesn't work and it throws the following error for every project in the solution:

The project 'D:\a\1\s\src\xxx\xxx.csproj' could not be loaded: The imported project "C:\Program Files\dotnet\sdk\2.2.105\Current\Microsoft.Common.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk. C:\Program Files\dotnet\sdk\2.2.105\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props

Is it possible to use dnt tool in an azure pipeline and how i can overcome this exception?

Preserve version placesholders when switching from packages to projects (and back)

Hi Rico

First, thank you for your tools. Switching between packages and project is extremely valuable to me.

However, I am using placeholders throughout my solution for the versions which are defined at a central file on solution level:
<PackageReference Include="My.Library" Version="$(CurrentVersion)" />

However, the restore information is using the actual version number (switching back obviously inserts that one).
{ "solution": "MySolution.sln", "mappings": { "My.Library": "../Libraries/My.Library/My.Library.csproj" }, "restore": [ { "name": "My.Project", "packages": [ { "packageName": "My.Library", "version": "7.2.0-*" } ] } ]

Is there any chance you could preserve the placeholder during the switching process?

Cheers
Marcel

dnt clean-packages

This is effectively clean, but for packages. This is useful if you're switching branches and stuff doesn't get cleaned up, among other reasons.

This is a pre-requisite for me to kill off MSBuild pretty much entirely from my build process, and move to using Microsoft.DotNet.Cli.Utils / buildtools hooks instead.

In my build environment, I currently have MSBuild target defined as:

  <!-- Target: CleanCore -->
  <Target Name="CleanCore">
    <Error Text="SolutionOrProjectFile property is required!" Condition="$(SolutionOrProjectFile) == ''" />
    <Error Text="Configuration property is required!" Condition="$(Configuration) == ''" />
    <Error Text="Platform property is required!" Condition="$(Platform) == ''" />

    <Message Importance="High" Text="Clean: Configuration=[$(Configuration)] Platform=[$(Platform)] SolutionOrProjectFile=[$(SolutionOrProjectFile)]" />

    <MSBuild Projects="$(SolutionOrProjectFile)" Targets="Clean" Properties="Configuration=$(Configuration);Platform=$(Platform);"/>
  </Target>

  <!-- Target: CleanFullCore -->
  <Target Name="CleanFullCore" DependsOnTargets="CleanCore">

    <!-- Create some metadata we can use to discover the source root directory -->
    <CreateItem Include="$(SolutionOrProjectFile)">
      <Output TaskParameter="Include" ItemName="PathMetadata"/>
    </CreateItem>

    <PropertyGroup>
      <SourceDirectory>%(PathMetadata.RootDir)%(PathMetadata.Directory)</SourceDirectory>
    </PropertyGroup>

    <Message Importance="High" Text="$(SourceDirectory)" />

    <!-- Remove NuGet packages-->
    <Message Importance="High" Text="Clean: Removing NuGet packages directory" />
    <RemoveDir Directories="$(SourceDirectory)\packages"/>

    <!-- Remove MSTest Results-->
    <Message Importance="High" Text="Clean: Removing MSTest results directory" />
    <RemoveDir Directories="$(SourceDirectory)\testresults"/>

    <!-- Remove bin/obj folders -->
    <ItemGroup>
      <BinDirectoriesToClean Include="$([System.IO.Directory]::GetDirectories(&quot;$(SourceDirectory)&quot;,&quot;bin&quot;, SearchOption.AllDirectories))"/>
      <ObjDirectoriesToClean Include="$([System.IO.Directory]::GetDirectories(&quot;$(SourceDirectory)&quot;,&quot;obj&quot;, SearchOption.AllDirectories))"/>
    </ItemGroup>

    <Message Importance="High" Text="Clean: Removing obj directories: %(ObjDirectoriesToClean.Identity)" />
    <RemoveDir Directories="@(ObjDirectoriesToClean)" />

    <Message Importance="High" Text="Clean: Removing bin directories: %(BinDirectoriesToClean.Identity)" />
    <RemoveDir Directories="@(BinDirectoriesToClean)" />
  </Target>

dnt switch-to-packages doesn't restore recursive

Following setup:

  • CommonA
    -- CommonA.sln
    -- CommonA
    --- CommonA.csproj
  • CommonB
    -- CommonB.sln
    -- CommonB
    --- CommonB.csproj
  • ConsumcerC
    -- ConsumerC.sln (includes currently only ConsumerC.csproj)
    -- ConsumerC
    --- ConsumerC.csproj

CommonB references CommonA via nuget
ConsumerC references CommonA and CommonB via nuget

Created switcher.json for ConsumerC to replace CommonA and CommonB

{
    "solution": ConsumerC.sln,
    "mappings": {
    "CommonA": "../CommonA/CommonA.csproj",
    "CommonB": "../CommonB/CommonB.csproj"
    }
}

dnt switch-to-project switcher.json

nuget References get switched recursively to project references.
CommonB references CommonA as a project reference!
ConsumerC.csproj references CommonA and CommonB as a project reference!
ConsumerC.sln contains CommonA and CommonB + ConsumerC

dnt switch-to-packages switcher.json

Package references get switched back for ConsumerC.csproj, ConsumerC.sln contains only ConsumerC.csproj. Correct so far. But CommonB.csproj still contains the project reference to CommonA.csproj.

DNT (DotNetTools, https://github.com/RSuter/DNT, v1.2.2.0)

Keep PrivateAssets on switch-to-projects and back

I have a package that is referenced like this:

<PackageReference Include="MyPackage" Version="1.0.0-beta01" PrivateAssets="None" />

When I switch-to-projects and switch-to-packages, the PrivateAssets part is dropped.

Would it be possible to save such properties?

Wildcard versioning not supported

System.ArgumentException: '3.*' is not a valid version string.
Parameter name: value
   at NuGet.Versioning.NuGetVersion.Parse(String value)
   at Dnt.Commands.Packages.ListUsedPackagesCommand.LoadDependenciesAsync(PackageReferenceInfo entry, List`1 packages, List`1 tasks, IConsoleHost host) in C:\projects\dnt\src\Dnt.Commands\Packages\ListUsedPackagesCommand.cs:line 146

3.* means highest version within major 3.

https://docs.microsoft.com/en-us/nuget/reference/package-versioning#version-ranges-and-wildcards

Unhandled Exception error

So I was using this within Azure Devops pipeline and when I started using it was version 1.5.1 that it was installing.
As part of the pipeline it just has the update command to get the latest stable version using the command line task.

After that I would use the bump-version preview $(Build.BuildNumber) to create a preview of the nuget package before it's pushed out.

However now when it attempts to do the bump it comes back with this error

Generating script.
Script contents:
dnt bump-versions preview "20201116.1"

##[error]Unhandled exception. System.IO.FileLoadException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
File name: 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
##[error]Cmd.exe exited with code '-532462766'.

Switching Packages/Projects with mutual references

Say I have two packages/projects that I'd like switch out, Lib1 and Lib2, where Lib2 also references Lib1 as a project reference, and I want to keep it that way. Switching from packages to projects works fine - all projects are now in my solution with everyone having project references, but then when I switch back to packages, the tool thinks that Lib2 is one of the projects that should be updated to have a NuGet package reference of Lib1, which I don't want. Only the other projects in my solution not listed in my .dnt file should get updated.

Support Central Package Versions

Currently we are managing our NuGet packages versions in one place with Central Package Versions. This means we don't specify versions of NuGet packages in our .csproj files.

<PackageReference Include="StdLib" />

DNT is currently not supporting this. When switching from packages to projects the version is set in the switcher.json file as shown below.

{
  "solution": "App.sln",
  "mappings": {
    "StdLib": "../StdLib/StdLib/StdLib.csproj"
  },
  "restore": [
    {
      "name": "App",
      "packages": [
        {
          "packageName": "StdLib",
          "version": "2.0.0"
        }
      ]
    }
  ]
}

When switching from project to package then the version is set in the .csproj as shown below

<PackageReference Include="Oce.StdLib" Version="2.0.0" />

switch-to-projects: the project 'path/myproject.csproj' could not be loaded. Not a project...

A couple of months ago it worked.
Now I'm receiving this error:

The project 'path/myproject.csproj' could not be loaded: Not a project: path\myproject.csproj

I'm using DNT v1.3.1.0, installed via dotnet tool install -g dnt
Current workaround is to reinstall DNT using npm: npm i -g dotnettools

"myproject.csproj" is an ASP.NET MVC Visual Studio Project that is using .NET Framework 4.6.1

Here it is a snippet of my .csproj file

    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>

In my solution I have also other types of .csproj (class and library) that are correctly switched.

Switch to projects not working for NSwag/NJsonSchema

I'm trying to run the standard switch to projects command for NSwag/NJsonSchema interop and hitting an issue running this command:

dnt switch-to-projects switcher.json

Which produces multiple entries like the following:

The project 'C:\Users\rossk\Documents\source\nswag\src....\NJsonSchema\src\NJsonSchema.CodeGeneration.TypeScript\NJsonSchema.CodeGeneration.TypeScript.csproj' could not be loaded: The imported project "C:\Program Files\dotnet\sdk\2.2.101\Current\Microsoft.Common.props" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk. C:\Program Files\dotnet\sdk\2.2.101\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props

The projects are successfully added to the solution but the packages are not swapped for the projects. Looking at the file "C:\Program Files\dotnet\sdk\2.2.101\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props" it has the following line:

<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />

So it appears to be substituting $(MSBuildToolsVersion) with "Current" which doesn't actually exist on my system. The correct substitution seems to be "15.0" as the filepath matches. Note that I'm running VS 2017 which is version 15.0.

Any ideas on how to fix this?

Suggestion: put projects in Folder

I have some larger Solutions with a lot of c# projects. When i switch from packages to projects, the inserted projects appear all over the solution, as the solution tree is sorted alphabetically.
My suggestion: put those inserted projects in a folder like "dnt.temporary".
After the last project in this folder is deleted when switching back to packages, this folder can be deleted from the solution tree.

Enhancement:
most of my packages are made of a solution with multiple c# projects.
So the above mentioned folder could have a subfolder for every package.

Support for PackageReference Format

I have a NET461 WPF project in VS2017 in the old style csproj format as the new style does not currently support XAML. I have recently updated packages.config to use the newer PackageReference format. I also have several nuget dependencies which have been migrated to .net standard using the new csproj SDK format.

Unfortunately, Nuget Reference Switcher does not support PackageReferences which results in the error message:

"this reference cannot be removed from the project because it is always referenced by the compiler"

DNT is regarded as the new replacement of NugetReferenceSwitcher, but unfortunately this doesn't appear to support PackageReference in the older csproj format either:

dnt switch-to-projects switcher.json
DNT (DotNetTools, https://github.com/RSuter/DNT, v1.2.5.0)
Binary: %userprofile%\.dotnet\tools\.store\dnt\1.2.5\dnt\1.2.5\tools\netcoreapp2.2\any\dnt.dll

Microsoft.Build.Exceptions.InvalidProjectFileException: The project file could not be loaded. Could not find file 'xxxxxxxxxxxxxxxxxxx\MyProject.sln'.  xxxxxxxxxxxxxxxxxxx\MyProject.sln
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, BuildEventFileInfo projectFile, String resourceName, Object[] args)
   at Microsoft.Build.Construction.SolutionFile.ParseSolutionFile()
   at Microsoft.Build.Construction.SolutionFile.Parse(String solutionFile)
   at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.AddProjectsToSolutionAsync(ReferenceSwitcherConfiguration configuration, IConsoleHost host)
   at Dnt.Commands.Packages.SwitchPackagesToProjectsCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\dnt\src\Dnt.Commands\Packages\SwitchPackagesToProjectsCommand.cs:line 25
   at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
   at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
   at NConsole.CommandLineProcessor.Process(String[] args, Object input)
   at Dnt.Program.Main(String[] args) in C:\projects\dnt\src\Dnt\Program.cs:line 27

Is there a workaround to this issue? Could DNT support PackageReference format perhaps?
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.