BadImageFormatException with SQLite in ASP.NET razor website - c#

I'm trying to create a very simple webshop in Razor with SQLite. Unfortunately, when i trying to create the database (or creating the SQLiteConnection object) it throws a strange System.BadImageFormatException.
An attempt was made to load a program with an incorrect format.
(Exception from HRESULT: 0x8007000B)"} System.BadImageFormatException
My code looks similar as the following:
public bool CreateDatabase()
{
try
{
string db = HttpContext.Current.Server.MapPath("~/App_Data/mydb.sqlite");
SQLiteConnection.CreateFile(db);
SQLiteConnection m_dbConnection = new SQLiteConnection(#"Data Source="+ db + ";Version=3;");
m_dbConnection.Open();
string sql = "create TABLE cart (UserHash varchar(35), imageid varchar(255), rider varchar(255), competition varchar(255), usagetype varchar(255), retouch varchar(10), blacknwhite varchar(10))";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
return true;
}
catch (Exception)
{
return false;
}
}
This website probably will run on third-party hosting, so it's essential to use a relative path for the sqlite file location, although i couldn't get it work so far.
In db variable, i get the correct App_Data folder location.
I get the exception at new SQLiteConnection. I also tried using the following connectionstring, no luck:
"Data Source=|DataDirectory|mydb.sqlite; Version=3;"
What am i missing?

BadImageFormatException happens when your application and your libraries use a different bitness. For example, the application is built for AnyCPU (without prefer 32bit) or x64 and your libraries are compiled for 32bit or viceversa.
Usually the solution is very simple. Just copy the appropriate version of SQLite for the bitness of your app to your run folder or change the Target Platform of your app to match the library version used

Related

Crashing/error on opening SQLite database in UWP/C#

I'm trying to add code to an old UWP app to access an SQLite database. It works fine when debugging in VisualStudio but when I package it for sideloading it breaks.
I've shrunk it down and tried to simplify the code to see if there's any issues. Below is a small bit of code I'd put in to test out what is going on. The code breaks on opening the database. Again, this works fine when debugging in Visual Studio and breaks when sideloaded.
string entry = "";
string dbpath = #"S:\TestDB.db");
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
string textCommand = "SELECT Source from Materials WHERE Material = #keyValue";
SqliteCommand selectCommand = new SqliteCommand(textCommand, db);
selectCommand.Parameters.AddWithValue("#keyValue", "PMMA");
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read()) { entry = query.GetString(0); }
db.Close();
}
return entry;
Does anyone have anything I can try out?
Crashing/error on opening SQLite database in UWP/C#,'Unable to open database file' Is there a way I can get more info out of it.
I'm afraid you can't access db file where in the S disk with path directly. In UWP it only has permission access local folder with path. So we suggest you place your db file into LocalFolder like this document.
string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
using (SqliteConnection db =
new SqliteConnection($"Filename={dbpath}"))
I found someone else who had a similar problem while searching for the answer to my question. I messaged them and they told me to put:
<rescap:Capability Name="developmentModeNetwork" />
in my manifest.
Seemed to do the trick.

Backup localDB database in ClickOnce

I've created a WPF 4.5 .NET application it with a database backup feature. The functions and the backup works fine when debugging but when I publish it in ClickOnce and install it in target machine everything works except the backup won't work because ClickOnce obfuscate the app folder location so it becomes too long for the backup statement to work! Is there a way to make the backup statement shorter? here's my code and the error I get:
code:
SaveFileDialog sfd = new SaveFileDialog();
string stringCon = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\whdb.mdf;Integrated Security=True";
string dbPath = Application.StartupPath + #"\whdb.mdf";
if (sfd.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(stringCon))
{
string backupStmt = string.Format(#"backup database #whdb to disk='{0}' WITH INIT ", sfd.FileName);
using (SqlCommand sqlComm = new SqlCommand(backupStmt, conn))
{
sqlComm.Parameters.AddWithValue("#whdb", dbPath);
conn.Open();
sqlComm.ExecuteNonQuery();
conn.Close();
}
}
)
************** Exception Text **************
System.Data.SqlClient.SqlException (0x80131904): Invalid database name 'C:\Users\Abubaker\AppData\Local\Apps\2.0\52WR4JTO.12O\D6M4D7OQ.Z3D\sa3a..tion_fef19ab42c2b8f22_0001.0000_9fc10c82bbf23ed2\whdb.mdf' specified for backup or restore operation.
BACKUP DATABASE is terminating abnormally.
The whdb.mdf database file is create by another existing application? And your WPF application is only for Backup the existing whdb.mdf database?
I also struggled for days for this kind of situation. I tried |Data Directory| and Application.StartupPath and some other approaches as you've found as well.
However, I finally chose this way and successfully launched(published) my service.
According to my experience, |Data Directory| indicates different places depending on circumstances, in other word, it's not always same..
And I could read (SQL Select command) database with |Data Directory| setting in connectionString but couldn't insert or update the database. You can find some people are having this difficulties by searching on interent. I think when we set |Data Directory| in connectionString, the database plays a role as read-only data file like the nuance of |Data Directory|.
Instead the |Data Directory|, I chose more obvious path which indicates always same place(directory).
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Environment.GetEnvironmentVariable("APPDATA") + #"\whdb.mdf;Integrated Security=True";
Above Environmental variable indicates always C:\Users\Abubaker\AppData\Roaming directory.
For this scenario, you're needed to create the whdb.mdf database file with above path first.
And further, you may create your own additional directory like mybackup with the connectionString as,
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Environment.GetEnvironmentVariable("APPDATA") + #"\mybackup" + #"\whdb.mdf;Integrated Security=True";
I couldn't find the official document from Microsoft how the |Data Directory| works but failed. Understanding |Data Directory| would be your key, otherwise, there's alternative way like my case.
My case is also WPF, ClickOnce, SQL Database (it was localDB but I changed to normal SQL Database because of remote networking)
Solved the problem by adding Initial catalog=whdb in the connection string and then replace the full path Application.StartupPath + #"\whdb.mdf" with just the database name "whdb"!

