I'm trying to use dotnet watch however my project references nuget package which uses $(SolutionDir) to copy some files in prebuild event. It kinda make sense because dotnet watch is run on project level so $(SolutionDir) doesn't exist. Is there any way to run dotnet watch for entire solution?
I created a batch script watch.bat
call SET ASPNETCORE_ENVIRONMENT=Development
call SET SolutionDir=%~dp0\\..\\..\\
call dotnet watch run
Added a script in package.json:
"scripts": { "dotnetwatch": "watch.bat" }
Now I can run it like this from CLI:
npm run dotnetwatch
or from within visual studio with the following launchsettings.json profile:
"dotnet watch": {
"executablePath": "watch",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
It's not an ideal solution but at least it's good enough for me.
As of dotnet-watch 2.0.0-preview2, it is not possible to run dotnet watch on solution files. However, you can construct a custom 'project' for the watcher that will watch multiple projects. See https://github.com/aspnet/DotNetTools/tree/rel/2.0.0-preview2/samples/dotnet-watch/WatchMultipleProjects for a complete sample of how to do this.
Related
This is my dotnet build command for my .netcoreapp 2.1 MVC website which has two class library projects(VinXP.Core.csproj, VinXP.Infrastructure.csproj) referenced to the main web project(VinXP.web.csproj).
dotnet build VinXP.sln /nologo /p:PublishProfile=Release /p:PackageLocation="E:\Publish\DRS\package" /p:OutDir="E:\Publish\DRS\out" /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /maxcpucount:1 /p:platform="Any CPU" /p:configuration="Release" /p:DesktopBuildPackageLocation="E:\Publish\DRS\package\package.zip"
This above command doesn't create a zip in E:\Publish\DRS\package as mentioned in DesktopBuildPackageLocation. Instead, it creates E:\Publish\DRS\package\VinXP.VinXPWeb.zip.
Upon unzipping this zipped file, my build is available in a very deep sub folder as
E:\Publish\DRS\package\VinXP.Web.zip\Content\E_C\Working\Projects\Git\VinXPDevelopment\src\VinXP.Web\obj\Release\netcoreapp2.1\PubTmp\Out\[build]
Why cant it doesn't create a zip file with a build without creating a lengthy subfolder as I mentioned in DesktopBuildPackageLocation="E:\Publish\DRS\package\package.zip" on dotnet build command?
Attempts:
1 : Changed the path mentioned in the keys of my dotnet build command "PackageLocation","OutDir","DesktopBuildPackageLocation" but it only changes the root folder.
2 : Looked for .net documentation on Microsoft site couldn't find it useful with my challenge faced.
This basically depends on the CLI version you are using
If 2.X Instead of donet build since you are on a Windows PC you can replace this with donet publish
I.E
dotnet publish VinXP.sln /nologo /p:PublishProfile=Release /p:PackageLocation="E:\Publish\DRS\package" /p:OutDir="E:\Publish\DRS\out" /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /maxcpucount:1 /p:platform="Any CPU" /p:configuration="Release" /p:DesktopBuildPackageLocation="E:\Publish\DRS\package\package.zip"
Ideally to stop the creation of recursive directories you need include(Update) the following on the package.json file
"publishOptions": {
"exclude": [
"bin/**",
"obj/**",
"node_modules",
"**.user",
"**.vspscc"
],
OR
1.X Instead of donet build since you are on a Windows PC you can replace this with msbuild
I.E : msbuild VinXP.sln /nologo /p:PublishProfile=Release /p:PackageLocation="E:\Publish\DRS\package" /p:OutDir="E:\Publish\DRS\out" /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /maxcpucount:1 /p:platform="Any CPU" /p:configuration="Release" /p:DesktopBuildPackageLocation="E:\Publish\DRS\package\package.zip"
Refer this link for more.
Refer to this for path related issues:
1 , 2
I have a solution which contains multiple projects. I want to create a docker image of a project so I have added a Dockerfile via docker support. The project I have added the Dockerfile to has build dependencies on other projects at the same level. When I try to run the project via Docker I get the following error:
COPY failed: Forbidden path outside the build context: ../API.Common.AspNetCore/API.Common.AspNetCore.csproj ()
C:\Users\user.nuget\packages\microsoft.visualstudio.azure.containers.tools.targets\1.4.10\build\Container.targets(258,5): error CTP1001: An error occurred while attempting to build Docker image.
Dockerfile:
FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build
WORKDIR /src
COPY ["API.Customer/API.Customer.csproj", "API.Customer/"]
COPY ["../API.Common.AspNetCore/API.Common.AspNetCore.csproj", "../API.Common.AspNetCore/"]
COPY ["API.Customer.Eventing/API.Customer.Eventing.csproj", "API.Customer.Eventing/"]
COPY ["API.Customer.Errors.Database.AspNetCore/API.Customer.Errors.Database.AspNetCore.csproj", "API.Customer.Errors.Database.AspNetCore/"]
COPY ["API.Customer.Errors.AspNetCore/API.Customer.Errors.AspNetCore.csproj", "API.Customer.Errors.AspNetCore/"]
RUN dotnet restore "API.Customer/API.Customer.csproj"
COPY . .
WORKDIR "/src/API.Customer"
RUN dotnet build "API.Customer.csproj" -c Release -o /app
FROM build AS publish
RUN dotnet publish "API.Customer.csproj" -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "API.Customer.dll"]
LaunchSettings.json:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:5002",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Dev"
}
},
"STARS.API.Customer.Schools": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Dev"
},
"applicationUrl": "http://localhost:5002"
},
"Docker": {
"commandName": "Docker",
"launchUrl": "{Scheme}://localhost:{ServicePort}"
}
}
}
Please let me know if you require more information.
You're attempting to copy the API.Common.AspNetCore project into the directory above your work directory (../). That's not possible. I understand you're doing this because you need to maintain the relative project path references, but the only way to do that would be to embed the other projects one more directory deep. For example, instead of copying API.Customer.csproj to API.Customer/, copy to foo/API.Customer/. Then, for your API.Common.AspNetCore project, you can copy to just API.Common.AspNetCore/.
EDIT
Thinking about this more, the error is likely due to the opposite side of the equation, but the part above is also relevant. In short, Docker has a concept of a working or build directory, which is contextual to the directory that the Docker command is being run from. If you're running linux containers on Windows, then this becomes even more interesting, as that entire working directory is actually copied into the MobyLinux VM running in Hyper-V.
Anyways, because of this, you need to be careful about where you're running the Docker commands. If you need the context of a parent directory, then you need t to run out of that parent directory, so you have access to it and of course your project under it. Ironically, this is not something you have to really think about for a single Dockerfile, since traditionally, you don't have other participating applications when you're working with a Dockerfile directly. Conversely, when you are orchestrating multiple Docker apps, you'd traditionally be using a docker-compose.yml file, which would be at the parent level to all the participating apps. In either case, running those files directly in the folders they exist in would provide all the necessary context.
Your issue is that your effectively skating the two concepts, so you need to be much more careful about what your actual context is when you run your Docker commands. If you do have a docker-compose.yml, I'd recommend running that instead of the Dockerfile(s) directly. In Visual Studio, you simply need to add orchestration support, rather than adding Dockerfiles directly. This will add the Dockerfile, but also add a docker-compose project, and then it will up the docker-compose.yml, instead of building each image directly using the Dockerfile.
As #Chris Pratt says, if you have multiple projects in the solution it is best to use the file docker-compose.yml. But if for some reason you need to directly use Dokerfile and specify the context, you can add the following line to your *.csproj file.
<PropertyGroup>
...
<DockerfileContext>../..</DockerfileContext>
</PropertyGroup>
For example, ../.. to go back once. Check here.
To run dotnet core application with specified absolute path we need to run following command:
dotnet run -p C:\foo\bar\Project\Project.csproj
But it seems it doesn't work the same with dotnet watch run:
watch : Could not find a MSBuild project file in 'C:\directory\where\we\execute\command'. Specify which project to use with the --project option.
Running the same command with -project instead of -p doesn't help however...
Dotnet watch help specifies -p or -project parameter anyway:
Microsoft DotNet File Watcher 2.1.1-rtm-30846
Usage: dotnet watch [options] [[--] ...]
Options: -?|-h|--help Show help information
-p|--project The project to watch -q|--quiet Suppresses all output except warnings and errors -v|--verbose
Show verbose output --list Lists all discovered
files without starting the watcher --version Show
version information
Environment variables:
DOTNET_USE_POLLING_FILE_WATCHER When set to '1' or 'true',
dotnet-watch will poll the file system for changes. This is required
for some file systems, such as network shares, Docker mounted
volumes, and other virtual file systems.
DOTNET_WATCH dotnet-watch sets this variable to '1' on all child
processes launched.
Remarks: The special option '--' is used to delimit the end of the
options and the beginning of arguments that will be passed to the
child dotnet process. Its use is optional. When the special option
'--' is not used, dotnet-watch will use the first unrecognized
argument as the beginning of all arguments passed into the child
dotnet process.
For example: dotnet watch -- --verbose run
Even though '--verbose' is an option dotnet-watch supports, the use
of '--' indicates that '--verbose' should be treated instead as an
argument for dotnet-run.
Examples: dotnet watch run dotnet watch test
What's wrong then? Why absolute path to project doesn't work with dotnet watch run while works with dotnet run?
You can resolve this by specifying the -p (or the longer --project) option on the watch command rather than on the run command. In your case, that would be:
dotnet watch -p C:\foo\bar\Project\Project.csproj run
There's a note in the docs that covers this:
You can use dotnet watch --project <PROJECT> to specify a project to watch. For example, running dotnet watch --project WebApp run from the root of the sample app will also run and watch the WebApp project.
I'm not 100% sure, but dotnet watch is looking for file changes in the current directory. So if you use absolute path it must know where should it looks for changes. Of course, such implementation is possible but I just think that nobody thinked about it when implementing watch command
In my case, its just a minor error, you have to enter in the project directory before executing dotnet command, like:
cd yourAppName
dotnet watch run
It'll run
I have a simple .NET Core project (console app) that I'm trying to compile and run. dotnet build succeeds, but I get the following error when I do dotnet run:
dotnet run
Project RazorPrecompiler (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in [path].
My project.json looks like this:
{
"buildOptions": {
"warningsAsErrors": true
},
"dependencies": {
"Microsoft.AspNetCore.Razor": "1.0.0",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"description": "Precompiles Razor views.",
"frameworks": {
"netcoreapp1.0": {
"imports": [ ]
}
},
"version": "1.2.0"
}
What is hostpolicy.dll, and why is it missing?
Update for dotnet core 2.0 and beyond: the file appname.runtimeconfig.json (for both debug and release configuration) is needed in the same path as appname.dll.
It contains:
{
"runtimeOptions": {
"tfm": "netcoreapp2.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "2.0.0"
}
}
}
then dotnet.exe exec "path/to/appname.dll" [appargs] works.
This error message is unhelpful. The actual problem is a missing emitEntryPoint property:
"buildOptions": {
...
"emitEntryPoint": true
},
Once this is added, the compiler will let you know about any other problems (like a missing static void Main() method). Successfully compiling the project will result in an output that dotnet run can execute.
If I'm not mistaken, one scenario when you can hit the issue is this: You have an integration project that references another application project (not library). In this case, dependentProject.runtimeconfig.json won't be copied to your integration project's output folder and you won't be able to run dependentProject.exe binary because it will throw The library hostpolicy.dll was not found..
There is a Github issue for this and a workaround.
Edit: Should be fixed in .NET SDK 5.0.200.
I had similar problem running tests in VS19.
========== Starting test run ==========
Testhost process exited with error: A fatal error was encountered. The
library 'hostpolicy.dll' required to execute the application was not
found in 'C:\Program Files\dotnet'. Failed to run as a self-contained
app.
After digging into it I found the source of the problem:
The full path the the .runtimeconfig.json in the test binary folder was above 255 characters. Renaming the module, so the file path becomes shorter, resolved the problem.
This occurred when a Visual Studio 2019 preview upgrade .Net Core to the latest preview (specifically .Net Core 3.1.100-preview2-014569).
Reinstalling/repairing .Net Core 3.0.100 solved the problem for me.
I'm not sure why but I ran in to the problem when executing the .exe file in my \bin folder while the .exe in my \obj folder works fine.
I am having this problem in Dotnet Core 3.1 Console application.
If you are publishing your application, make sure that your target runtime set to the specific runtime that you had installed in your target machine.
If you set to portable it will pick whatever runtime that it feels comfortable (which you might not have it installed)
I had this happen with .NET 6.0 where somehow the appname.runtimeconfig.dev.json file was not being generated in the bin/Debug/net6.0/ directory.
The fix was modifying the .csproj file and include this fragment inside the <PropertyGroup> element:
<GenerateRuntimeConfigDevFile>true</GenerateRuntimeConfigDevFile>
I found this solution while searching with https://www.google.com/search?q=net60+runtimeconfig.dev.json at Breaking change: runtimeconfig.dev.json file not generated - .NET | Microsoft Learn with the solution at MSBuild properties for Microsoft.NET.Sdk - .NET | Microsoft Learn:
GenerateRuntimeConfigDevFile
Starting with the .NET 6 SDK, the [Appname].runtimesettings.dev.json file is no longer generated by default at compile time. If you still want this file to be generated, set the GenerateRuntimeConfigDevFile property to true.
<PropertyGroup>
<GenerateRuntimeConfigDevFile>true</GenerateRuntimeConfigDevFile>
</PropertyGroup>
After applying this to the .csproj file and re-building the project, debugging from Visual Studio Code worked fine including stopping at the breakpoints that I had set previously.
For me the issue was with the version mismatch. I had a different ".Net core SDK" version installed and a different version was specified in .json file.
Once I modified the version in my .json file the application started working fine.
In my case it was because I was publishing a self-contained application for the wrong target. My intent was to run on alpine linux, but I was building for libc when I should have been building for musl.
The failing package was built using:
dotnet publish --self-contained true --runtime linux-x64 --framework netcoreapp2.1 --output /app
Changing the RID:
dotnet publish --self-contained true --runtime linux-musl-x64 --framework netcoreapp2.1 --output /app
produced a functional package. Notice the RID changed from linux-x64 to linux-musl-x64. If I had read the .NET Core RID Catalog page this could have been avoided. 😅
Maybe you didn't want to do a "Console .Net Core" project but a "Console .Net Framework" project. It solves the problem, for me...
My problem was that I have 2 .NET Core App projects and one is dependent on the other.
(so I can then execute that application from that other application)
But .NET Core applications (with default config) need <assembly name>.runtimeconfig.json file (to get some launch config) which isn't copied by default.
The only solution that worked for me was adding to Project Properties > Build Events (of the dependent project) this command:
COPY "$(SolutionDir)<dependency name>\$(OutDir)<dependency assymbly name>.runtimeconfig.json" "$(SolutionDir)$(ProjectName)\$(OutDir)" /Y
But you can also copy the <dependency assembly name>.runtimeconfig.json file by hand to the dependent project.
Note that there should be a better more generic way to do this for every .NET Core App Project automatically.
This error is quite generic. So the real problem can be anything.
In my case (if helps anyone with same issue), I created a Class Library project instead of a Console Application project.
A Class Library DLL can't be runned with MSBuild, even if it has a Main method.
Only Console Application DDL can be runned as dotnet <appname>.dll
I was getting similar error while running Unit tests using VSTest#2 task in Azure Devops.
In my case, the problem was with my testAssemblyVer2 value. I was giving wrong pattern for test dlls.
Below one worked for me.(if you are getting this error with VSTest)
- task: VSTest#2
displayName: 'Running UnitTests'
inputs:
testSelector: 'testAssemblies'
testAssemblyVer2: |
$(System.DefaultWorkingDirectory)\SrcFolder\BBBB.UnitTests\**\bin\**\*.BBBB.UnitTests.dll
$(System.DefaultWorkingDirectory)\SrcFolder\AAAAa.UnitTests\**\bin\**\*.AAAA.UnitTests.dll
!**\*TestAdapter.dll
!**\obj\**
platform: x64
configuration: Debug
codeCoverageEnabled: true
So try to give correct pattern value for testAssemblyVer2 input. Make sure its filtering only the required dlls.
I had this same problem with a .NET Core 3.0 WPF app, but I found that my app wouldn't run in Visual Studio 2019 either.
I discovered on the project properties page (right-click on project > Properties) that the Target framework was set to .NET Core 3.0.
I'd recently updated VS 2019 which had also installed .NET Core 3.1, so I switched to that in the dropdown, and it worked again.
(I also had to update my shortcut to point to the netcoreapp3.1 folder instead of the previous netcoreapp3.0 folder.)
Promoting voltrevo's comment as an answer as I believe this should be the most common case of the problem. When you build your solution, sometimes you might get 2 directories with outputs bin and obj. 'Bin' directory has everything that is needed to run dotnet.exe command. Just run from the bin directory and things should be good. :)
For me with ASP.NET Core 2.0 on Azure, it was the appname.deps.json that did the trick. You need to copy it from your build directory to Azure.
For me, the error occurred during the SonarQube coverage scan due to one of the projects had a project reference to a MSTest project.
I faced this problem and it took me couple of days to figure out the solution.
Go to Visual Studio Installer.
Click on 'More' option of the Visual Studio.
Select 'Repair'.
It'll take some time for the download and installation.
Once it's completed restart the machine and try again.
This should solve the issue.
Add the OutputType on the PropertyGroup and issue is solved
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
more about this MSBuild can be found here
I have installed the preview version of Microsoft's new code editor "Visual Studio Code". It seems quite a nice tool!
The introduction mentions you can program c# with it, but the setup document does not mention how to actually compile c# files.
You can define "mono" as a type in the "launch.json" file, but that does not do anything yet. Pressing F5 results in: "make sure to select a configuration from the launch dropdown"...
Also, intellisense is not working for c#? How do you set the path to any included frameworks?
Launch.json:
"configurations": [
{
// Name of configuration; appears in the launch configuration drop down menu.
"name": "Cars.exe",
// Type of configuration. Possible values: "node", "mono".
"type": "mono",
// Workspace relative or absolute path to the program.
"program": "cars.exe",
},
{
"type": "mono",
}
Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B.
If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M.
(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)
Intellisense does work for C# 6, and it's great.
For running console apps you should set up some additional tools:
ASP.NET 5; in Powershell: &{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}
Node.js including package manager npm.
The rest of required tools including Yeoman yo: npm install -g yo grunt-cli generator-aspnet bower
You should also invoke .NET Version Manager: c:\Users\Username\.dnx\bin\dnvm.cmd upgrade -u
Then you can use yo as wizard for Console Application: yo aspnet Choose name and project type. After that go to created folder cd ./MyNewConsoleApp/ and run dnu restore
To execute your program just type >run in Command Palette (Ctrl+Shift+P), or execute dnx . run in shell from the directory of your project.
SHIFT+CTRL+B should work
However sometimes an issue can happen in a locked down non-adminstrator evironment:
If you open an existing C# application from the folder you should have a .sln (solution file) etc..
Commonly you can get these message in VS Code
Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!
Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'
Finished
Failed to spawn 'dotnet --info' //this is a possible issue
To which then you will be asked to install .NET CLI tools
If impossible to get SDK installed with no admin privilege - then use other solution.
Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:
"code-runner.executorMap": {
"csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
// "csharp": "echo '# calling dotnet run\n' && dotnet run"
}
Open your C# file and use the execution key of Code Runner.
Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).
To Run a C# Project in VS Code Terminal
Install CodeRunner Extension in your VS Code (Extension ID: formulahendry.code-runner)
Go to Settings and open settings.json
Type in code-runner.executorMap
Find "csharp": "scriptcs"
Replace it with this "csharp": "cd $dir && dotnet run $fileName"
Your project should Run in VS Code Terminal once you press the run button or ALT + Shift + N