C# database file directory - c#

I'm using the windows forms aplication with an ms access database. And i would like to know if there is a way to show the directory of the database file (to save data in it)excpet like this:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb";
OleDbConnection empConnection = new OleDbConnection(conString);
string insertStatement = "INSERT INTO zivila "
+ "([naziv],[kalorij],[beljakovin],[oh],[mascob]) "
+ "VALUES (#naziv,#kalorij,#beljakovin,#oh,#mascob)";
or this:
"Data Source=D:\Simonova aktovka na namizju\matura\test5\save.mdb";
couse if i use the first one the aplication undos the changes i've made when i close it(the aplication)
the second one makes me have to change the path everytime i bring the aplication to another computer(cous the direktory is different of coars)
So... is there another way?

Try this:
Data Source=|DataDirectory|\save.mdb

Related

Getting current path in Windows form application not working properly

I'm working on an app linked to a local db and I'd like to get the path of db dynamically. I don't know where exactly users will copy this app, so I'd like to get the path to the db automatically. I wrote the following code, it gets the path, but not exactly. I mean, if I have my app in: C:\Users\ROG\Desktop , it says that there is no db in C:\Users\ROG . So it doesn't get the last location of it. Why is that and how to solve it?
I connect to it as follow:
var connString = (#"Data Source=" +
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName +
#"\Angajati.sdf");
Consider using the following code to determine appllication base directory:
AppDomain.CurrentDomain.BaseDirectory
Full code will look like the following:
var connString = "Data Source=" +
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Angajati.sdf");
try to use the following code
var connString = (#"Data Source=" +
System.IO.Path.Combine(System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location),
"Angajati.sdf"));
Rather than using get current directory I suggest using Application Path. That's because if an OpenFileDialog be used the current directory changes but the applicationPath is the same.
System.Reflection.Assembly.GetExecutingAssembly().Location
I hope it would be helpful.

Copy LocalDB in Winform gives me a 'File being used by another process'

I'm developing a Windows Forms App with VS2012. The data is stored in a SQL Server LocalDB. I'm also using EF6.
At some point I want to zip and send the .mdf file to a server for backup.
The problem is I'm getting the following error 'The process cannot access the file '[filepath]' because it is being used by another process'.
Now I understand that it's my app that is locking the file, but is there any way to unlock it? Or maybe kill the sqlserver client engine?
I'm even considering backing up the localDB File. Is this possible in a winform app?
I can't test it now, but I suggest to execute a standard T-SQL BACKUP command, then take the BAK file, zip it and store/send it.
string backupDB = #"FullPathToYourBackupFile.bak";
string databaseName = "YourDBName"; // This is not the MDF file, but the logical database name
using (var db = new DbContext())
{
var cmd = string.Format("BACKUP DATABASE {0} TO DISK='{1}' WITH FORMAT;",
databaseName, backupDB);
db.Database.ExecuteSqlCommand(cmd, null);
}
Thanks to you all I got this working.
I used Steve's answer but with some modifications.
string backupDB = String.Format(#"{0}\{1}", Constants.Paths.CompressedProjects, Constants.DataBase.FileNameBackup);
string databaseName = Constants.DataBase.LogicalName; // This is not the MDF file, but the logical database name
using (var db = new DBContext())
{
string[] parms = new string[2];
parms[0] = databaseName;
parms[1] = backupDB;
var cmd = "BACKUP DATABASE " + databaseName + " TO DISK='" + backupDB + "' WITH FORMAT;";
db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, cmd, parms);
}
params in ExecuteSqlCommand cannot be null and I had to add a TransactionalBehavior.DoNotEnsureTransaction because I was getting this error
Cannot perform a backup or restore operation within a transaction
Uploading the LocalDB is now working.
Thank you so much for your help.
Hugo MaurĂ­cio
just found out a new solution
System.Data.SqlClient.SqlConnection.ClearAllPools()
I tested it and it works
Hugo

C# Winform Application

