Usage of NPoco in .net Core - asp.net-core

I have recently started diving into the new .net core along with asp.net core mvc. There have been several issues that I have come across but have been able to get most of them answered on my own. The one that has really stumped me is the use of NPoco.
How are you supposed to create the database instance?
The documentation reads:
IDatabase db = new Database("connStringName");
List<User> users = db.Fetch<User>("select userId, email from users");
This is not correct for DNXCORE50 as this constructor has been excluded for DNCORE50
I have also attempted this:
IDatabase _db = new Database(new SqlConnection(ConnStr));
_db.Single<string>("SELECT Username FROM dbo.Member");
When this code is ran I get a 'NullReferenceException'
Does anyone know how to get NPoco working properly?

There are other people having the same issue. This has been reported as issue #293 on NPoco GitHub repository.
The current workaround for this problem is to list the DbProviderFactory as shown below.
IDatabase _db = new Database(new SqlConnection(ConnStr),
DatabaseType.SqlServer2012, SqlClientFactory.Instance);
_db.Single<string>("SELECT Username FROM dbo.Member")

Related

How to login in the database of entity framework context

I'm trying to connect to my context in my VS solution with EF Core
But when I test the connection I get this error
Because it is trying to connect with my domain user instead the user in the connection string
Any idea, please?
Thanks
i cant post pictures in reply so i am using it as answer
i will doublecheck lower versions (i guess 5) - since i dont know which version are you using (but image of EF connection is different than mine (!))
in linqpad 7 it works
in addition, if you need a context you can write using regular connection
using(TypedDataContext context = new TypedDataContext(Connection.ConnectionString)){
context.TABLE.Where(w=>w.ID == 64463).Dump();
}

Integrate PetaPoco v6 with asp.NET core

I am trying to use petapoco with my .NET core MVC application,
I have installed petapoco compiled as stated in another answer but don't know what to do next,
I searched many places but most of them had been using the previous versions of petapoco and not the latest one,
Can someone please help and provide some resources link as to how am I supposed to connect it with my SQL server using a connection string, and since now their documentation suggested to use PetaPoco.DBEntityGenerator instead of T4 templates, I have no idea how to use it.
Start by reading the Quick start guide
To connect to your db, you can start with the samples given:
// Normal
var db = new PetaPoco.Database("connectionStringName");
// Or the fluent configuration (PostgreSQL as an example)
var db = DatabaseConfiguration.Build()
.UsingConnectionString("Host=127.0.0.1;Username=petapoco;Password=petapoco;Database=petapoco;Port=5001")
.UsingProvider<PostgreSQLDatabaseProvider>()
.UsingDefaultMapper<ConventionMapper>(m =>
{
m.InflectTableName = (inflector, s) => inflector.Pluralise(inflector.Underscore(s));
m.InflectColumnName = (inflector, s) => inflector.Underscore(s);
})
.Create();
V6 only change the package and dropped support for some thing like T4, but you don't need the templates to start. The rest it's the same as V5

System.Data.SQLite.Core Cannot use "Password" connection string property

