Why does "dotnet ef migrations add" throw a Win32Exception? - .net-core

I have a dotnet core v3.1 project with an entity framework DbContext.
when I try to run:
dotnet ef migrations add someMigrationName
this Exception will be thrown:
System.ComponentModel.Win32Exception (2): No such file or directory
at System.Diagnostics.Process.ForkAndExecProcess(String filename, String[] argv, String[] envp, String cwd, Boolean redirectStdin, Boolean redirectStdout, Boolean redirectStderr, Boolean setCredentials, UInt32 userId, UInt32 groupId, UInt32[] groups, Int32& stdinFd, Int32& stdoutFd, Int32& stderrFd, Boolean usesTerminal, Boolean throwOnNoExec)
at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Microsoft.EntityFrameworkCore.Tools.Exe.Run(String executable, IReadOnlyList`1 args, String workingDirectory, Boolean interceptOutput)
at Microsoft.EntityFrameworkCore.Tools.Project.FromFile(String file, String buildExtensionsDir, String framework, String configuration, String runtime)
at Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute(String[] _)
at Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.<Configure>b__0(String[] args)
at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
No such file or directory
My development environment is a Linux elementary os (Ubuntu 18.04.4 LTS) and rider IDE.
It may be irrelevant but when I try to debug my xunit tests it returns this warning and cannot start execution.
All of these commands work properly and show all options:
dotnet
dotnet ef
dotnet ef migrations
but when I use these options Exception raised:
dotnet ef migrations add
dotnet ef migrations list
Also, I run my command with verbose option and this is the output:
Using project '/media/navid/9bf0167c-d789-4e06-9e23-4023ec551745/Stuff/Work/SabaCell/venus/Venus.CustomerProfileManagement/Venus.CustomerProfileManagement.csproj'.
Using startup project '/media/navid/9bf0167c-d789-4e06-9e23-4023ec551745/Stuff/Work/SabaCell/venus/Venus.CustomerProfileManagement/Venus.CustomerProfileManagement.csproj'.
Writing '/media/navid/9bf0167c-d789-4e06-9e23-4023ec551745/Stuff/Work/SabaCell/venus/Venus.CustomerProfileManagement/obj/Venus.CustomerProfileManagement.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpUud0Xf.tmp /verbosity:quiet /nologo /media/navid/9bf0167c-d789-4e06-9e23-4023ec551745/Stuff/Work/SabaCell/venus/Venus.CustomerProfileManagement/Venus.CustomerProfileManagement.csproj
System.ComponentModel.Win32Exception (2): No such file or directory
at System.Diagnostics.Process.ForkAndExecProcess(String filename, String[] argv, String[] envp, String cwd, Boolean redirectStdin, Boolean redirectStdout, Boolean redirectStderr, Boolean setCredentials, UInt32 userId, UInt32 groupId, UInt32[] groups, Int32& stdinFd, Int32& stdoutFd, Int32& stderrFd, Boolean usesTerminal, Boolean throwOnNoExec)
at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Microsoft.EntityFrameworkCore.Tools.Exe.Run(String executable, IReadOnlyList`1 args, String workingDirectory, Boolean interceptOutput)
at Microsoft.EntityFrameworkCore.Tools.Project.FromFile(String file, String buildExtensionsDir, String framework, String configuration, String runtime)
at Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute(String[] _)
at Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.<Configure>b__0(String[] args)
at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
No such file or directory
this is the result of running dotnet --info in my environment:
.NET Core SDK (reflecting any global.json):
Version: 3.1.405
Commit: 3fae16e62e
Runtime Environment:
OS Name: elementary
OS Version: 5.1.7
OS Platform: Linux
RID: linux-x64
Base Path: /usr/share/dotnet/sdk/3.1.405/
Host (useful for support):
Version: 3.1.11
Commit: f5eceb8105
.NET Core SDKs installed:
3.1.405 [/usr/share/dotnet/sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.11 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.11 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download

This helped me,
I deleted dotnet symlink in /usr/local/bin/ (macOS)

It didn't work for me removing the symlink.
I had to reinstall the dotnet-ef tool:
dotnet new tool-manifest
dotnet tool install dotnet-ef
That fixed the issue :)

