Using Fluent NHibernate SQL Server CE cannot create the driver - nhibernate

Could not create the driver from NHibernate.Driver.SqlServerCeDriver,
NHibernate, Version=3.3.0.4000, Culture=neutral,
PublicKeyToken=aa95f207798dfdb4.
inner exeption:
The IDbCommand and IDbConnection implementation in the assembly System.Data.SqlServerCe could not be found. Ensure that the assembly System.Data.SqlServerCe is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use element in the application configuration file to specify the full name of the assembly.
This is the error I get when I try to use fluent nHibernate!
I try the simple examples by the configuration doesn't work well with local database
using this dlls.
My code:
private static String ConnectionString = "Data Source = Database1.sdf";
public static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlCeConfiguration.Standard
.ConnectionString(ConnectionString)
.Driver<NHibernate.Driver.SqlServerCeDriver>()
.Dialect<NHibernate.Dialect.MsSqlCeDialect>())
.Mappings(m => m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly()))
.ExposeConfiguration(BuildSchema)
.ExposeConfiguration(x => x.SetProperty("connection.release_mode", "on_close"))
.BuildSessionFactory();
}
private static void BuildSchema(Configuration configuration)
{
SchemaExport schemaExport = new SchemaExport(configuration);
schemaExport.Execute(false, true, false);
}
Thank you! It's very important!
i found that it break in the buildsessionfactory...helpppp!!!!

If you're coming at this from .net core, and you're getting the error message
The IDbCommand and IDbConnection implementation in the assembly
System.Data.SqlServerCe could not be found. Ensure that the assembly
System.Data.SqlServerCe is located in the application directory or in
the Global Assembly Cache. If the assembly is in the GAC, use element
in the application configuration file to specify the full name of the
assembly.
Assuming you've installed NHibernate via NuGet, then you need to ensure the appropriate Sql package is installed. There are a couple of unofficial System.Data.SqlServerCe out there. In my case I needed System.Data.SqlClient

Are you sure you do have Version=3.3.0.4000 of NHibernate in your bin directory? It looks like you have a different build of NHibernate in your bin directory.
If you sure it is there, check if your references are correct:
Do you have a reference in your project to:
"System.Data.SqlServerCe"
This is located in the following dir:
"C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Desktop\System.Data.SqlServerCe.dll"
Make sure you have:
"Copy Local" to true.

Related

Issue with nested DLL referencing in a self-contained .Net Core web app running as a Windows service

The Error
First off, lets start with the error message:
System.BadImageFormatException: 'Could not load file or assembly 'System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (0x80131058)'
In my experience, this type of error usually occurs if the DLL is missing, or it's not in the expected format/version. However, I cannot work out what I need to do to resolve this error.
The Setup
The main project is an ASP.Net Core 3.1 application.
It is configured to be able to run as a Window service and support Web API and MVC frameworks. So my Program.cs looks something like this:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var builder = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
builder.UseWindowsService();
return builder;
}
}
That part all works great, I can run the app as a Windows service and serve razor views and web API endpoints, etc.
However, there are more projects in this solution. I have a couple of .Net 4.6 class libraries projects that are referenced by the service app. So my solution looks something like this:
Service App (NET CORE 3.1)
Lib 1 (NET 4.6)
Lib 2 (NET 4.6)
Service App references Lib 1, and Lib 1 references Lib 2.
Any code is either of these two libraries works fine and can be used by the service app.
The problem is that Lib 2 references System.Management DLL, and this is what is causing the error. Whenever I use a function that uses that DLL, I get the error above.
The Attempts So Far
My attempts so far have including:
Setting the DLL to "copy to output"
Adding the DLL reference directly to the web service app
Manually copying the DLL to the output folder. Both debug, and publish folder (note: publish is set to "self contained" application)
The Question
Basically, how can I resolve this issue? Or at least, how can I further debug the problem to potentially find a solution.
I can't repro this at the time, but I suspect this to be a bug in the way that the self-contained publication process using dotnet publish resolves transitive dependencies.
The point is, your .NET Core 3.1 application doesn't run on .NET Framework, while the library you reference, call it "Lib 2", does.
And your Lib 2 has a reference to the NuGet package System.Management, which, when installed on a project targeting .NET Framework ... does nothing, except making your project reference the .NET Framework reference assembly for System.Management, found in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1. At runtime, the .NET Framework will load the appropriate assembly from the GAC, but the .NET Core runtime does not do this.
Now when publishing your .NET Core app, MSBuild walks through the dependencies to be copied, and (again, I suppose) looks at the reference assembly and goes "I want that one!" and copies it to your output directory.
But you can't run reference assemblies, you can just reference them, so at runtime, your application blows up with an exception stating exactly that:
Reference assemblies should not be loaded for execution
A workaround, but definitely not a solution, is to reference the same System.Management package from your .NET Core application, where the package will actually extract a DLL containing runnable code, and that one will be copied to your output directory. But this might cause other issues, such as the DLL being overwritten during build with the reference one.
I'd suggest looking at GitHub whether this is a known issue, or that this is something caused by your project setup.