I am creating a winform application which connects to a ms-access database. The problem is with my connection string as i can access the database locally but if i run from my usb stick or from any other pc it would give me error. How can i modify my connection string so that i can run my application on other pc without any trouble.
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Aakash\Documents\Visual Studio 2013\Projects\Industrial Foundry\record.accdb";
using (OleDbConnection con = new OleDbConnection(strConnect))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("select * from Industry ", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Perhaps this would be a good start:
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx
Since your title indicates you have a WinForms application, you may also want to consider adding a "Browse" button to locate the database and then using a connection string builder to build your connection.
I hope this can help you.
Create a winform where you can input parameters like "server", "password", etc., etc
After that, update your connection string with the parameters:
Friend Principal As New SqlClient.SqlConnection("data source=" & My.Settings.Server & ";INITIAL CATALOG=" & My.Settings.DB & ";UID=" & My.Settings.User & ";PWD=" & My.Settings.Password & ";workstation id=" & My.Settings.PC & ";packet size=4096")
Your connection string points directly to a path on your C: drive.
There are a number of ways that you could fix it; you could just prompt the user for the file location, and/or store it in a user configurable settings file.
I think simple way for you would be use App.Config file (Application Configuration File), you can add your database key in config file, when app launch you can check if key value is null than you should force user to choose database path, and you can set that database path to your config file. You can read your key value something using..
Code for Read Key
System.Configuration.ConfigurationSettings.AppSettings["DBKey"];
Code for Write Key
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("DBKey", "DBPath");
config.Save(ConfigurationSaveMode.Modified)
Thanks
Suresh

Creating dBase-file sporadically throws exception

I'm having trouble creating dbf-files while exporting shapefile data. Most of the times it works, but sometimes it'll just trow the following error, even though the file doesn't exist yet:
The Microsoft Jet database engine cannot open the file 'C:\Test\258ba2f1-cc05-4a21-a047-ef060c46a3ca\data\tablename.DBF'. It is already opened exclusively by another user, or you need permission to view its data.
The code looks something like this:
using (var dBaseConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + databasePath + ";Extended Properties=dBASE IV;"))
{
var createTableString = "Create Table " + tableName + ".dbf (p_id char(10), answered char(20), mnote char(50), descr char(50), grade char(50))";
var cmd = new OleDbCommand(createTableString, dBaseConnection);
dBaseConnection.Open();
cmd.ExecuteNonQuery();
This only happens when i use Microsoft Jet database engine. Using Visual FoxPro creates an additional column named "_NullFlags" and the dbf-file doesn't work with any GIS-software.
Any ideas?
What you may want to do is to have a "template" table structure always available and never used in production. Then, just copy that template table to whatever your new table name would need to be. Then, you can query and connect and do whatever with that file version. In addition, you can rename the file extension from .DBF to anything, such as YourTable.GISDBF so no other application would even accidentally open it.
However, if that doesn't work for you, you may want to look at another post I answered quite a while back was issues with Jet engine too. In this case, I am using VFP OleDb driver and using ExecScript(). You can write command line statements and then execute them as if it were a program. As far as creating the table, you could always do something like creating a CURSOR, and then copying out to the destination table as "TYPE FOXPLUS" which would put it into an older supported file format which might also be readable by GIS.
string VFPScript = "ExecScript( "
+ "[create cursor C_Tmp ( fld1 i, fld2 c(50), fld3 c(10) )] +chr(13)+chr(10)+ "
+ "[copy to '" + YourFileNameVariable + "' type FoxPlus] ";
// put this script into command object, then execute it...
using (OleDbCommand comm = new OleDbCommand( VFPScript, connection))
{
comm.ExecuteNonQuery();
}

In visual Studio 2012 .SDF file not replacing (committing) my changes to original file

I have a problem with inserting to my SQL CE Database.
I have wrote some code, then when I needed a DB, I have right clicked on projected, added new item, Local Database, after that it offered me to choose a datamodel - I selected 'dataset'.
This has created a DB for me, under Server Explorer on my left, and same .sdf file is seen on my right, in solution explorer.
I start my application, I run an insert query, it gives me output that insert was successful, I see that .sdf file under root/bin/Debug/db.sdf was just modified, I close my application, but my original database located at /root/db.sdf. If I query DB from Server explorer, I see no changes/inserted rows. Here is the code I use:
First I have tried sever Data Source options, all uncommented ones did not work for me.
//String connectString = #"Data Source=" + '"' + #"C:\Users\Alex\Documents\Visual Studio 2012\Projects\my\my\myDB.sdf;" + '"';
//String connectString = "Data Source:=" + '"' + #"C:\Users\Alex\Documents\Visual Studio 2012\Projects\my\my\my.sdf" + '"';
//String connectString = "Data Source:=C:\\Users\\Alex\\Documents\\Visual Studio 2012\\Projects\\my\\my\\my.sdf";
//String connectString =#"Data Source:=C:\Users\Alex\Documents\Visual Studio 2012\Projects\my\my\myDB.sdf";
String connectString = "Data Source=myDB.sdf";
using (SqlCeConnection connection = new SqlCeConnection(connectString))
{
connection.Open();
String query = "Insert into items (id, title) VALUES ('" + ID + "', '" + title + "');
SqlCeCommand cmd = new SqlCeCommand(string.Format(query), connection);
int result = cmd.ExecuteNonQuery();
}
After closing application I do a right click on the items table, and 'show table data' - no inserts. What am I doing wrong?
Visual studio is probably creating a copy of your original solution item into the bin/Debug sub-folder (on every build). The original file is never touched while executing your code and your changes are possibly discarded the next time you build the application.
So depending on your use-case you either have to open the database in bin/Debug for viwewing the data or change your connection string to use the one located in the root of your project/solution.
You have a copy of the database in your bin/debug folder, that contains correct data - enter a full path to the database file in your connection string to avoid confusion

Categories