Saving data in a Database C# WPF [duplicate]

I have following C# code in a console application.
Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "FlowerShop.sdf";
string fileLocation = "|DataDirectory|\\";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.Connect(fileName, fileLocation);
Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
string res = dbAccess.ExecuteQuery(query);
Console.WriteLine(res);
string query2 = "Select * from Products";
string res2 = dbAccess.QueryData(query2);
Console.WriteLine(res2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
class DatabaseAccess
{
private SqlCeConnection _connection;
public void Connect(string fileName, string fileLocation)
{
Connect(#"Data Source=" + fileLocation + fileName);
}
public void Connect(string connectionString)
{
_connection = new SqlCeConnection(connectionString);
}
public string QueryData(string query)
{
_connection.Open();
using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
using (DataSet ds = new DataSet("Data Set"))
{
da.Fill(ds);
_connection.Close();
return ds.Tables[0].ToReadableString(); // a extension method I created
}
}
public string ExecuteQuery(string query)
{
_connection.Open();
using (SqlCeCommand c = new SqlCeCommand(query, _connection))
{
int r = c.ExecuteNonQuery();
_connection.Close();
return r.ToString();
}
}
}
EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.
It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.
But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.
Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.
Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.
You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.
EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.
Committing changes / saving changes across debug sessions is a familiar topic in SQL CE forums. It is something that trips up quite a few people. I'll post links to source articles below, but I wanted to paste the answer that seems to get the best results to the most people:
You have several options to change this behavior. If your sdf file is part of the content of your project, this will affect how data is persisted. Remember that when you debug, all output of your project (including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
Answer Source
Here is a link to some further discussion and how to documentation.

Create new SQLite database on WinRT?

I want to create a new database from C# code in my WinRT app. I searched the Web and the way to do that appears to be the SQLiteConnection.CreateFile() method. However, that method does not exist in the SQLite namespace, at least in the WinRT version. I installed SQLite using the NuGet packge name "sqlite-net" and included the sqlite3.dll into my project. I do see properly methods like CreateTable(), Query(), etc. but not CreateFile(). Where is it? Or does the WinRT package use a different method for creating database files from code?
var db = new SQLiteConnection(databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite);
is how I did it.
One of the times where Microsoft provides a straightforward example:
https://learn.microsoft.com/en-us/windows/uwp/data-access/sqlite-databases
await ApplicationData.Current.LocalFolder.CreateFileAsync("sqliteSample.db", CreationCollisionOption.OpenIfExists);
string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
using (SqliteConnection db =
new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
String tableCommand = "CREATE TABLE IF NOT " +
"EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " +
"Text_Entry NVARCHAR(2048) NULL)";
SqliteCommand createTable = new SqliteCommand(tableCommand, db);
createTable.ExecuteReader();
Because depending on how you add sqlite to a UWP project, not having createfile() available is still an issue in 2021.

System.Data.Sqlite problems

I'm having a problem getting Sqlite to work in my c# irc bot.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.IO;
namespace ModBot
{
class Database
{
private SQLiteConnection myDB;
private SQLiteCommand cmd;
public Database()
{
InitializeDB();
}
private void InitializeDB()
{
if (File.Exists("ModBot.db"))
{
Console.WriteLine("HEYOOOOOOO");
myDB = new SQLiteConnection("Data Source=ModBot.db;Version=3;");
String sql = "CREATE TABLE IF NOT EXISTS twitch (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, btag TEXT DEFAULT null);";
cmd = new SQLiteCommand(sql, myDB);
cmd.ExecuteNonQuery();
}
else
{
Console.WriteLine("YOOHOOOOO");
SQLiteConnection.CreateFile("ModBot.db");
myDB = new SQLiteConnection("Data Source=ModBot.db;Version=3;");
String sql = "CREATE TABLE IF NOT EXISTS twitch (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, btag TEXT DEFAULT null);";
cmd = new SQLiteCommand(sql, myDB);
cmd.ExecuteNonQuery();
}
}
}
}
I downloaded System.Data.Sqlite, and added it as a resource to my project. When I run the code, it throws a DllNotFound exception (Specifically: Unable to load DLL 'SQLite.Interop.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)) when it tries to make the actual connection.
Any ideas?
Installing the RTM version of the Visual C++ runtime libraries works perfectly with System.Data.SQLite 1.0.74. So the SP1 version is not needed.
The version of the C runtime installed with the .NET 4 runtime is the RTM version of msvcr100, but has the name msvcr100_clr0400.dll. With a copy of this renamed to msvcr100.dll, either in System32 or next to the System.Data.SQLite.dll, everything seems to work.
It seems they've moved away from SxS deployment of the C runtime. So no more 'dependency' tag in the embedded manifest, and whatever the latest version is in System32 (or same directory as the .exe) will be loaded.
Some buddy asked a question on StackOverflow about these changes: Visual C++ 2010: Changes to MSVC runtime deployment (no more SxS with manifest).
This all means for the .NET 4 version you can deploy System.Data.SQLite.dll and msvcr100.dll in the same directory, which was not possible with the previous version of the runtime. For me that sorts out all my problems and you can move to the current versions of System.Data.SQLite.dll.

Categories

Resources