C# .NET Core 2.2 - C# MongoDB.Driver - Exception - c#

I have 4 projects:
A - .NET Core 2.2 project - reference to B and D (knows nothing about C)
B - .NET 4.7.2 Class Library - reference to C and D
C - .NET 4.7.2 Class Library - reference D and the the MongoDB C# Driver (Version 2.7.30) installed with NuGet.
D - .NET 4.7.2 Class Library - just a container for DTO classes
All projects do build and run.
===
B is a generic data repository.
C is a database context, which uses the MongoDB C# driver.
Both projects B and C work well without any errors, when I use them in "normal" .NET 4.7.2, also 4.5.2 projects.
===
The error:
When I make a call from the .NET Core project A to B which ends in C, I get an error at this point:
private IMongoCollection<T> _Collection;
public IMongoCollection<T> Collection
{
get
{
if (_Collection == null)
{
//This is still ok!
_Collection = _DataBase.GetCollection<T>("MyTableName");
}
return _Collection;
}
}
public IEnumerable<T> All
{
get
{
try
{
//Collection is NOT Null and was loaded from the DB
return Collection.Find(new BsonDocument()).ToList();
}
catch (Exception ex)
{
//THE EXCEPTION APPEARS HERE
}
return null;
}
}
The exception details are:
{System.TypeLoadException: Could not load type 'System.Runtime.Remoting.Messaging.CallContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
at MongoDB.Driver.Core.Events.EventContext.AsyncLocal1.get_Value()
at MongoDB.Driver.Core.Events.EventContext.BeginOperation(Nullable1 operationId)
at MongoDB.Driver.Core.Operations.FindCommandOperation1.Execute(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.FindOperation1.Execute(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.OperationExecutor.ExecuteReadOperation[TResult](IReadBinding binding, IReadOperation1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.ExecuteReadOperation[TResult](IClientSessionHandle session, IReadOperation1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.ExecuteReadOperation[TResult](IClientSessionHandle session, IReadOperation1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.FindSync[TProjection](IClientSessionHandle session, FilterDefinition1 filter, FindOptions2 options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass41_01.b__0(IClientSessionHandle session)
at MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSession[TResult](Func2 func, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.FindSync[TProjection](FilterDefinition1 filter, FindOptions2 options, CancellationToken cancellationToken)
at MongoDB.Driver.FindFluent2.ToCursor(CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
...}
(sorry for the full exception, but I thought it would help)
My question:
What can I do to solve this problem?
As I said earlier above - this seems to be a .NET Core problem, since the projects run without any error in other projects.

After debugging and testing countless scenarios, I figured out, what was wrong.
Man, that was really hard to find out, because there was only one little hint here on SO that helped me.
So the story from beginning to end:
1.) I have a "normal" .NET 4.7.2 DLL, which hosts my custom MongoDB context.
2.) To do this, I installed the MongoDB Nuget package into this DLL.
3.) The package worked well and as expected when in collaboration with other "normal" .NET 4.7.2 DLLs. No problem. Very happy.
4.) When trying to use my 4.7.2 DLL with a .NET Core project, I get the exception in the start post. Shit.
5.) What you have to keep in mind: When you install a nuget package, it seems to install and references the DLLs, that targets the same (nearest?) framework. In my case target was 4.7.2, so NuGet installed 4.5 versions of the MongoDB.Driver and MongoDB.Driver.Core.
6.) What you actually need, when working with .NET Core, are NOT the 4.5 versions, but the NetStandard 1.5 versions of BOTH MongoDB.Driver and MongoDB.Driver.Core.
7.) So I downloaded the Nuget packages of MongoDB.Driver and MongoDB.Driver.Core manually. NuGet packages are just *.zip files, so I changed the extension and unpacked them.
8.) Inside of each package you find a lib folder with two folders: net45 and netstandard1.5
9.) I extracted the netstandard 1.5 versions of BOTH MongoDB.Driver and MongoDB.Driver.Core.
10.) I replaced the references of BOTH MongoDB.Driver and MongoDB.Driver.Core inside my .NET 4.7.2 DLL with the Netstandard 1.5 versions - BOOM! Working!
So everything in summary:
If (.NET Core + MongoDB)
{
use MongoDB.Driver Netstandard 1.5;
use MongoDB.Driver.Core Netstandard 1.5;
}
If (.NET + MongoDB)
{
use MongoDB.Driver Net 4.5;
use MongoDB.Driver.Core Net 4.5;
}
I really hope, my answer saves others hours or even days of pure confusion.