Could not find 'UserSecretsIdAttribute' on assembly but it exists and correct package is added

I follow this tutorial: https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-3.1&tabs=windows#access-a-secret
To a .NET Core 3.1 project I've added Microsoft.Extensions.Configuration.UserSecrets package, I have clicked on the project to manage secrets, the file has been created in the AppData directory and the UserSecretsId has been added automatically in .csproj file.
Because the Host.CreateDefaultBuilder didn't load secrets I decided to add them manually
if (hostContext.HostingEnvironment.IsDevelopment())
{
builder.AddUserSecrets(Assembly.GetExecutingAssembly());
}
})
.Build();
But then I get
System.InvalidOperationException
HResult=0x80131509
Message=Could not find 'UserSecretsIdAttribute' on assembly 'XXX'.
Check that the project for 'XXX' has set the 'UserSecretsId' build property.
If the 'UserSecretsId' property is already set then add a reference to the Microsoft.Extensions.Configuration.UserSecrets package.
Source=Microsoft.Extensions.Configuration.UserSecrets
I've checked the suggestion in the expecion's description and both predicaments are fulfilled.
Same issue here. after check the source code in GitHub
https://github.com/aspnet/Configuration/blob/f64994e0655659faefccead7ccb5c1edbfd4d4ba/src/Config.UserSecrets/UserSecretsConfigurationExtensions.cs#L94
Check if you have <GenerateAssemblyInfo>true</GenerateAssemblyInfo> in your .csproj file as well.
Faced the same runtime error. I have disabled the automatic creation of the AssemblyInfo for assembly in the csproj, because my system CI automatically updates this file with the version of the build
My fix is to add
[assembly: UserSecretsId ("<Project guid>")]
in AssemblyInfo.
You should have the UserSecretsId listed in your .csproj file. If you right click on the API layer and manage user secrets confirm that the GUID matches in the AppData directory with whats in the project.
<PropertyGroup>
<UserSecretsId>Your GUID</UserSecretsId>
Your Program.cs class should be using the CreateDefaultBuilder, you should see that there is a section to include Secrets when the environment is Development. Check your ASP "ASPNETCORE_ENVIRONMENT": "Development" is set to development. Lastly I'm assuming your executing assembly has the PropertyGroup for the user secrets mentioned above.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Just use the context menu on your project and choose "Manage User Secrets..." and save the empty user secrets configuration file. Visual Studio should create the necessary project file entries automatically.

Referencing DLL's between solutions

