Visual studio app.config file database path for installed apps - c#

I am using local database in my app and when I generate installation file (By Installer Package), after installing program it gives database path errors.
Eample
an attempt to attach an auto-named database for file....
//OR
The given path format is not supported
I've tried to edit database path in app.config file but it failed every time, By default my code line is like this:
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
And my app installing in C:\Program Files (86)\App_Folder\Setup Please note that future users might install it in custom path so I need a way to get dynamic path of installed app.
My question is How can I get app installed path to replace with this part AttachDbFilename=|DataDirectory|\SampleDatabase.mdf?

You could try to use AppDomain.CurrentDomain.SetData method to change your mdf file path.
Since, I don't know how do you published the winform project.
I recommend that you use Clickonce to publish it.
First, please include your mdf file in your project.
Second, you could try the following code to change the installed path after you published it.
private void Form1_Load(object sender, EventArgs e)
{
if(System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
string path = ApplicationDeployment.CurrentDeployment.DataDirectory; //Get installed path
AppDomain.CurrentDomain.SetData("DataDirectory", path);//set the DataDirectory
}
}
Finally, based on my test, I can get the information from the mdf file after I publised it and installed it in another computer.

In production mode |DataDirectory| refers to 'bin' directory, not 'app_data'. If you placed the .mdf file in the app_data directory, you can change it like this:
|DataDirectory|\SampleDatabase.mdf to |DataDirectory|\app_data\SampleDatabase.mdf
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\app_data\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Update1:
I'm sending some code. I just want to give you an idea. You can change it for your situation.
private void Form1_Load(object sender, EventArgs e)
{
if (!IsExist())
{
CreateDatabase();
CreateTables();
}
}
// Create the Database
private void CreateDatabase()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string ldfFile = "TestDatabase_Log.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
string ldfFullPath = System.IO.Path.Combine(basePath, "Data", ldfFile);
SqlConnection myConn = new SqlConnection("Server=.;Data Source=(LocalDB)\\MSSQLLocalDB;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE TestDatabase ON PRIMARY " +
"(NAME = TestDatabase, " +
$"FILENAME = '{mdfFullPath}', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
"LOG ON (NAME = MyDatabase_Log, " +
$"FILENAME = '{ldfFullPath}', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Create the tables and other stuff that you want
private void CreateTables()
{
string conStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\TestDatabase.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection myConn = new SqlConnection(conStr);
string str = #"CREATE TABLE [dbo].[TestTable]
(
[Id] INT NOT NULL PRIMARY KEY,
[Test] NVARCHAR(50) NULL
)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Check if there is the database
private bool IsExist()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
return System.IO.File.Exists(mdfFullPath);
}

Related

Backup SQL Server 2014 DB in c# not work

I create a program to backup the whole DB from SQL server 2014 , i used the code before it was work perfectly on another laptop (was working on it coding with c#).
now i'm trying to backup not work at all this is the code:
1/- SqlConnection:
SqlConnection con = new SqlConnection(WindowsFormsApplication11.Properties.Settings.Default.database1ConnectionString);
2/- textbtn1
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.SelectedPath;
BackupButton.Enabled = true;
}
}
3/- textbtn2 code :
private void BackupButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
try
{
if(textBox1.Text==string.Empty)
{
MessageBox.Show("please enter backup file location");
}
else
{
string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + textBox1.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using(SqlCommand command = new SqlCommand(cmd,con))
{
if(con.State!=ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("database backup done successefully");
BackupButton.Enabled = false;
}
}
}
catch
{
}
}
** even this code not work and no message show up :p , don't know why ?
i changed every thing , i created a new class called DBconnect :
class DBconnect
{
public SqlConnection myConn = new SqlConnection(#"Data Source=MYSERVERNAME;Initial Catalog=MYDBNAME;User ID=sa;Password=12345");
public void backup(string name_path)
{
try
{
string query = "Backup Database MYDBNAMEto Disk ='" + name_path + ".bak'";
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = query;
myCommand.Connection = myConn;
myCommand.ExecuteNonQuery();
MessageBox.Show("sauvegarde succès", "sauvegarde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
}
in my form i did this :
DBconnect conn = new DBconnect();
in backup textbtn2 i did this :
string Namefile = textboxBATH.Text + "\\MYDBNAME" + " " + DateTime.Now.ToShortDateString().Replace('/', '-') + "-" + DateTime.Now.ToLongTimeString().Replace(':', '-');
Conn.backup(Namefile);
in this case i faces this erorr message :
Cannot open backup device. Operating system error 5(Access is denied.) BACKUP DATABASE is terminating abnormally.
i thought SQL service might not have permission to the Path where backup bath is supposed to be created . and i create new folder in my Desktop and gave it the permission Read+Write .. and this not work too .. :p
thank you all .

file upload error, "not found on selected data source"

I've written the following code and when it was simply uploading the file to the folder everything was fine. I've changed it to insert the file name and file path into a database and I'm getting an error:
A field or property with the name 'DataUpload' was not found on the selected data source
DataUpload is the folder name and worked fine before. I'm probably missing something simple but I'm not seeing it.
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
try
{
FileUpload1.SaveAs(Server.MapPath("DataUpload\\" + FileUpload1.FileName));
Guid newGUID = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string InsertUser = "INSERT INTO UserUpload (ID, Comment, FilePath, FileName) VALUES (#ID, #Comment, #FilePath, #FileName)";
SqlCommand com = new SqlCommand(InsertUser, conn);
com.Parameters.AddWithValue("#ID", newGUID.ToString());
com.Parameters.AddWithValue("#Comment", TextBoxComment.Text);
com.Parameters.AddWithValue("#FilePath", "DataUpload/" + FileName);
com.Parameters.AddWithValue("#FileName", FileName);
com.ExecuteNonQuery();
LabelMessage.Text = ("Your Upload Is Complete");
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Add single quotes to the string you are creating for the FilePath, like:string.Format("'DataUpload/{0}'", FileName);

The Microsoft Jet database engine could not find the object

Here users browse to the Excel file from there system and then data is uploaded to sql database table.
I get this Error in Following Code : The Microsoft Jet database engine could not find the object 'C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Student Registration1.xls'. Make sure the object exists and that you spell its name and the path name correctly.
I have no idea why it is asking for this Path ? C:\Program
Files\Microsoft Visual Studio 9.0\Common7\IDE\
protected void import_xls_Click(object sender, EventArgs e)
{
try
{
if (xmlupload.HasFile)
{
string path = xmlupload.PostedFile.FileName;
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet2$]", excelConnection);
OleDbDataReader dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlConnectionstring.mainConnectionString, SqlBulkCopyOptions.KeepIdentity);
sqlBulk.DestinationTableName = "dbo.studentA";
sqlBulk.ColumnMappings.Add("UserName", "UserName");
sqlBulk.ColumnMappings.Add("Password", "Password");
sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.ColumnMappings.Add("Standard", "Standard");
sqlBulk.ColumnMappings.Add("Division", "Division");
sqlBulk.ColumnMappings.Add("SchoolName", "SchoolName");
sqlBulk.ColumnMappings.Add("Language", "Language");
sqlBulk.ColumnMappings.Add("ExamStatus", "ExamStatus");
sqlBulk.ColumnMappings.Add("Result", "Result");
sqlBulk.WriteToServer(dReader);
lblmsg.Visible = true;
lblmsg.Text = "Your data uploaded successfully";
excelConnection.Close();
}
}
catch (Exception ex)
{
lblmsg.Visible = true;
lblmsg.Text = ex.Message.ToString();
}
SqlConnectionstring.cs :
public class SqlConnectionstring
{
public SqlConnectionstring()
{
//
// TODO: Add constructor logic here
//
}
public static readonly string mainConnectionString = ConfigurationManager.ConnectionStrings["constring"].ToString();
}
I will try to save the file in a working directory and then try to open from there.
If the fileName has no path then the connection could find the file only if it is in the
current directory (Usually where your program start)
string savePath = #"c:\temp\uploads";
if (xmlupload.HasFile)
{
string fileName = xmlupload.FileName;
savePath = Path.Combine(savePath, fileName);
xmlupload.SaveAs(savePath);
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
savePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
....
On a web server, to avoid permission problems, it is better to keep the file in a subfolder of the root folder of your site.
In this case the folder could be fully qualified using the HttpServerUtility.MapMath method.

Set database backup file on local machine

POSSIBLE DUPLICATE OF :
How to create SQL Server 2008 database full backup programmatically in desired folder
I have a database on my computer (SQL Server 2008 Express).
I need any sample code in C# that I can use to backup the database to a file using Visual Studio 2010.
Thanks..
i'll using this code to connect Database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Just execute SQL Server command
BACKUP DATABASE database_name TO DISK='d:\path\to\backup\file\on\the\server.bak'
from your program
EDIT
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;
Integrated Security=True; User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
SqlCommand command;
command = new SqlCommand(#"backup database SMS_DB.mdf to disk ='" + path + "\\" + name, con);
command.ExecuteNonQuery();
MessageBox.Show("Backup Created.");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Try this peice of code.
Im using flowing code to connect database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
can i use your SQL Command to set backup using upon type connection
This what I did and it Worked!
private void BackupButtonClick(object sender, RoutedEventArgs e)
{
// FILE NAME WITH DATE DISTICNTION
string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
try
{
// YOUR SEREVER OR MACHINE NAME
Server dbServer = new Server (new ServerConnection("DESKTOP"));
Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
{
Action = BackupActionType.Database,
Database = "School"
};
dbBackup.Devices.AddDevice(#backupDirectory() +"\\"+ fileName, DeviceType.File);
dbBackup.Initialize = true;
dbBackup.SqlBackupAsync(dbServer);
MessageBox.Show("Backup", "Backup Completed!");
}
catch(Exception err)
{
System.Windows.MessageBox.Show(err.ToString());
}
}
// THE DIRECTOTRY YOU WANT TO SAVE IN
public string backupDirectory()
{
using (var dialog = new FolderBrowserDialog())
{
var result = dialog.ShowDialog();
return dialog.SelectedPath;
}
}

Create database file (.sdf) if doesn't exists?

Just wondering about some practice about this;
I have made a simple visual C# program with local database (SQL CE) (dB.sdf file).
Let's say user deletes the dB.sdf file and try to open the exe program - nothing happens (the exe file starts but closes again).
What's the typically practice here? Is it that the program just won't start or is it to make the program create a database file if it doesn't exists?
If it is the latter, how is it done?
The second approach is more wise as your program is uselsess if it depends on database which gets deleted.
string connStr = "Data Source = DBName.sdf; Password = DBPassword";
if (!File.Exists("DBName.sdf")){
try {
SqlCeEngine engine = new SqlCeEngine(connStr);
engine.CreateDatabase();
SqlCeConnection conn = new SqlCeConnection(connStr);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE TableName(Col1 int, Col2 varchar(20))";
cmd.ExecuteNonQuery();
}
catch (SQLException ex){
// Log the exception
}
finally {
conn.Close();
}
}
string fileName = txtEditFolderPath.Text + "\\" + txtEditDatabaseName.Text + ".sdf";
if (File.Exists(fileName))
{
MessageBox.Show("Database with this name already existed at this location !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
string connectionString;
string password = "123";
connectionString = string.Format(
"DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine en = new SqlCeEngine(connectionString);
en.CreateDatabase();
}

Categories