In my case my Core standart library project has using normal library project even i have changed 4.5, 4.52, 4.61, 4.72 vs. but problem never ended until converting normal lib project to standart library project.
I suggest convert to standart lib

Related

Does SevenZipSharp work with .NETCore on Windows?

I have a .NETCore app which I am trying to add 7 zip functionality to.
Compiling gives this warning:
warning NU1701: Package 'SevenZipSharp 0.64.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project.
So I presume the project is .NETCore v5.0. Can I run SevenZipSharp in this project?
Running the app gives an error at the call to CompressFiles: SevenZip.SevenZipLibraryException: 'Can not load 7-zip library or internal COM error! Message: failed to load library.'
public void ZipQOB(string sevenZipDllPath, string zippedQobPath, string unzippedQobFiles)//List<string> sourceFiles)
{
// throw exception if paths passed in are null, does 7zipsharp throw exceptions in this case?
try
{
if (System.IO.File.Exists(sevenZipDllPath) && System.IO.Directory.Exists(zippedQobPath))// && System.IO.Directory.Exists(unzippedQOBFiles))
{
string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll");
//SevenZipCompressor.SetLibraryPath(sevenZipDllPath);
SevenZipCompressor.SetLibraryPath(path);
SevenZipCompressor sevenZipCompressor = new()
{
CompressionLevel = SevenZip.CompressionLevel.Ultra,
CompressionMethod = CompressionMethod.Lzma
};
string[] files = System.IO.Directory.GetFiles(unzippedQobFiles);
sevenZipCompressor.CompressFiles(zippedQobPath + #"\zip.QOB", files);
//System.IO.Path.ChangeExtension(zippedQobPath, ".QOB");
}
This question How do I use 7zip in a .NET Core app running on Linux? mentions a CLI wrapper ported from .NET Framework to .NET Core, but I can't find any details - is this something I would have to write and how?
I have already tried things suggested elsewhere, I altered the project build setting to:
Platform Target = AnyCPU,
ticked Prefer 32-bit
Should I just look at a different option as this page seems lists some stating .netcore compatible: https://github.com/topics/7zip?l=c%23
Many thanks for any help :)

Oracle blocks NET6 migration - Detected package version outside of dependency constraint

I am currently migrating our main NET Core 3.1 app to NET 6. Our database access layer is encapsulated into a class library using EF Core 3.1 that also needs migrating to a newer version. In that lib, there is logic to access 2 databases, Azure Sql und Oracle Sql.
The Oracle.EntityFrameworkCore nuget package is not yet available for NET6.
dotnet restore gives the following warning:
warning NU1608: Detected package version outside of dependency constraint: Oracle.EntityFrameworkCore 5.21.4 requires Microsoft.EntityFrameworkCore.Relational (>= 5.0.9 && < 6.0.0) but version Microsoft.EntityFrameworkCore.Relational 6.0.0 was resolved.
Running a query against Oracle throws a TypeLoadException
Unhandled exception. System.TypeLoadException: Method 'AppendIdentityWhereCondition' in type 'Oracle.EntityFrameworkCore.Update.Internal.OracleUpdateSqlGenerator' from assembly 'Oracle.EntityFrameworkCore, Version=5.0.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342' does not have an implementation.
at Microsoft.Extensions.DependencyInjection.OracleServiceCollectionExtensions.<>c.<AddEntityFrameworkOracle>b__0_4(ServiceCollectionMap b)
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.TryAddProviderSpecificServices(Action`1 serviceMap)
at Microsoft.Extensions.DependencyInjection.OracleServiceCollectionExtensions.AddEntityFrameworkOracle(IServiceCollection serviceCollection)
at Oracle.EntityFrameworkCore.Infrastructure.Internal.OracleOptionsExtension.ApplyServices(IServiceCollection services)
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions options, ServiceCollection services)
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<GetOrAdd>g__BuildServiceProvider|4_0(IDbContextOptions options, ConcurrentDictionary`2 configurations)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd[TArg](TKey key, Func`3 valueFactory, TArg factoryArgument)
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions options, Boolean providerRequired)
at Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions options)
at OracleLib.MyDbContext..ctor(DbContextOptions`1 options)
at App.Program.Main(String[] args) in C:\Users\me\app\Program.cs:line 39
at App.Program.<Main>(String[] args)
I then tried splitting the Azure Sql part and Oracle Sql part, with the latter targeting only NET5. I then dotnet pack'ed both libs and included them in an NET6 app. But again, I am getting the above warning and typeload exception.
Oracle effectively keeps me from migrating to NET6. Is there any way I can tell the oracle lib to use its own lower version of Microsoft.EntityFrameworkCore.Relational and call it a day?

Method not found: 'System.Threading.Tasks.Task`1<!!0>

i'm using the Microsoft Graph Apps to retrieve or create OneDrive files. I made a POC last week and everything worked wonderfully.
Now i tried implementing the our App into an existing MVC website but i'm having weird messages that System.Threading.Tasks.Task cannot be found:
at Microsoft.Graph.DriveRequest.<GetAsync>d__6.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Graph.DriveRequest.GetAsync(CancellationToken cancellationToken)
at Microsoft.Graph.DriveRequest.GetAsync()
at BizzMine.Data.Repositories.OnlineEditorRepo.OnlineEditorRepository.<RequestSuccess>d__10.MoveNext() in C:\Users\geertverthe\Documents\repos\bizzmine\BizzMine.Data.Repositories\OnlineEditorRepo\OnlineEditorRepository.cs:line 89
I suspect that there is some kind of problem with binding references to System.Threading.Tasks or even System.Web.Http but i am not sure.
This is the (simple) code i use:
Drive myDrive = await _graphServiceClient.Me.Drive.Request().GetAsync();
And my GraphServiceClient is constructed like this:
_graphServiceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) => {
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", _tokens.AccessToken);
await Task.FromResult<object>(null);
}));
.NET Framework version is 4.6.1
I do have the correct consent permissions and do have a valid access token.
Any idea on why i receive such kind of error and how i can fix this?
Thank you very much
After lot of trying i managed to solve my issue. Since our solution and projects contain lots of nuget packages, one of them was system.net.http. Apparantly this came with a package NETStandard.Library.1.6.1.
I found it strange to have a nuget package for system.net.http as this is just in the framework itself.
I could delete the system.net.http nuget packages after upgrading NETSTandard.Library.1.6.1 to the latest version.
Only changes i had to do after this was referencing the FRAMEWORK system.net.http in projects where it was missing and removing an obsolete binding redirect in some projects.
It works fine now :-)