I've found an interesting issue with using DLL's in .NET Core (.NET Framework works fine). MVCE as follows:
Create an F# (language is irrelevant) .NET Core class library with the following single file (specific code irrelevant as well):
namespace FSharpClassLibrary
module Say =
let hello name =
printfn "Hello %s" name
Create a C# .NET Core class library in a separate solution (very important--it completely works if they are all in the same solution) with the following code:
namespace CSharpClassLibrary
{
public class HelloClass
{
public void Hello(string name)
{
FSharpClassLibrary.Say.hello(name);
}
}
}
Also, add a folder dlls, copy/paste FSharpClassLibrary.dll into it, and add it as a reference to the project (otherwise, the file above won't compile). It's actually not important to move the .dll into the project, but since I'm distributing this second project independently of the first, I need to guarantee the DLL is available.
Finally, add a console app to the same solution as CSharpClassLibrary with the following file:
using System;
using CSharpClassLibrary;
namespace ConsoleApp1
{
public class Main1
{
public static void Main()
{
new HelloClass().Hello("test");
#if DEBUG
Console.Write("Press any key");
Console.ReadKey();
#endif
}
}
}
Finally, go into NuGet and add FSharp.Core version 4.3.4 to both C# projects (just to make sure everything has access to the F# language stuff; not necessary if you create the first class library with C#). Also, I am using VS 15.6; this may or may not be relevant as well.
Set the console app as the startup project and run it. You will get the following error:
System.IO.FileNotFoundException: Could not load file or assembly 'FSharpClassLibrary, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'FSharpClassLibrary, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
at ClassLibrary1.Facade.Hello1.Hello(String name)
at ConsoleApp1.Main1.Main() in C:\Users\***\source\ConsoleApp1\ConsoleApp1\Main.cs:line 11
The most curious part about this is that if I bypass the CSharpClassLibrary library and host FSharpClassLibrary.dll and HelloClass.cs in the ConsoleApp1 project, everything works as expected. The same issue happens if I use two C# DLL's, I used F# because that's what I was working with already.
What I already tried:
Cleaning and rebuilding all projects, making sure each project was referencing the latest build.
Referencing the child (FSharpClassLibrary.dll) from ConsoleApp1 as well as CSharpClassLibrary.dll.
Using the .dll from the obj folder instead of the bin folder (shouldn't matter as far as I'm aware).
Verify that FSharpClassLibrary.dll exists in ConsoleApp1's bin folder.
Double-check that all projects compile to .NET Core, no .NET Standard projects.

NHibernate - missing dll's

This call
// this._cfg is an NHibernate Configuration instance
this._sessionFactory = this._cfg.BuildSessionFactory();
Gives me this exception at runtime (NOT at compile time).
Could not load file or assembly 'NHibernate.ByteCode.Castle' or one of its dependencies. The system cannot find the file specified.":"NHibernate.ByteCode.Castle
OK so far. But the thing is, this code is running in a class library project, and I have referenced NHibernate.ByteCode.Castle (along with all the other NHibernate dll's) in that project.
Wierder: I can fix the exception by additionally referencing the NHibernate dll's in the Windows WPF executable project that calls my class library. But the Windows WPF executable contains no code that directly uses NHibernate (as evidenced by: It compiles fine without any NHibernate references). So what's going on? Apparently it's insufficient to reference NHibernate.ByteCode.Castle in the project that actually uses the NHibernate stuff. Anyone know why?
I know this is old, but what I've done to fix the dependency problem is simple:
In my UnitOfWork I added one static method:
private static void bringCastleDamnit()
{
var pf = new NHibernate.ByteCode.Castle.ProxyFactoryFactory();
}
Then, and only then, would MSBuild see that it was needed and copy it to my output directory for my (asp.net and console) apps that references my Data project.
I wouldn't reference the castle byte code factory at all; just ensure it (and all other needed dependancies) are copied to the output directory using a post-build step.

Odd Exception when Combining .hbm.xml and Fluent NHibernate - Any ideas?

So I'm converting my mapping files on an as needed basis (when making
changes, convert to mapping). Any when configuring NHibernate like so:
Assembly asm = Assembly.Load("RPMWare.Core.DataAccess");
//NHibernate configuration: see hibernate.cfg.xml
var cfg = new Configuration();
cfg.AddMappingsFromAssembly(asm);
cfg.Configure();
And running my web-application I get the following exception:
Could not load file or assembly 'NHibernate, Version=2.0.0.4000,
Culture=neutral, PublicKeyToken=aa95f207798dfdb4' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
However, all my integration tests are working as expected. Any ideas?
Nevermind. If you're using the latest version of Fluent NHibernate and the lastest version of NHibernate you need to add YOUR VERSION of NHibernate to the Fluent NHibernate project before building.