I have a console application project where i'm using the powershell SDK, it works perfectly fine in debug but on release, everything except powershell works.
The only settings i've found where it works is when releasing the project as framework dependent and portable. Or at least it works on my pc, on other computers it says the dotnet runtime is missing, even when installed via the link provided.
Using self contained, .net6-windows and win-x86 doesn't work. Not quite sure what could be wrong? I've tried cleaning the project, the solution, restarting visual studio and my PC. Everything works as expected in debug but when I publish, powershell just doesn't work.
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-SocketService-04A4D71F-C305-4A5B-BD0B-529C28B25DAD</UserSecretsId>
<PlatformTarget>AnyCPU</PlatformTarget>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.1" />
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.2" />
<PackageReference Include="System.Management" Version="6.0.0" />
<PackageReference Include="System.Management.Automation" Version="7.2.1" />
</ItemGroup>
<ItemGroup>
<Folder Include="Speedtest\" />
</ItemGroup>
<ItemGroup>
<None Update="Speedtest\speedtest.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
EDIT:
I changed my powershell handler to use .EndInvoke(), now I finally get a proper error! I found an issue mentioning the error https://github.com/PowerShell/PowerShell/issues/7909 but installing Microsoft.Management.Infrastructure didn't resolve the issue, I installed version 2.0.0. If i try installing version 1 I get an error stating that the System.Management.Automation package requires a higher version (2.0.0)
public static string CMD(string script)
{
string errorMsg = "";
string output;
ps.AddScript(script);
//Make sure return values are outputted to the stream captured by C#
ps.AddCommand("Out-String");
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
ps.Streams.Error.DataAdded += (object sender, DataAddedEventArgs e) =>
{ errorMsg = ((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString(); };
IAsyncResult result = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);
ps.EndInvoke(result);
//while (!result.IsCompleted)
// Thread.Sleep(300);
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject outputItem in outputCollection)
{
stringBuilder.AppendLine(outputItem.BaseObject.ToString());
}
output = stringBuilder.ToString();
//Clears commands added to runspace
ps.Commands.Clear();
if (!string.IsNullOrEmpty(errorMsg))
return string.Empty;
return output.Trim();
}
Here is the error message
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Den angivne fil blev ikke fundet.
File name: 'Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
at SocketService.PowerShellHandler.CMD(String script) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Handlers\PowershellHandler.cs:line 35
at SocketService.Classes.SystemInfo..ctor() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Classes\SystemInfo.cs:line 21
at SocketService.CommandHandler.Initialize() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Handlers\CommandHandler.cs:line 31
at SocketService.SocketService..ctor() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\SocketService.cs:line 27
at SocketService.WindowsBackgroundService.StartAsync(CancellationToken cancellationToken) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\WindowsBackgroundService.cs:line 17
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Program.<Main>$(String[] args) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Program.cs:line 14
at Program.<Main>(String[] args)
[process exited with code 3762504530]
Line 14 is me calling PowerShell.Create();
What ended up solving my issue was this answer: Dotnet publish not publishing DLL to publish directory
I changed the target runtime to win10-x86 and that worked!
<TargetFramework>net6.0-windows</TargetFramework>
<RuntimeIdentifier>win10-x86</RuntimeIdentifier>
Without showing actual code and giving a more descriptive detailing about what's going on aside from "it doesn't work" it's difficult to say exactly what is occurring here but I'll do my best.
Thankfully, according to Microsoft's documentation you most certainly can run the Powershell SDK in a self-contained .Net application.
A self-contained .NET application can use Microsoft.PowerShell.SDK to run arbitrary PowerShell functionality without depending on any external PowerShell installations or libraries.
This leads me to believe that you may not be having an issue with the SDK itself but rather with the compiler.
Single-File deployments
I noticed in your screenshot that you are attempting to perform a single-file deployment. You could potentially be having a few issues here. One is to ensure that you're not using an incompatible API. If you are calling any of these within your application, that could be a factor:
Assembly.CodeBase
Assembly.EscapedCodeBase
Assembly.GetFile
Assembly.GetFiles
Assembly.Location
AssemblyName.CodeBase
AssemblyName.EscapedCodeBase
Module.FullyQualifiedName
Module.Name
As none of these are compatible with single-file deployments.
Trimming
Another issue you may be experiencing is referred to as trimming. This is where the compiler will 'trim' unused assemblies from the project at compile time and tends to happen on release runs. While I believe this is off by default you can add the following to your .csproj file to ensure that trimming is disabled:
<PropertyGroup>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
Optimizing
The JIT compiler tends to try to optimize code on release builds. When we run an application in debug mode the application is optimized for debugging the code. It tries to leave everything almost exactly as you wrote it with maybe some minor differences. When an application is run in release mode the actual code that is being run can be drastically different while maintianing the same logic. This is usually to try and make the final assembly as small and fast as possible. You can disable this optimization by the following steps:
Right click on project
Click "properties"
Go to "Build"
Under the section "general" deactivate "Optimize Code"
Other than the above mentioned possible causes I can't think of much more I can offer without seeing code, or error messages, or further details.
I am following Get started with Blazor. I have created the application and attempt to run it as is i have made no changes.
There are three things in my event log.
The directory specified for caching compressed content C:\inetpub\temp\IIS Temporary Compressed Files\Clr4IntegratedAppPool is invalid. Static compression is being disabled.
Application 'MACHINE/WEBROOT/APPHOST/WEBAPPLICATION1' with physical root 'C:\Users\LindaL\source\repos\Daimto.RazorTest.Tools\WebApplication1\' failed to start process with commandline 'c:\program files (x86)\microsoft visual studio\2017\professional\common7\ide\extensions\microsoft\web tools\projectsystem\VSIISExeLauncher.exe -argFile "C:\Users\LindaL\AppData\Local\Temp\tmpF272.tmp"', ErrorCode = '0x80004005' : 0.
Application 'MACHINE/WEBROOT/APPHOST/WEBAPPLICATION1' with physical root 'C:\Users\LindaL\source\repos\Daimto.RazorTest.Tools\WebApplication1\' failed to start process with commandline 'c:\program files (x86)\microsoft visual studio\2017\professional\common7\ide\extensions\microsoft\web tools\projectsystem\VSIISExeLauncher.exe -argFile "C:\Users\LindaL\AppData\Local\Temp\tmpF272.tmp"', ErrorCode = '0x80004005' : 0.
Note i just update to visual studio professional 2017 15.9.3. I have used blazor before this was working fine.
Update: This appears only in the "Blazor" project type.
Update2: hitting Cntrl-F5 as opposed to just F5 – No change.
Update3 Project file per request in comment in answer below
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RunCommand>dotnet</RunCommand>
<RunArguments>blazor serve</RunArguments>
<LangVersion>7.3</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Blazor.Browser" Version="0.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="0.6.0" PrivateAssets="all" />
<DotNetCliToolReference Include="Microsoft.AspNetCore.Blazor.Cli" Version="0.6.0" />
</ItemGroup>
</Project>
Delete global.json and see if that helps.
https://github.com/aspnet/Blazor/issues/1342
If that doesn't help try adding global.json with content
{
"sdk": {
"version": "2.1.500"
}
}
If all fails, close all Visual Studio instances and reinstall Blazor templates with dotnet new -i Microsoft.AspNetCore.Blazor.Templates and create new Blazor solution with dotnet new and use Blazor template you want.
Test class
[TestFixture]
public class Class1
{
[Test]
public void testtesttest()
{
Assert.IsTrue(true);
}
}
Dependencies
I followed instructions from here.
Why can't I discover my unit tests?
.NET Core Solution
It turns out I had to have a unit test project instead of a class library:
I also followed instructions from the MSDN website here.
I was running the following in a command prompt to make sure I had the unit test template:
dotnet new -i NUnit3.DotNetNew.Template
My NuGet Packages Dependencies
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="1.2.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.2.0" />
<PackageReference Include="NUnit" Version="3.8.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.9.0" />
</ItemGroup>
Update
As #Lexli pointed out, you don't need the MSTest packages if you are only going to use NUnit tests.
However, make sure you use .NET Core and not .Netcore Standard. The .NET Core comes with the Microsoft.netCore.App SDK which is needed for running unit tests. Unit tests can't be run with .NET standard class libraries.
Projects Referencing .NET Framework 4.0
In projects where the .NET framework was v4.0 I had to use NUnit version 3.0 - anything higher and the project wasn't discovered.
Still not working?
Try clearing temporary files located in the %TEMP% directory.
Note: This path is generally at C:\Users\(yourusername)\AppData\Local\Temp
When trying to add a Controller in an ASP.NET Core project using Visual Studio 15 Enterprise with Update 3, I get the error below:
"The was an error running the selected code generator: No executables found matching command 'dotnet-aspnet-codegenerator'"
If you're using csproj (Visual Studio 2017) instead of project.json, then you need to add the following to your csproj file:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.1" />
</ItemGroup>
If you are using Mac (OS X) or any supported distribution of Linux, you have to run:
dotnet tool install --global dotnet-aspnet-codegenerator --version 2.2.3
Additionally, on Mac I added to my .zshrc (or bash equivalent)
export PATH=$HOME/.dotnet/tools:$PATH
And I had to make sure to restart Terminal.
For the latest version, in project.json add the following under dependencies:
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
"version": "1.1.0-preview4-final",
"type": "build"
},
"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
"type": "build",
"version": "1.1.0-preview4-final"
}
and the following under tools:
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
"version": "1.1.0-preview4-final",
"imports": [
"portable-net45+win8"
]
}
A more robust answer than copying version numbers into your configuration file is to use NuGet to ensure that the packages are added to your project.
Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.
First, get everything up to date. Choose the Updates tab. Check the box for Update All and run this a few times. Don't be surprised if some stuff downgrades the first couple of times you run the upgrade. Some dependencies seem to have to be handled sequentially. It took me about 5 upgrades to get everything up to date.
Then, in the browse tab, search for CodeGeneration.Tools. Install it. Do the same for CodeGenerators.Mvc. As you find additional error messages, you should be able to find any missing packages in NuGet.
In dotnet core 2.1.1 you'd expect that the situation has changed and you may not need to add much. I'm sorry to annoy you but the situation is same and all you need to do now is update your version of the tool or package you wish to use.
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
This worked for me. I hope it works for eveyone else that gets stuck here. Note that the key reference is DotNetCliToolReference not PackageReference
Add the following to your project.json:
Under dependencies:
"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
"version": "1.0.0-preview2-final",
"type": "build"
}
Under tools:
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
"version": "1.0.0-preview2-final",
"imports": [
"portable-net45+win8"
]
}
Version number may change depending on which version of .NET Core you're using in your project
You may get another error about Microsoft.DotNet.InternalAbstractions missing, in which case you'll need to get from NuGet
Make sure "Microsoft.VisualStudio.Web.CodeGeneration.Tools" version in dependencies matches "Microsoft.VisualStudio.Web.CodeGeneration.Tools" version in tools
I had to add the following to my CSProj file:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0-msbuild3-final" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0-msbuild3-final" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
</ItemGroup>
After adding that I installed CodeGenerators.Mvc with nuget package manager.
I was still getting an error saying it can't find some file in the MCD folder so I had to copy and paste the entire bin\Debug\netcoreapp1.1 folder into bin\MCD\Debug\netcoreapp1.1
I ran the scaffolding and it worked!
I encountered the same issue in Visual Studio Mac Community Edition 2017. Prior to running the scaffold command from the project directory, make sure the directory has the Program.cs, Startup.cs and .csproj files. if not, then run the command ls-al and then cd into the project directory which would be inside your current project directory and then execute the scaffold command. An obvious mistake many overlook.
Just add tag 'DotNetCliToolReference ' and package code design on .csproj and execute code-generate command on root solution. Thats worked to me.
.csproj
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" />
</ItemGroup>
<ItemGroup>
...
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.3" />
</ItemGroup>
Command
PS C:\Users\miche\projetos\asp_net_core\crud> dotnet aspnet-codegenerator controller -name ProdutosController -m Produto -dc AppDataContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries
Don't forget to build and restore solution after add package ;)
For VS 2015, in project.json file -
under dependencies add -
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
"version": "1.0.0-preview2-final",
"imports": [
"portable-net45+win8"
]
},
"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": "1.0.0-preview2-final"
then under tools add-
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
"version": "1.0.0-preview2-final",
"imports": [
"portable-net45+win8"
]
}
In Visual Studio Code change your yourproject.csproj
<pre>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.6" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" version= "2.1.0-preview1-final" />
<PackageReference Include="Microsoft.Extensions.SecretManager.Tools" version= "2.0.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.2" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" version="2.1.0-preview1-final" />
</ItemGroup>`enter code here`
</pre>
I just typed in Linux:
~/.dotnet/tools/dotnet-aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages/Movies --referenceScriptLibraries
So, I did not start with 'dotnet' (my current version: 2.2.300)
I do not like this solution, but it worked.
On Windows 10
In my case the installer added the wrong path to the Path environment variable.
The path added was pointing to a non existing folder under Programs. It needs to point to dotnet-aspnet-codegenerator.exe.
For me the correct path was in my user folder: ~\.dotnet\tools
You can check if the correct path was added by running: echo $env:Path
If the path is missing or incorrect you just need to add the correct path to the Path system environment variable.
You might be able to test this by using PowerShell to set your local variable: $env:Path += ";C:\Users\<YOUR_NAME_HERE>\.dotnet\tools"
But I haven't tried this.
To fix it globally
Start typing Environment in the windows search and you should see the Control panel option to Edit system environment variables.
Click the Environment Variables... button in the lower right corner.
Under System variables find and select the Path variable, then click Edit.
Check if the path to dotnet-aspnet-codegenerator.exe is there and if not click New and add it.
Restart your computer.
I am currently working on a project in C#, and trying to get NUnit to run on my project in a Jenkins Build through restoring the package in NuGet. We do not want to install NUnit on all of our Jenkins machines so installing it directly on the box is not an option.
We've investigated the use of NUniter Runners as suggested in this link: https://peteris.rocks/blog/running-nunit-with-msbuild-on-windows-and-mono/
But, we receive an error that the tools do not exist
"C:\Users\Name\NewBranch\project\project.Tests\project.Tests.csproj(121,3): error MSB6003
: The specified task executable "cmd.exe" could not be run. The working directory "C:\Users\Name\NewBranch\project\
packages\NUnit.Runners.3.4.1\tools" does not exist."
How do I execute NUnit tests from the command line without having NUnit installed directly on the machine?
the easiest way is to dump there 2 lines in the packages.config which should be in the same folder as your project.Tests.csproj
<package id="NUnit" version="2.6.4" targetFramework="net45" />
<package id="NUnit.Runners" version="2.6.4" />
Assuming you have a target in your .csproj which is like this:
<Target Name="NugetRestore">
<Exec Command="nuget.exe restore" />
</Target>
if you use a solution level build.config, then add this instead
<Target Name="NugetRestore">
<Exec Command="nuget.exe restore $(YourSolution).sln" />
</Target>