I am writing a .NET Core 3.1 application that depends on another library (Serilog.Sinks.SQLite) which is attempting to store log data to an SQLite database. Unfortunately, Serilog.Sinks.SQLite does not support passing in a password to System.Data.SQLite via the SQLiteConnectionStringBuilder.Password property (which you provide to the SQLiteConnection constructor) and I would really like that functionality.
The code that Serilog.Sinks.SQLite uses to connect to the database is as follows:
private SQLiteConnection GetSqLiteConnection()
{
var sqlConString = new SQLiteConnectionStringBuilder
{
DataSource = _databasePath,
JournalMode = SQLiteJournalModeEnum.Memory,
SyncMode = SynchronizationModes.Normal,
CacheSize = 500,
PageSize = (int)MaxSupportedPageSize,
MaxPageCount = (int)(_maxDatabaseSize * BytesPerMb / MaxSupportedPageSize)
}.ConnectionString;
var sqLiteConnection = new SQLiteConnection(sqlConString);
sqLiteConnection.Open();
return sqLiteConnection;
}
There are a number of similar posts on StackOverflow about encryption with SQLite stating very convincingly that encryption / password protection of the database is indeed supported by System.Data.SQLite. However, that is not matching my experience.
I grabbed a copy of the Serilog.Sinks.SQLite source in an attempt to prototype a modification to it to support specifying the password. This seems like it should be easy enough to accomplish with the following addition to the above code (specifying the Password property in the connection string):
MaxPageCount = (int)(_maxDatabaseSize * BytesPerMb / MaxSupportedPageSize),
Password = "mypasswordhere"
}.ConnectionString;
Unfortunately, this does not work and results in an exception being thrown on startup with the following message:
Exception has occurred: CLR/System.Data.SQLite.SQLiteException An
unhandled exception of type 'System.Data.SQLite.SQLiteException'
occurred in LoggingWebApi.dll: 'SQL logic error Cannot use "Password"
connection string property: library was not built with encryption
support, please see "https://www.sqlite.org/see" for more information'
What is confusing me the most here are the number of other posts I've found claiming that System.Data.SQLite supports this password and the fact that a .NET Framework 4.6 application from another team in my company is using System.Data.SQLite.dll (though an older version 1.0.111.0) and this Password behavior works fine for them.
My code is targeting netcoreap3.1 and my dependency of Serilog.Sinks.SQLite is targeting netstandard2.0 so that is one obvious difference I see. In my modified version of the Serilog.Sinks.SQLite code, I am referencing System.Data.SQLite.Core as follows (added via otnet add package System.Data.SQLite.Core --version 1.0.113.1):
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.113.1" />
Is there something with .NET Core 3.1 or .NET Standard 2.0 that causes System.Data.SQLite.Core to not support the Password connection string property like everyone else seems to think it supports?
I thought maybe my issue was running on Linux so I tried running on my Windows but it produced the same error.
I did find another post referencing a potentially helpful approach but this sample is not using System.Data.SQLite.Core and instead is using SQLitePCLRaw.bundle_e_sqlcipher and I would prefer to avoid rewriting all of the Serilog.Sinks.SQLite code to use a different SQLite client: https://github.com/paragpkulkarni/SQLiteEncryptionUsingEFCore
It seems that System.Data.SQLite has dropped support for encryption as of version 1.0.113.1 which explains why I haven't been able to get it working:
https://system.data.sqlite.org/index.html/tktview?name=9c330a3e03
This is also mentioned on their News page though it was not clear to me that the Password support was part of the "legacy CryptoAPI Codec":
https://system.data.sqlite.org/index.html/doc/trunk/www/news.wiki
The other team I referred to is using an older version 1.0.111.0 so if you require this support, I guess just don't upgrade...

EF Core Migration error: "Unable to create an object of type 'ApplicationContext'"

