Crashing/error on opening SQLite database in UWP/C# - 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.

Related

Cannot add sqlite db file to Word adding deployment

I developed C# Word add-in which populates some data from database file. It is working fine while I am running through Visual studio running. But if I publish it cannot connect to database.
Here is how I get data from database:
SQLiteConnection con = new SQLiteConnection(ThisAddIn.connectionString);
con.Open();
var command = con.CreateCommand();
command.CommandText =
#"
SELECT *
FROM JK
WHERE article_number = $article_number
";
command.Parameters.AddWithValue("$article_number", textFromDoc);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var title = reader.GetString(2);
var article = reader.GetString(3);
ResultForm resultForm = new ResultForm();
resultForm.setArticle(title, article);
resultForm.ShowDialog();
}
}
public static string connectionString = #"Data Source=E:\projects\c#\TBPWordAddin\WordAddIn1\codexes.db";
Am I doing something wrong or do I need to include file in another way? Any help will be appreciated.
Also I tried publishing using Visual studio installer and it connected to database but the add in didnot lounched on other computers.
The connection string contains an absolute path which can be changed after publishing an application. I'd suggest using a relative path instead - in that case you will be able to find the Db easily. You may check out the following threads for more information on such kind of issues:
Connection string with relative path to the database file
How to give relative path of connection string or data source in windows form application
But if I publish it cannot connect to database.
Make sure the Db path (see the connection string) corresponds to the hardcoded value in the application used.

Writing data from C# to a MDF database

I have a C# piece of code which listens for mouse-up events and then the data is to be written to a database. I have a .MDF database file I locally created in Visual Studio within the application. I am using the below code for this.
The thing is when I open the .MDF database file in SQL Server Management Studio after installing the application, I can't see any rows of data. I can see the columns I created but no data. The "Server" in server explorer in Visual Studio shows up to be my laptop number it seems:
private void MouseUpEvent(object sender, KeyEventArgs e)
{
MousePressed = e.KeyCode.ToString();
int Counting = MousePressed.Split('/').Length - 1;
long TimePressed = _MousePressed_Length;
String DateToday = SQLDate;
String TimeToday = SQLTime;
float TimeNow = SQLTimeExactmilliseconds;
var guid = Guid.NewGuid().ToString();
var guid2 = guid + TimeNow;
string sqlCon = #"Data Source=.\SQLEXPRESS;" +
#"AttachDbFilename=|DataDirectory|\Database1.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
using (var db = new SqlConnection(sqlCon))
{
db.Open();
var command = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Date);", db);
command.Parameters.AddWithValue("#Date", DateToday);
var command2 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Time);", db);
command2.Parameters.AddWithValue("#Time", TimeToday);
var command3 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Mousepress);", db);
command3.Parameters.AddWithValue("#Mousepress", TimePressed);
var command5 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#TimeExact);", db);
command5.Parameters.AddWithValue("#TimeExact", TimeNow);
var command6 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Id);", db);
command6.Parameters.AddWithValue("#Id", guid2);
command.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
db.Close();
}
}
When I try to open the .MDF database file in Server Explorer, I get this message from Visual Studio :
Database 'C:\Program Files (x86)\muhammadADIbrahim#outlook.com\Setup_Attention_Assist\Database1.mdf' already exists. Choose a different database name.
An attempt to attach an auto-named database for file C:\Users\muham\OneDrive\Desktop\Attention_Residue\BAAB UL WORK\NIZAM\CURRENT SOFTWARE\NizamSolutionBackup2.6\Nizam.Monitor\Database1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The code compiles and works properly so I am guessing this is something that is just to do with the connection to the database.
What should happen is that the .mdf data gets installed along with the .msi file when the user installs the application locally and the data is written to the database. For any user, I should be able to take the local .mdf file and open it in SQL Server Management Studio and view the results.
Thanks,
Ibrahim
The problem with the mdf database is that you need to install SQLSever.
The problem with mySql is similar. SQLLite didn't seem to work well for me either.
I have ended up creating a .txt file for this which for now seems to be working fine.

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"!

how to set a path to the local directory in c# for .mdf database in Service.cs file

Do you know how to set a path to the local directory in c# when trying to set a path for a datbase in the service.cs file? (I am developing in VS2010)
I have developed a winforms program that uses a .mdf (SQL Server) database. The program communicates to the database through a SQL Server connection string.
I have hard coded the path of the db at the mo but would like to know how to point to the current directory.
I have seen online
AttachDbFilename =|DataDirectory|\Database.mdf
But it doesn't seem to work for me as the connection will not open.
Also I have tried using Environment.CurrentDirectory however that with CurrentDirectory is weirdly not in the namespace.
If the file is in the same assembly folder you can use this
string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["myCS"].ConnectionString = config.ConnectionStrings.ConnectionStrings["myCS"].ConnectionString.Replace("#folder#",folder);
config.Save(ConfigurationSaveMode.Full, true);
Go to solution Explorer >> right click the project>> click properties>> go to setting tab>>Make name: MyConnectionString Type:(connection string) Scoper: Application
and select the DB(Db should be kept in your |DataDirectory| along with your dblog)>> select that DB. >> save it.
Then use this code for connection
SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.MyConnectionString);
You have to give the namespace: using System.Data.SqlServerCe;
hope this will solve.
Accept if this works and close the question
there is a way to get the .mdf and .ldf of a databese, through the code that have worked for me, to do that, open a connection to the database using the connection string, prepare SQL command, with the query
select physical_name from sys.database_files where type = 0
then execute the command, and by the way, type = 0, is for mdf, and type = 1 is for ldf, you can also use this query directly in the SSMS
this is the sample code, keep in mind that you need to get the connection string
string _mdfCommand = "select physical_name from sys.database_files where type = 0";
string _ldfCommand = "select physical_name from sys.database_files where type = 1";
SqlCommand GetSQLData = new SqlCommand();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
GetSQLData.CommandText = _mdfCommand;
GetSQLData.Connection = connection;
string mdf_Path= (string)GetSQLData.ExecuteScalar();
GetSQLData.CommandText = _ldfCommand;
GetSQLData.Connection = connection;
string ldf_Path= (string)GetSQLData.ExecuteScalar();
connection.Close();

SQlite & c#, unable to connect database error

SQLiteConnection conn = new SQLiteConnection("Data Source=/data/bakkal.db3;");
conn.Open();
conn.Close();
I am new at programming so maybe the problem is a very dumb one, sorry for that.
I am trying to connect my project with a database which exists in the directory listed above. But the project gives an error at "conn.Open();" line which is just "unable to connect database". Database has no passwords or etc, it is just a very small database with 2 columns.
I don't think it is going to change anything but my project is a WPF application project, maybe differs.
Thanks for any help
If the database file is located in the same folder as the executable you could try this:
using (var conn = new SQLiteConnection(#"Data Source=|DataDirectory|bakkal.db3"))
{
conn.Open();
}
If it is in a subfolder:
#"|DataDirectory|data\bakkal.db3"
If not use absolute path:
#"c:\somepath\data\bakkal.db3"
Write out the location of the database completely [drive][path][databasefile]
using (SQLiteConnection connection = new SQLiteConnection(#"Data Source=c:\data\bakkal.db3"))
{
connection .Open();
}

Categories

Resources