How do I call SQLitePCL.Batteries.Init().? - c#

I am attempting to create an SQLite database for my application and have come across this error.
System.Exception: 'You need to call SQLitePCL.raw.SetProvider(). If
you are using a bundle package, this is done by calling
SQLitePCL.Batteries.Init().'
I created a simple console app the run the exact same code for creation, with no issues. The code looks like this!
using (var dataContext = new SampleDBContext())
{
dataContext.Accounts.Add(new Account() { AccountName = name, AccountBalance = balance });
}
public class SampleDBContext : DbContext
{
private static bool _created = false;
public SampleDBContext()
{
if (!_created)
{
_created = true;
Database.EnsureDeleted();
Database.EnsureCreated();
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
{
optionbuilder.UseSqlite(#"Data Source="Source folder"\Database.db");
}
public DbSet<Account> Accounts { get; set; }
}
Can anyone shed any light on the issue? I installed the same Nuget Packages on both projects, the only difference between the two is the Data Source and the POCO classes I used for the database.
Thanks.
Edit
My program currently consists of a Console application that references a .Net Framework Class Library. The Console application simple has a constructor that looks like this:
public Program()
{
using (var db = new FinancialContext())
{
db.Accounts.Add(new Account() { AccountName = "RBS", AccountBalance=20 });
}
}
The Class Library has a FinancialContext as Follows:
public class FinancialContext : DbContext
{
public DbSet<Account> Accounts { get; set; }
public FinancialContext()
{
# Database.EnsureDeleted();
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
{
optionbuilder.UseSqlite(#"Data Source="Some Source Folder"\Database.db");
}
}
The Above error is shown at the # symbol point, is there a problem with the way I am coding? I would really like to know what the issue is so I can fix it properly rather than apply a 'fix'. Also I tried the suggestion in the comments, but putting the code line SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_e_sqlite3()); in the Console Application gave the error SQLitePCL is not in the current context, which leaves me thinking I am missing a reference?

This happened to me when I tried to avoid any additional dependencies and went for the Microsoft.EntityFrameworkCore.Sqlite.Core package.
You should install and use the Microsoft.EntityFrameworkCore.Sqlite package instead, which has a dependency upon the SQLitePCLRaw package.

Install Nuget Package Microsoft.Data.Sqlite (not Microsoft.Data.Sqlite.Core). (my version is 2.2.2)
and use SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_e_sqlite3());
connection = new SqliteConnection("Data Source = Sample.db");
SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_e_sqlite3());
connection.Open();
but I advise use nuget package System.Data.SQLite instead Microsoft.Data.Sqlite

I had this very exact error. It turned out that I had package Microsoft.Data.Sqlite.Core (2.2.4) installed, but not SQLitePCLRaw.bundle_winsqlite3.
Installing package SQLitePCLRaw.bundle_winsqlite3 (1.1.13) solved the issue.

Switching from Microsoft.Data.Sqlite.Core to Microsoft.Data.Sqlite as Patrick said here did the trick for me

I got this issue when working with Microsoft.EntityFrameworkCore.Sqlite version 3.1.10. The above solutions did not work for me. Then I have modified the My DbContext as follows (added SQLitePCL.Batteries.Init(); to OnConfiguring method) and the issue is gone!!!
public class ApplicationDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=mydb.db");
SQLitePCL.Batteries.Init();
}
}

For some reason the Nuget Package hadn't installed the required references, reinstalled the package and it has corrected the issue!
Missing the SQLitePCL.raw* references.

I had the same issue when I try to use, Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.6". What I did was downgrade the version into 2.2.2 which I was previously used. Then issue not occur.

On Xamarin.iOs I had the same problem.
Solution: Call SQLitePCL.Batteries_V2.Init() In the FinishedLaunching method of your AppDelegate class.
Source: https://learn.microsoft.com/en-us/dotnet/standard/data/sqlite/xamarin

Related

grab UserSecrets from a NuGet package

I've written a C# class library for my company to use internally, and it uses DotNet UserSecrets to allow each developer to have their own credentials set without needing to worry about accidentally committing them. It worked fine during testing, but after installing it as a NuGet package as opposed to a project dependency, it no longer seems to be able to read from the secrets.json file. I'm wondering if this is a security thing that C# prevents, or if I need to do something else to enable that functionality in an external package.
The package code looks like this:
using Microsoft.Extensions.Configuration;
using TechTalk.Specflow;
namespace Testing.Utilities
{
[Binding]
public class Context
{
private static IConfigurationRoot configuration { get; set; }
private static FeatureContext feature_context;
// SpecFlow attribute runs this before anything else executes
[BeforeFeature(Order = 1)]
private static void SetFeatureContext(FeatureContext context)
{
try
{
configuration = new ConfigurationBuilder()
.AddUserSecrets<Context>()
.Build();
}
catch { }
feature_context = context;
test_context = context.FeatureContainer.Resolve<TestContext>();
}
public static string GetSecretVariable(string name)
{
object v = null;
// if the user secrets were found
if (configuration != null)
{
v = configuration[name];
}
if (v == null)
{
Logger.Warning($"secret variable '{name}' not found");
return null;
}
return v.ToString();
}
}
}
And in the calling code which always gets Null from the getter method:
using Testing.Utilities; // via NuGet package
namespace Testing
{
public static void Main()
{
System.Console.WriteLine($"found {Context.GetSecretVariable("super_secret")}");
}
}
Update:
It works as expected when I drag my locally built .nupkg file into my NuGet package cache and replace the one pulled from the repo. I updated the version number and pushed the change so I know they are on the same version, and it still only worked when I manually inserted my build. Now I'm more confused...
I ported the project from .NET Framework 4.6.1 to .NET 6 and it seemed to fix it. Kinda drastic change, but easy enough refactor and 461 is EOL anyways.

Entity Framwork Core Add-Migration fails

I'm trying to use Ef Core in my project.
The structure is a little different, in the sense that I'm not using EfCore insite the WebApi.csproj. In fact I have a different dll. and a DependenciesResolver.dll that handles all my dependency injection.
In my EfCore.dll I've installed both
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Now when I try to run the command (the dll in which I'm running is the EfCore.dll)
Add-Migration Name
I get this :
An error occurred while accessing the IWebHost on class 'Program'.
Continuing without the application service provider. Error: Object
reference not set to an instance of an object. Unable to create an
object of type 'StoreContext'. Add an implementation of
'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time.
The structure of the sln is like this
WebApi | EfCore.dll | DependencyResolver.dll and I want to keep it this way, don't want to permit using EfCore in my WebApi.
What is the resolution for this issue ?
If this helps within the EfCore.dll I have this.
public sealed partial class StoreContext : DbContext, IStoreContext
{
private string _connectionString;
public StoreContext(string connectionString) : base()
{
_connectionString = connectionString;
Database.EnsureCreated();
}
/// db.tbls
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddOrderConfiguration();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
}
which is called by DependencyResolver like this
private DependenciesResolver RegisterInfrastructure()
{
_serviceCollection.AddScoped<StoreContext>(factory => new StoreContext(_connectionString));
return this;
}
and the DependencyResolver is then called by the WebApi
Please have a look at this: https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
The error message clearly specifies the EF Core tools can't create an instance of your Context at design-time.
If you can define a constructor with no parameters for your StoreContext that would work, otherwise you need tell the tools how to create an instance of your context at design-time by defining a class that implements the IDesignTimeDbContextFactory interface.

How do you install an engine for JavaScriptEngineSwitcher?

I'm trying to run some javascript from a .NET class library using JSPool and JavaScriptEngineSwitcher.V8, but I can't work out how to install JavaScriptEngineSwitcher.V8. My code so far is simple
public class Renderer : IDisposable
{
private readonly JsPool _pool;
private static readonly string[] _requiredFiles = { "vendors", "app" };
public Renderer(string jsPath)
{
_pool = new JsPool(new JsPoolConfig
{
Initializer = initEngine =>
{
foreach (var file in _requiredFiles)
{
initEngine.ExecuteFile(jsPath + "\\" + file + ".js");
}
}
});
}
public string Render()
{
using (var engine = _pool.GetEngine())
{
return engine.Evaluate<string>(#"myjsFn()");
}
}
public void Dispose()
{
_pool.Dispose();
}
}
But this throws a NullRefException as no engine has been registered
NullReferenceException: Object reference not set to an instance of an object.
JavaScriptEngineSwitcher.Core.JsEngineSwitcher.CreateDefaultJsEngineInstance()
My app is targeting dnx451, and I've specified JSPool 0.4.1 and JavaScriptEngineSwitcher.V8 1.5.8 in my dependencies. I've had a good look but can't seem to find anything that shows any code required to register the V8 engine. Can anyone point me in the right direction?
This problem was solved in the JavaScript Engine Switcher version 2.0.0 and JSPool version 2.0.0. Before installing of NuGet packages, I recommend to first read “How to upgrade applications to version 2.X” section of the documentation.
But worth noting, that the JavaScriptEngineSwitcher.V8 module can be used only in web application created by the “ASP.NET Core Web Application (.NET Framework)” template.

Prompted for EnumerableExtensions.cs using Castle.Facilities.NHibernateFacility

I am being prompted for a file called EnumerableExtensions.cs when using the NHibernateFacility for Castle Windsor. I have replicated this with the following steps (all packages were installed from NuGet):
Create a new WPF project
Install Castle.Core 3.1.0
Install Castle.Windsor 3.1.0
Install Castle.FactorySupportFacility 3.1.0
Install Castle.Transactions 3.2.207.2207
Install Castle.Facilities.AutoTx 3.2.207.2207
Install NHibernate 3.3.1.4000
Install Fluent NHibernate 1.3.0.733
Install Castle.Facilities.NHibernate 0.7.1.23602
Override OnStartup() in App.xaml.cs to create the Windsor container and add the facilities to it. See code below.
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
IWindsorContainer container = new WindsorContainer();
container.AddFacility<AutoTxFacility>();
container.Register(
Component.For<INHibernateInstaller>()
.ImplementedBy<FluentNHibernateInstaller>());
container.AddFacility<NHibernateFacility>();
}
This is the code in FluentNHibernateInstaller.cs
public class FluentNHibernateInstaller : INHibernateInstaller
{
public FluentConfiguration BuildFluent()
{
return Fluently.Configure();
}
private IPersistenceConfigurer SetupDatabase()
{
return MsSqlConfiguration.MsSql2008
.ConnectionString(c => c
.Server("Server")
.Database("Database")
.Username("User")
.Password("Password"));
}
public Maybe<NHibernate.IInterceptor> Interceptor
{
get { return Maybe.None<NHibernate.IInterceptor>(); }
}
public bool IsDefault
{
get { return true; }
}
public void Registered(ISessionFactory factory)
{
}
public string SessionFactoryKey
{
get { return "sf.default"; }
}
}
When I run the application, this is the dialog I am presented with:
To me this looks like something is wrong with the DLL but when I posted about this on the Castle Project Google Group it was suggested that I had incompatible versions of Windsor in my app. Is this true or does it seem like something else is going on?
That dialog is Visual Studio asking for the source code of the file where an exception originated. Click cancel, and Visual Studio will instead stop somewhere in your own code and display the exception.
You can prevent the dialog by removing the pdb-file for the component in which the exception occurs (but that will also lead to less useful stack traces in case you want to report a bug in the affected component).

EntityFramework.Migrations, using DbMigrator in a C# class

I just installed the new EntityFramework.Migrations package. I scaffoled my migrations following this tutorial: http://blogs.msdn.com/b/adonet/archive/2011/09/21/code-first-migrations-alpha-3-no-magic-walkthrough.aspx
Using the Powershell window, everything works fine.
But we need to create a class that will rollback all the migrations for our automated tests.
So I made a simple class that looks like this:
public class CustomMigrator
{
public void DropDatabase()
{
new DbMigrator(new Settings()).Update("0");
}
public void RegenerateDatabase()
{
new DbMigrator(new Settings()).Update();
}
}
Settings is my DbMigrationContext implementation that looks like this:
public class Settings : DbMigrationContext<MyDb>
{
public Settings()
{
AutomaticMigrationsEnabled = false;
SetCodeGenerator<CSharpMigrationCodeGenerator>();
AddSqlGenerator<SqlConnection, SqlServerMigrationSqlGenerator>();
}
}
When I call this:
new CustomMigrator().DropDatabase();
I get a weird exception:
The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
I know that Migrations are still in alpha, but I was wondering if anyone have been able to run the migrations using DbMigrator?
Thanks.
I just found my problem, it is because I was using EntityFrameworkProfiler and there is a bug with the latest EF release that breaks the profiler.
http://blogs.hibernatingrhinos.com/5121/entity-framework-june-2011-ctp-v4-2-is-now-supported-in-entity-framework-profiler
For the moment I did not need the profiler, so I just removed the line of code that was initializing the profiler and now it works.

Categories