I was able to solve this issue with #bjorn answer. there was a symlink in my /usr/local/bin pointing to /snap/..., back when I tried to install .net sdk with snap, which was not successful, so I tried a different approach. Just complementing #bjorn answer, this is what I did :
Check if you have a symlink :
ls -l /usr/local/bin/
It will look something like this :
lrwxrwxrwx 1 root root 54 jul 22 09:46 dotnet -> /snap/...
Then remove it :
sudo rm /usr/local/bin/dotnet

Related

Could not load file or assembly Newtonsoft.Json when running app from the dotnet publish output folder

I am finding a problem with Newtonsoft.Json library throwing a
System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified
when running an app as a Docker container and I'd like to know why this happens and why dependency management does not work smoothly.
I use .NET 5.
I have a library MyLibrary.A that explicitly uses Newtonsoft.Json 13.0.1 for serializing and deserializing json.
I have a different library MyLibrary.B that wraps a MassTransit.AmazonSQS library. This MassTransit library also uses Newtonsoft.Json, but probably a different version.
If I don't do anything explicit, it seems the MassTransit dependency shows the Newtonsoft.Json 11.0.2. If at MyLibrary.B I explicitly add Newtonsoft.Json 13.0.1, even though I don't explicitly use it, then MassTransit seems to be happy with using this newest Newtonsoft.Json 13.0.1
Now, I have a web app MyApp that uses MyLibrary.A and MyLibrary.B. It works fine locally, but I use a CI/CD server to generate a Docker image.
Now I spin up this Docker image as a container locally (as a Docker Compose) and I get the error
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified.
It complains about a version that does not even exist. There is no 13.0.0.0, This library seems to go from 12.0.3 to 13.0.1.
I am now going through all my libraries and making sure they all use Newtonsoft.Json 13.0.1 explicitly. And when I detect that some of them use some third party that relies on Newtonsoft.Json I add explicitly the very same version, so that I can get everywhere the 13.0.1 version.
UPDATE 1: My workaround didn't work. I don't know what else to try.
I have even added the Newtonsoft.Json 13.0.1 explicitly to my webapp so I was hoping that at least at runtime it has it available.
Also, if I run my web up locally as a standard kestrel AspNetCore app (.NET 5) it launches properly. What is going on? Why is my docker container complaining about Newtonsoft.Json 13.0.0.0 not being found?
These are the traces when attempting to run as a Docker container
docker run -p 8080:80 \
> -e ASPNETCORE_ENVIRONMENT=Production \
> registry.gitlab.com/sample/foo-integration-service:latest
Unable to find image 'registry.gitlab.com/sample/foo-integration-service:latest' locally
latest: Pulling from sample/foo-integration-service
07aded7c29c6: Pull complete
97aff7269a5a: Pull complete
633b89d569a5: Pull complete
bd0e639a2ac9: Pull complete
a9a5571a369e: Pull complete
9569d825ee3a: Pull complete
Digest: sha256:5499b40392512f1731890ccf1ee13507769b733ee2f30c95d281f0550f7a892e
Status: Downloaded newer image for registry.gitlab.com/sample/foo-integration-service:latest
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified.
File name: 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
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 Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
at foo.ItgService.Program.Main(String[] args) in /builds/sample/foo-integration-service/src/foo.ItgService/Program.cs:line 10
UPDATE 2: I decided to match MassTransit dependency Newtonsoft.Json 11.0.2 everywhere in my libraries.
The problem remains.
The error is now
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified.
I don't get it. All my dependencies of Newtonsoft.Json are now 11.0.2 and still it complains. I'll add this version explicitly (even though I don't directly need it) at the web app main assembly and see if it still complains about it.
UPDATE 3: Still same problem after adding Newtonsoft.Json 11.0.2 to all my libraries and after adding that very same dependency to my web app assembly as a dependency.
As per Chris' comment I have now a .dockerignore.
bin/
obj/
The way I build the image is, with GitLab, with a standard dotnet build, dotnet publish and then copying all the contents of publish folder into the Docker image like this
FROM mcr.microsoft.com/dotnet/aspnet:5.0
COPY publish/ .
EXPOSE 80
ENTRYPOINT ["dotnet", "MyCompany.ItgService.dll"]
More specific, I use Kaniko and this is my .gitlab-ci.yml
image: mcr.microsoft.com/dotnet/sdk:5.0
variables:
GIT_DEPTH: 1000
PUBLISH_OUTPUT_DIR: publish
ENTRYPOINT_DLL: ReplaceMe.dll
CLUSTER_NAME: ReplaceMe
SERVICE_NAME: ReplaceMe
stages:
- build
- test
- publish
- delivery
build:
stage: build
script:
- dotnet restore --no-cache --force
- dotnet build --configuration Release --no-restore
artifacts:
paths:
- test
expire_in: 8 hour
rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
test:
stage: test
services:
- name: localstack/localstack:0.12.17.5
alias: localstack
variables:
# Localstack with SNS and SQS
AWS_DEFAULT_REGION: "us-east-1"
EDGE_PORT: "4566"
SERVICES: "sns,sqs"
before_script:
- rounds=10;
while [ $rounds -gt 0 ]; do
curl http://localstack:4566 && echo OK && break || echo FAIL
rounds=$rounds - 1;
sleep 5;
done;
script: dotnet test --blame --configuration Release
rules:
- if: $CI_COMMIT_TAG
when: never
- exists:
- test/**/*Tests.csproj
publish:
stage: publish
before_script:
- export PATH=$PATH:/root/.dotnet/tools
- dotnet tool install --global GitVersion.Tool --version 5.7.0
- dotnet gitversion
- SEMVER=$(dotnet gitversion -showvariable semver)
- mkdir version
- echo "${SEMVER}" > ./version/semver
- APP_VERSION=$(cat ./version/semver)
script:
- dotnet publish -c Release -o $PUBLISH_OUTPUT_DIR -p:Version=$APP_VERSION
artifacts:
paths:
- $PUBLISH_OUTPUT_DIR/
- version/
expire_in: 8 hour
rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
container_registry:
stage: delivery
image:
name: gcr.io/kaniko-project/executor:debug
entrypoint: [""]
before_script:
- IMAGE_TAG=$(cat ./version/semver)
- echo "bin/" > $CI_PROJECT_DIR/.dockerignore
- echo "obj/" > $CI_PROJECT_DIR/.dockerignore
- echo "FROM mcr.microsoft.com/dotnet/aspnet:5.0" > $CI_PROJECT_DIR/Dockerfile
- echo "COPY $PUBLISH_OUTPUT_DIR/ ." >> $CI_PROJECT_DIR/Dockerfile
- echo "EXPOSE 80" >> $CI_PROJECT_DIR/Dockerfile
- echo "ENTRYPOINT [\"dotnet\", \"$ENTRYPOINT_DLL\"]" >> $CI_PROJECT_DIR/Dockerfile
- cat $CI_PROJECT_DIR/Dockerfile
- echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
- cat /kaniko/.docker/config.json
script:
- /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile --destination $CI_REGISTRY_IMAGE:latest --destination $CI_REGISTRY_IMAGE:$IMAGE_TAG
rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
I don't know if the dotnet publish is messing something up for docker or whether there is some flaw in my process (it works fine for all other services). What might be the problem?
I can see Newtonsoft.Json.dll among the files produced by dotnet publish along with MassTransit.AmazonSqsTransport and all others that are supposedly being copied properly to the Docker image.
Also, If I open the .deps.json I can see all references to Newtonsoft.Json are 11.0.2, so no version conflict anymore (I think!).
I'm out of ideas.
UPDATE 4
I've just cleared all my local nuget packages (using Ubuntu)
dotnet nuget locals all --clear
Clearing NuGet HTTP cache: /home/diegosasw/.local/share/NuGet/v3-cache
Clearing NuGet global packages folder: /home/diegosasw/.nuget/packages/
Clearing NuGet Temp cache: /tmp/NuGetScratch
Clearing NuGet plugins cache: /home/diegosasw/.local/share/NuGet/plugins-cache
Local resources cleared.
An interesting thing is that when I restore dependencies after that on my project
dotnet restore
I can see at /home/diegosasw/.nuget/packages/newtonsoft.json
that there are versions 11.0.2 and 9.0.1
So I guess somewhere somehow a sub-dependency is using Newtonsoft 9.0.1, even though there is no trace of a Newtonsoft.Json 9.0.1 in my the *.deps.json that my dotnet publish produces, and I'm wondering whether this is related to my problem, maybe because that's the assembly being loaded and the 11 is being ignored?
UPDATE 5
I've just seen that the Newtonsoft.Json 9.0.1 is being used by some test project, because I can trace it at coverlet.collector.deps.json under coverlet.core 1.0.0 and the Microsoft.Extensions.DependencyModel 2.1.0
I guess it's not the cause of my problem then.
Also I've verified with docker export $(docker ps -lq) -o foo.tar that the container has the Newtonsoft.Json.dll.
I would like to understand why is this happening and learn how to better troubleshoot these kind of things.
UPDATE 6 (4 Oct)
I don't think the problem is with Docker. I think the problem is likely with dotnet publish or something I'm missing or doing wrong.
I have left Docker outside since I didn't see anything wrong there.
I tried to simply do a
dotnet publish -c Release -o publish
and execute the app in that
publish folder with dotnet MyCompany.ItgService.dll to reproduce the exception.
But before publishing, when I run the application with a
dotnet run -c Release --project src/Rubiko.ItgService
I don't get that exception.
See https://github.com/dotnet/sdk/issues/21716 for full details, traces, tree structure, etc.
Summary
The questions are:
Why dotnet publish does not seem to produce everything my app needs to run?
Why does it complain at runtime about an assembly that is there?
$ ls publish/ | grep Newtonsoft
Newtonsoft.Json.Bson.dll*
Newtonsoft.Json.dll*
FINAL UPDATE: Problem solved. See my own response where info on how to properly troubleshoot these kind of issues and how I solved it by ensuring my test projects (that use different version of the library) don't publish artifacts and overwrite the desired dependency assembly.
I solved the mystery. It had nothing to do with Docker. It kind of had something to do with dotnet publish but the SDK works well.
The problem was, as initially suspected, with a version conflict. When publishing with dotnet publish -c Release -o publish I could see the Newtonsoft.Json.dll there. But the following made me suspicious
ls publish/ -al | grep Newtonsoft
-rwxrw-r-- 1 diegosasw 89K mar 22 2017 Newtonsoft.Json.Bson.dll*
-rwxrw-r-- 1 diegosasw 641K mar 24 2018 Newtonsoft.Json.dll*
2018 seems a bit old for that version. What if.. that Newtonsoft.Json assembly being published wasn't the version 11.0.2 after all?
I updated all my libraries to match MassTransit dependency on Newtonsoft 11.0.2 but my findings on Update 4 made me think there was some other project depending indirectly on Newtonsoft.Json 9.0.1, and that's why I could see that nuget package being cached locally.
If, somehow, the assembly being published is not the expected Newtonsoft.Json 11.0.2 but the Newtonsoft.Json 9.0.1, the error would make sense when complaining about not finding the assembly Newtonsoft.Json 11.0.2
Bingo!
I installed exiftool in my Ubuntu to check dll and exe versions.
sudo apt install libimage-exiftool-perl
I run the following
$ exiftool publish/Newtonsoft.Json.dll
ExifTool Version Number : 11.88
File Name : Newtonsoft.Json.dll
Directory : publish
File Size : 465 kB
File Modification Date/Time : 2021:07:19 19:52:18+02:00
File Access Date/Time : 2021:10:04 12:53:14+02:00
File Inode Change Date/Time : 2021:10:04 12:44:39+02:00
File Permissions : rwxrw-r--
File Type : Win32 DLL
File Type Extension : dll
MIME Type : application/octet-stream
Machine Type : Intel 386 or later, and compatibles
Time Stamp : 2016:06:13 13:05:00+02:00
Image File Characteristics : Executable, Large address aware, DLL
PE Type : PE32
Linker Version : 48.0
Code Size : 465920
Initialized Data Size : 2048
Uninitialized Data Size : 0
Entry Point : 0x738b6
OS Version : 4.0
Image Version : 0.0
Subsystem Version : 4.0
Subsystem : Windows command line
File Version Number : 9.0.1.19813
Product Version Number : 9.0.1.0
File Flags Mask : 0x003f
File Flags : (none)
File OS : Win32
Object File Type : Dynamic link library
File Subtype : 0
Language Code : Neutral
Character Set : Unicode
Comments : Json.NET is a popular high-performance JSON framework for .NET
Company Name : Newtonsoft
File Description : Json.NET .NET Standard 1.0
File Version : 9.0.1.19813
Internal Name : Newtonsoft.Json.dll
Legal Copyright : Copyright © James Newton-King 2008
Legal Trademarks :
Original File Name : Newtonsoft.Json.dll
Product Name : Json.NET
Product Version : 9.0.1
Assembly Version : 9.0.0.0
and as you can see, the published assembly is Newtonsoft.Json 9.0.1. A mix of relief invades me.
I went to my test projects and added the following to the *.csproj
<IsPublishable>false</IsPublishable>
and
rm -rd publish
dotnet publish -c Release -o publish
Moment of truth
$ exiftool publish/Newtonsoft.Json.dll
ExifTool Version Number : 11.88
File Name : Newtonsoft.Json.dll
Directory : publish
File Size : 641 kB
File Modification Date/Time : 2018:03:24 18:44:14+01:00
File Access Date/Time : 2021:10:04 12:44:38+02:00
File Inode Change Date/Time : 2021:10:04 12:57:29+02:00
File Permissions : rwxrw-r--
File Type : Win32 DLL
File Type Extension : dll
MIME Type : application/octet-stream
Machine Type : Intel 386 or later, and compatibles
Time Stamp : 2098:12:14 20:33:48+01:00
Image File Characteristics : Executable, Large address aware, DLL
PE Type : PE32
Linker Version : 48.0
Code Size : 653824
Initialized Data Size : 2048
Uninitialized Data Size : 0
Entry Point : 0xa16b6
OS Version : 4.0
Image Version : 0.0
Subsystem Version : 4.0
Subsystem : Windows command line
File Version Number : 11.0.2.21924
Product Version Number : 11.0.2.0
File Flags Mask : 0x003f
File Flags : (none)
File OS : Win32
Object File Type : Dynamic link library
File Subtype : 0
Language Code : Neutral
Character Set : Unicode
Comments : Json.NET is a popular high-performance JSON framework for .NET
Company Name : Newtonsoft
File Description : Json.NET .NET Standard 2.0
File Version : 11.0.2.21924
Internal Name : Newtonsoft.Json.dll
Legal Copyright : Copyright © James Newton-King 2008
Legal Trademarks :
Original File Name : Newtonsoft.Json.dll
Product Name : Json.NET
Product Version : 11.0.2
Assembly Version : 11.0.0.0
Now the assembly published is the expected 11.0.2.
I verify that running my app from the publish folder now works fine!
cd publish
dotnet MyCompany.ItgService.dll
Just use the version that MassTransit depends upon, which is much earlier than v13. Upgrading past that without the proper assembly redirects is likely causing your issue.
I had a very similar problem with the Newtonsoft package in my .NET core 3.1 web application (not using docker). Neither in my main project (web app) nor in the class library (implemented for sending emails) I explicitly referenced Newtonsoft.Json.dll. Running locally on my machine a dotnet publish created the web app correctly with Newtonsoft.Json.dll (v11.0.2). This is the correct dll, I have checked it in the *.deps.json.
Same command on my windows server which I use for the build step in my deplyoment pipeline created a different Newtonsoft.Json.dll (v9.0.1). With this one my web app did not run correctly (same error like you).
What worked for me: I deleted the folder C:\Program Files\dotnet manually. Then I reinstalled the latest .NET SDK x64 on my build server. And BOOM, correct Newtonsoft.Json.dll (v11.0.2) was published. Before that I deinstalled an old Visual Studio 2019 instance and installed a fresh Visual Studio 2022 Enterprise IDE. Apparently, this does not replace the dotnet folder and has no effect. So my conclusion is that the dotnet.exe was buggy I had installed on my server and did not restore correctly the nuget package for Newtonsoft.

dotnet core compile time error - System.Net.Sockets.SocketException (98): Address already in use

Occasionally, while running build on build machine, we are getting multiple errors when trying to run 'dotnet test' command. After all, build succeeds but error is unexpected and might be confusing:
/usr/bin/dotnet test /home/vsts_agent3/VSTS-Desktop-agents/_work/15/s/Name.Tests.csproj --logger trx --results-directory /home/vsts_agent3/VSTS-Desktop-agents/_work/_temp --configuration Prod
MSBUILD : error MSB1025: An internal failure occurred while running MSBuild.
System.Net.Sockets.SocketException (98): Address already in use
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.IO.Pipes.NamedPipeServerStream.SharedServer..ctor(String path, Int32 maxCount)
at System.IO.Pipes.NamedPipeServerStream.SharedServer.Get(String path, Int32 maxCount)
at System.IO.Pipes.NamedPipeServerStream.Create(String pipeName, PipeDirection direction, Int32 maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, Int32 inBufferSize, Int32 outBufferSize, HandleInheritability inheritability)
at System.IO.Pipes.NamedPipeServerStream..ctor(String pipeName, PipeDirection direction, Int32 maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, Int32 inBufferSize, Int32 outBufferSize, HandleInheritability inheritability)
at System.IO.Pipes.NamedPipeServerStream..ctor(String pipeName, PipeDirection direction, Int32 maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, Int32 inBufferSize, Int32 outBufferSize)
at Microsoft.Build.BackEnd.NodeEndpointOutOfProcBase.InternalConstruct(String pipeName)
at Microsoft.Build.Execution.OutOfProcNode.Run(Boolean enableReuse, Exception& shutdownException)
at Microsoft.Build.CommandLine.MSBuildApp.StartLocalNode(CommandLineSwitches commandLineSwitches)
at Microsoft.Build.CommandLine.MSBuildApp.ProcessCommandLineSwitches(CommandLineSwitches switchesFromAutoResponseFile, CommandLineSwitches switchesNotFromAutoResponseFile, String& projectFile, String[]& targets, String& toolsVersion, Dictionary`2& globalProperties, ILogger[]& loggers, LoggerVerbosity& verbosity, List`1& distributedLoggerRecords, Int32& cpuCount, Boolean& enableNodeReuse, TextWriter& preprocessWriter, Boolean& detailedSummary, ISet`1& warningsAsErrors, ISet`1& warningsAsMessages, Boolean& enableRestore, ProfilerLogger& profilerLogger, Boolean& enableProfiler, Dictionary`2& restoreProperties, Boolean recursing)
at Microsoft.Build.CommandLine.MSBuildApp.Execute(String[] commandLine)
Error can be repeated few times, but than finally build succeeds and tests are executed:
Build started, please wait...
Build completed.
Test run for /home/vsts_agent3/VSTS-Desktop-agents/_work/15/s/Project.Web.Tests/bin/Prod/netcoreapp2.1/Name.Tests.dll(.NETCoreApp,Version=v2.1)
Microsoft (R) Test Execution Command Line Tool Version 15.8.0
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
It looks like MSBuildApp start some server inside to compile our sources. It would be great to understand why to make sure we have a safe CI/CD pipeline.
We are running build on Ubuntu and using dotnet core 2.1.

OSX 10.13 DOTNET RUN System.ComponentModel.Win32Exception (0x80004005): No such file or directory

When executing dotnet run -c release in my terminal on OSX 10.13, I get the following error:
../../Properties/launchSettings.json...
System.ComponentModel.Win32Exception (0x80004005): No such file or
directory
at Interop.Sys.ForkAndExecProcess(String filename, String[] argv,
String[] envp, String cwd, Boolean redirectStdin, Boolean
redirectStdout, Boolean redirectStderr, Int32& lpChildPid, Int32&
stdinFd, Int32& stdoutFd, Int32& stderrFd, Boolean shouldThrow)
at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at Microsoft.DotNet.Cli.Utils.Command.Execute()
at Microsoft.DotNet.Tools.Run.RunCommand.Start()
at Microsoft.DotNet.Tools.Run.RunCommand.Run(String[] args)
at Microsoft.DotNet.Cli.Program.ProcessArgs(String[] args, ITelemetry
telemetryClient)
at Microsoft.DotNet.Cli.Program.Main(String[] args)
.NET Command Line Tools (2.2.0-preview1-007582)
Product Information:
Version: 2.2.0-preview1-007582
Commit SHA-1 hash: 4845efe2ea
Runtime Environment:
OS Name: Mac OS X
OS Version: 10.13
OS Platform: Darwin
RID: osx.10.12-x64
Base Path: /usr/local/share/dotnet/sdk/2.2.0-preview1-007582/
Microsoft .NET Core Shared Framework Host
Version : 2.1.0-preview1-25919-02
Build : 96a1025de48784825ac61e45ece24a4343e0bf01
The runtime identifier is set for OSX 10.12 as directed on the Microsoft documents.
The project works on Windows 10, just not on any OSX device.
The launchSettings.json file does exist. If I copy and nano the file, it will edit the file. I'm out of ideas right now.
dotnetcore 2.0.3 and 2.1 have this issue:
https://github.com/dotnet/cli/issues/6397
There is a . in our project name and it's causing the issue.
It's currently reopened as it has not been resolved.
Make sure that you have installed and are using a version of the .NET Core Runtime that supports macOS High Sierra (10.13).
Since you are building a self-contained app, make sure that you set the RuntimeFrameworkVersion to a recent version to ensure that you include all the assets necessary to run on High Sierra.
For example:
<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<RuntimeFrameworkVersion>1.0.8</RuntimeFrameworkVersion>
</PropertyGroup>
or if you are using .NET Core 1.1:
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
<RuntimeFrameworkVersion>1.1.5</RuntimeFrameworkVersion>
</PropertyGroup>
.NET Core 2.0 always supported High Sierra, but to get the newest runtime for self-contained apps, you currently also need to set this property:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.3</RuntimeFrameworkVersion>
</PropertyGroup>

Adding migrations: System.MissingMethodException: Method not found ILibraryManager

Full error:
System.MissingMethodException: Method not found:
'Microsoft.Extensions.PlatformAbstractions.ILibraryManager
Microsoft.Extensions.PlatformAbstractions.PlatformServices.get_LibraryManager()'.
at Microsoft.Data.Entity.Commands.Program.ValidateProject(String
targetProject) at
Microsoft.Data.Entity.Commands.Program.<>c__DisplayClass2_7.b__15()
at
Microsoft.Dnx.Runtime.Common.CommandLine.CommandLineApplication.Execute(String[]
args) at Microsoft.Data.Entity.Commands.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute(Assembly
assembly, String[] args, IServiceProvider serviceProvider) at
Microsoft.Dnx.ApplicationHost.Program.<>c__DisplayClass3_0.b__0()
at System.Threading.Tasks.Task`1.InnerInvoke() at
System.Threading.Tasks.Task.Execute()
Command that I try to run:
dnx ef migrations add test1
Version of EF commands:
Entity Framework Commands 7.0.0-rc1-16348
Version of dnx:
Microsoft .NET Execution environment Clr-x86-1.0.0-rc2-16595
My project currently use RC1. It all worked before.
Mostly sure the issue is the fact that you're mixing RC1 packages with RC2 runtime. Downgrade the runtime to RC1 or switch from dnx to dotnet and upgrade the packages to RC2

Saving a file to 'C:\Windows\System32\dns' causes 'Could not find a part of the path' error

I've written a windows forms (.net 4) application that needs to write a file to the folder 'C:\Windows\System32\dns'. When this line of code runs:
File.WriteAllText(dnsFileLocation, luxDns)
I get the following error, does anyone know why?
Note: This happens even if I run the application as administrator!
***** Exception Text *******
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Windows\System32\dns\lux2.dns'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
at System.IO.File.InternalWriteAllText(String path, String contents, Encoding encoding)
at System.IO.File.WriteAllText(String path, String contents)
at DnsServerUpdater.Main.Main_Load(Object sender, EventArgs e)
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
************** Loaded Assemblies **************
mscorlib
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.261 (RTMGDR.030319-2600)
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
DnsServerUpdater
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/web/dns/DnsServerUpdater.exe
----------------------------------------
Microsoft.VisualBasic
Assembly Version: 10.0.0.0
Win32 Version: 10.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/Microsoft.VisualBasic/v4.0_10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll
----------------------------------------
System
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.261 built by: RTMGDR
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Core
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.233 built by: RTMGDR
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Windows.Forms
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.235 built by: RTMGDR
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.276 built by: RTMGDR
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Runtime.Remoting
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Runtime.Remoting/v4.0_4.0.0.0__b77a5c561934e089/System.Runtime.Remoting.dll
***** JIT Debugging *******
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.
For example:
<configuration>
<system.windows.forms jitDebugging="true" />
</configuration>
When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
Are you running 64bit windows ? If yes then that's probably your issue as you will get redirected in another directory.
You will need to implement
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365743%28v=vs.85%29.aspx and
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365745%28v=vs.85%29.aspx
in order to temporarily disable the 64bit redirection in order to access that folder.
Can you check if the directory exists? Since system32 is a windows folder, to create files and folders inside it requires special rights. Does the user who is running the win forms app have rights to create folder/file inside the system32 folder?

Resources