Cannot add sqlite db file to Word adding deployment - c#

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.

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.

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.

Remote server claims table doesn't exist

I have a connection string in my config files like so
add name="entities" connectionString="Data Source=localhost;user id=username;password=somepassword;persist security info=True;database=dbname" providerName="MySql.Data.MySqlClient"
This works with localhost.
As soon as I change the Data Source to Data Source=123.34.45.56 <-- some remote server
I get MySql.Data.MySqlClient.MySqlException: Table 'mydb.Emails' doesn't exist
If I use connection code in c# it will work against the remote server : Example below
MySql.Data.MySqlClient.MySqlConnection mySqlConnection = new
MySql.Data.MySqlClient.MySqlConnection();
mySqlConnection.ConnectionString = "Data Source=123.34.45.56;user id=username;password=somepassword;persist security info=True;database=dbname";
string conString = mySqlConnection.ConnectionString;
using (MySqlConnection connection = new MySqlConnection(conString)) {
connection.Open();
using (MySqlCommand command = new MySqlCommand(
"SELECT * FROM emails",
connection)) {
using (MySqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
for (int i = 0; i < reader.FieldCount; i++) {
var tr = reader.GetValue(i);
}
}
}
}
}
How come the connection string in the web.config is throwing this error for every table MySql.Data.MySqlClient.MySqlException: Table 'mydb.Emails'doesn't exist.
The tables are there as the c# connection code can open a connection and query the data just fine.
How do I get the connection string to work?
John Garrard was correct. It was a case sensitivity issue with the database located on two different operating systems. I needed to make my entities case sensitive and the switching the connection string will work between the Windows development machine and the Linux production machine. Thanks.
I came across this issue when moving from a Windows dev to AWS test system. There is a parameter called "lower_case_table_names" that controls how MySql matches table names which defaults to 0 on linux and 1 in Windows (meaning case sensitive and insensitive):
On your AWS Console go to the RDS page.
Click on Parameter Groups.
Either create your own or click into the default parameter group.
Search for the parameter lower_case_table_names.
Edit the value and set it to 1
Save the parameters and restart the db instance.

Create setup file include MySQL database inside it

I developed application form using C# and connected this application with a MySQL database like this
string Coonstring = "datasource=localhost;port=3306;username=root;password=***;Charset=utf8";
string cmd = "select name from project.material ;";
MySqlConnection connectionDatabase = new MySqlConnection(Coonstring);
MySqlCommand cmddata = new MySqlCommand(cmd, connectionDatabase);
MySqlDataReader myreader;
When I try to build this app. and create setup file and get this setup file to another laptop error messagbox appear tell me missing MySQL host.
So what should I do ?
Add an application configuration file. MSDN Link
Add an entry for a connection string - this can now be changed when deployed. MSDN Link
Change your code to use it (as shown below).
Set the connection string appropriately on the deployed system in the *.exe.config file.
string Coonstring = ConfigurationManager
.ConnectionStrings["KeyValueYouSupplied"]
.ConnectionString;

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();

Categories

Resources