ServiceStack error calling Request.GetRawBody();

I am attempting to get access to the underlying JSON object (request body) within a service call in service stack. The reason I wish to do this is to create a PATCH version of an existing service, which will only attempt to update fields that were in the JSON. Seems simple enough:
public object Patch(AddUpdateContactRequest request)
{
var json = this.Request.GetRawBody();
var keysToUpdate = JsonSerializer.DeserializeFromString<Dictionary<string, string>>(json);
return Put(request);
}
However, I get an exception from service stack when GetRawBody() is called (when service stack is calling in to .NET core):
Message: "Could not load type
'Microsoft.AspNetCore.Http.Internal.BufferingHelper' from assembly
'Microsoft.AspNetCore.Http, Version=3.0.0.0, Culture=neutral,
PublicKeyToken=adb9793829ddae60'."
Source: "ServiceStack"
StackTrace: " at ServiceStack.Host.NetCore.NetCoreRequest.GetRawBody() in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\NetCore\NetCoreRequest.cs:line
211"
TargetSite: {System.String GetRawBody()}
TypeName: "Microsoft.AspNetCore.Http.Internal.BufferingHelper"
It seems to be referencing version 3.0 of Microsoft.AspNetCore.Http, but this version does not have the namespace Microsoft.AspNetCore.Http.Internal.BufferingHelper. It looks like a version mismatch issue, but I cannot seem to make it work. I cannot see any dll version conflicts locally, I am implicitly referencing the latest version of .NET core and have the latest SDK/hosting package installed.
If this is .NET Core 3.0 this is due to a breaking change in .NET Core 3.0 which has been resolved in the latest v5.7.1 packages on MyGet.