I'm trying to do the migration with EF Core but I get an error - how can I fix this error?
PM> add-migration ini
Unable to create an object of type 'ApplicationContext'. Add an
implementation of 'IDesignTimeDbContextFactory' to
the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
additional patterns supported at design time.
This will also happen if you have multiple start-up projects - when migrating, just select one (in VS right click Solution and Set StartUp Projects...)
I had the same issue with asp.net core 3.1.
For me, it was pretty straight forward, adding an implementation of IDesignTimeDbContextFactory to the main web project fixed the issue.
A basic implementation looks something like this:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
public YourDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<YourDbContext >();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new YourDbContext(builder.Options);
}
}
Please refer to this blog post on the subject.
It is highly probably because of your default startup project:
Open Package manager console and write this command:
PM> Add-Migration -StartupProject[YourProjectPath(just press a tab all the.csproj paths will come up, and then choose your DataBaseLayer project to execute a migration for)] migrationName
In this way you don't need to again go to solution and set startup
project with your webProject whenever you finished adding a new migration.
1.Modify your code in ConfigureService with :
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
x => x.MigrationsAssembly("WebApplication")));
In command line which includes WebApplication.csproj:
dotnet ef migrations add Init
I got this error when creating a migration. In my code in the ApplicationContext constructor, I used the Database.EnsureCreated() method. Typically this method is used for small applications where you need to check for the existence of a database and create it once. When creating an application with a database that will change with new versions and using migrations, you should not use this method.
In my case, this error existed because I was applying migrations at runtime. After removing Database.Migrate(); in my code, I was able to add the new migration without errors.
By the way, I used EF Core .NET command-line interface (CLI) tools, not the Package Manager Console (I run into problems I couldn't solve when I was using the Package Manager Console, so I went for the CLI alternative, and it was worth the change).
Also, make sure you use the appropriate options to select your startup project and your target project.
I got this error when the Primary Key for the table was not set manually (with attributes or with FluentAPI) and was not determined automatically (not "Id" kayword and not "TableName" + "Id")
Stack: ASP.NET Core EF + Postgres (Npgsql)

Conversion of V2 Ninject Binding to V3

I've been banging my head at this for about 8 hours now, and I just can't seem to find a simple explanation on how to change my custom bootstrapper for ninject (Last worked on the code back in v2.x.x.x) to the new v3.0.0.0 syntax.
I currently have the following:
public class NinjectCustomBootStrapper : NinjectNancyBootstrapper
{
protected override Ninject.IKernel GetApplicationContainer()
{
return Program.MyContainer;
}
}
in a septate class, and :
public static IKernel MyContainer
{
get { return _myContainer ?? (_myContainer = CreateKernel()); }
set { _myContainer = value; }
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<CardMonitorService>().ToSelf().InSingletonScope();
return kernel;
}
in my main program 'Program.c' in a command line app.
Iv'e since updated ninject to V3.0.0.0 only to find that there's been some breaking changes. I'll admit I don't use ninject very often (I usually use structuremap), and the only reason this project does is I didn't write it originally.
Since I've upgraded Ninject, now when the app is started up I get the following exception:
Method not found: 'Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax`1<!0>
Ninject.Syntax.IBindingToSyntax`1.ToConstant(!0)'.
After a ton of searching and researching, the closest I've been able to find is this:
http://sharpfellows.com/post/Ninject-Auto-registration-is-changing-in-version-3.aspx
Which while it points me in the right direction, still isn't quite a solution as I'm not using a custom binding generator.
So my question is this.
How do I rewrite the above so that my project once again works and the WCF service when called gets the correct singleton binding handed to it when a request comes in. Going back to ninject 2 is not an option, as other dependencies in the project that have been added have forced the v3 upgrade and these add new functionality that's been requested hence why I'm working on it.
For reference this is a .NET4 build, running on NancyFX with a self hosting WCF setup as a windows service using Topshelf to provide the SCM interface.
Cheers
Shawty
Addendum to clear things up a little
This is an existing project that was originally written sometime back, I've been asked to add some new features to the project.
As part of adding these new features I have been required to upgrade the version of Ninject being used from an earlier version to V3.0.0.0 as newer dependencies added to the project require the newer version of Ninject.
Under the previous V2 of Ninject the code I have given above worked fine, with no issues, since the project has had Ninject V3 added I now get the exception as described above.
I cannot go back to the earlier version of Ninject as that will mean not being able to add the new functionality that I'm adding.
From the research I've done so far the sharpfellows link above is the closest explanation of my issue that I've managed to find so far on the internet.
I don't use Ninject very often, so I've not got the background to know what's changed between V2 & V3 that (based on my research) is the cause of my issue.
I need to know how to change my code written under V2 (and shown above) so that it works under V3.
MissingMethodException is usually a deployment problem. You compile against a different assembly than you deploy. Check that you deployed the same version and same build.
So after a week or so it turns out that the problem was that the Nancy dev team broke binary comparability with the latest version of ninject (or vice versa) :-)
There is a GitHub pull request to fix this available at :
https://github.com/NancyFx/Nancy.Bootstrappers.Ninject/pull/6
However the next version 'Nancy.Bootstrapper.Ninject' 0.12 will be out on NuGet soon which will have the fix implemented.