How do I build using the native corert preview?

I have tried to get a .NET core 2.0 console application targeting win-x86 to build using the corert ilc compiler and microsoft linker.
So far I downloaded the latest version of the corert libraries and successfully built a preview using the release target as of commit c7781a90f00645f6bd06ef57e5d3fd879fe3e9a0.
I added build scripts rd.xml, ilc.rsp, and link.rsp, but I keep getting the message from ilc:
Error: Target architecture is not supported
Internal.CommandLine.CommandLineException: Target architecture is not supported
at ILCompiler.Program.Run(String[] args)
at ILCompiler.Program.Main(String[] args)
UPDATE: I was able to resolve the issue with the architecture, but now it is failing with a missing file reference:
C:\testapp>call "..\corert\bin\Windows_NT.x64.Release\tools\ilc.exe" ".\ilc.rsp"
Error: [TEMPORARY EXCEPTION MESSAGE] FileLoadErrorGeneric: Microsoft.Extensions.Options
Internal.TypeSystem.TypeSystemException+FileNotFoundException: [TEMPORARY EXCEPTION MESSAGE] FileLoadErrorGeneric: Microsoft.Extensions.Options
at Internal.TypeSystem.ThrowHelper.ThrowFileNotFoundException(ExceptionStringID id, String fileName)
at ILCompiler.CompilerTypeSystemContext.GetModuleForSimpleName(String simpleName, Boolean throwIfNotFound)
at Internal.TypeSystem.CustomAttributeTypeNameParser.GetTypeByCustomAttributeTypeName(ModuleDesc module, String name, Boolean throwIfNotFound, Func`4 resolver)
at Internal.TypeSystem.CustomAttributeTypeNameParser.GetTypeByCustomAttributeTypeName(ModuleDesc module, String name, Boolean throwIfNotFound, Func`4 resolver)
at ILCompiler.RdXmlRootProvider.ProcessTypeDirective(IRootingServiceProvider rootProvider, ModuleDesc containingModule, XElement typeElement)
at ILCompiler.RdXmlRootProvider.ProcessAssemblyDirective(IRootingServiceProvider rootProvider, XElement assemblyElement)
at ILCompiler.RdXmlRootProvider.AddCompilationRoots(IRootingServiceProvider rootProvider)
at ILCompiler.Compilation..ctor(DependencyAnalyzerBase`1 dependencyGraph, NodeFactory nodeFactory, IEnumerable`1 compilationRoots, DebugInformationProvider debugInformationProvider, Logger logger)
at ILCompiler.ILScannerBuilder.ToILScanner()
at ILCompiler.Program.Run(String[] args)
at ILCompiler.Program.Main(String[] args)
UPDATE 2: I was able to resolve the issues by finding references for all the missing files, but in the end I realized I needed to switch the architecture target to x64, however now it fails at the linker:
C:\testapp>call link #".\link.rsp"
libcpmt.lib(nothrow.obj) : fatal error LNK1112: module machine type 'x86' conflicts with target machine type 'x64'
The issue is caused by using the Developer Command Prompt instead of the x64 Native Tools Command Prompt. The former one targets x86 by default, but the latter one targets x64 and will link against the x64 libraries.

Categories

Resources