Database backup error - c#

I have this code snippet that creates backup of db:
try
{
string connStr = "<valid connection string>";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
string sqlStmt = String.Format("BACKUP DATABASE InventoryDB TO DISK='{0}'",
DBBackupSaveFileDialog.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
bu2.ExecuteNonQuery();
}
...
problem is that it works fine on developer pc but when i try on different machine it will give this error
Cannot open backup device 'C:\User\Saleh\Documents\12.bak'. Operating system error 5 (failed to rerieve text for this error. Reason: 15105).

You need to make sure the SQL Server service account has write access to C:\Users\Saleh\
First, see what account SQL Server is running as. Control Panel > Administrative Tools > Services, right-click the relevant SQL Server service, hit Properties, and see the account listed on the Log On tab. Now go to Windows Explorer, right-click the folder, hit Properties, and on the Security tab, you can add this user account to the list, and make sure they have write access. If you have further problems with this, your question should probably to to superuser.com as it's becoming a Windows / permissions problem, not a programming one.
Better yet, stop running backups to user folders - use SQL Server's backup folder, which SQL Server already has permissions to write to. If you need to move it later, do that separately.

Related

c# SQL) unable to open physical file(MS localdb .mdf) after attaching the .mdf file which was created in another computer(server)

I'm developing Windows Desktop appication(C# WPF) with Microsoft localdb(.mdf) and I want that users of my software can carry their localdb (.mdf) file when they move to other places(computers). The localdb (.mdf) file is created on the first computer.
To test my application, I copied my localdb file from computer A to computer B and attached with below code successfully.
string attach_greendbnameQuery = string.Format(#"EXEC sp_attach_db #dbname = N'greendb_{0}', #filename1 = N'{1}\greendb_{0}.mdf'", textBoxGreenLogin.Text, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString());
SqlCommand attach_greendbnamecomm = new SqlCommand(attach_greendbnameQuery, check_datadbinmasterConn);
attach_greendbnamecomm.ExecuteNonQuery();
And I could read and write data into the moved localdb file.
However, when I run backup command on this database, exception occurs like,
'Unable to open physical file, Operating system error 32, process cannot open the file because the file is in use by another process'
If I enter Server Management Studio- Security-KayLee-PC\KayLee- User Mapping,
the users of all other localdb are 'dbo' but only the user of manually moved database is KayLee-PC\KayLee and only 'public' is checked and all other database roles are not checked including db_owner. (I always start(login) Windows(O/S) with KayLee-PC\Kaylee account)
I tried to make all roles checked to database roles even to server roles but failed.
Even, I tried to drop the user KayLee-PC\KayLee through below code but the exception message show as,
'User 'KayLee-PC\KayLee' does not exist in current database'
If I click the database in Server Management Studio, the current database status is not changed to clicked database and subtree nodes(like Table, Security and so on) are not displayed with message 'cannot access to the database' eventhough if I click other databases, the current database status is changed to clicked database.
Also, I tried to change the owner of the localdb(database) through below code but it seems the execution failed with result '-1' with 'sa' and when trying with 'KayLee-PC\KayLee' which I always login to Windows O/S, error message is like 'KayLee-PC\KayLee is already an owner(exist) of this database'
SqlConnection dbownerchange_Conn = new SqlConnection();
dbownerchange_Conn.ConnectionString = dbownerchange_ConnectionString;
dbownerchange_Conn.Open();
SqlCommand dbownerchange_comm = new SqlCommand();
dbownerchange_comm.Connection = dbownerchange_Conn;
dbownerchange_comm.CommandText = "EXEC sp_changedbowner 'sa'";
dbownerchange_comm.ExecuteNonQuery();
dbownerchange_Conn.Close();
Simply, If we need to move(copy) Microsoft localdb file to another place(computer), how can I do this successfully?
Must we detach before move the localdb file? If so, I'm worried there're always people who don't follow guideline by running detach function.
I've tried several scenarios to understand how SQL server is working. The conclusion is we need to detach first and re-attach to same or different machine(computer). Then, I could have been successful to move to another computer.
However, a single process of backup and restoring localdb to another machine(computer) doesn't work. Furthermore, if we detach localdb(database file .mdf) first, SQL server no more recognizes the localdb database and we cannot run backup command for the localdb.
Conclusively and simply, if we want to move localdb (microsoft database .mdf file) to other local server(computer, machine), we're needed to just detach the localdb from master database in computer A and copy the files and re-attach to another master database of computer B.
Hope this helps someone else..

How to connect database with C# executable file?

I am writing code for a small company that is all about purchase and sell. I wrote C# code with using external database (SQL Server 2014), now it's time to make the exe file of that code.
I tried my best but it doesn't work.
How can I connect SQL Server 2014 database files with my application so that when someone installs it on his computer he also got SQL Server connected with that application?
Hi actually we deploy code as setup file (.msi), you can create setup project using Wix or install-shield ( maybe other too,but these two are most popular and widely used)
You can do database deployment in two ways
1.) you can provide SQL script for generating SQL server and give instruction for generating Database from Script. It is simple and easy to do.
2.) Other way is provide option to create database from setup. It need some work, but it is more good way.
Now come to your question, you can provide some UI in setup that take input from user and connect to appropriate DB. Or create a UI for Updating configurations, and save configuration (connection string ) in some file ( ex: .ini or .config file).
Below are the some URL for creating Setup and connecting to Db using Wix:
WIXDataBase
installing-databases-using-wix
Creating-an-installer-using-Wix
using-wix-to-install-sql-databases-and-execute-sql-scripts
WiX Samples
Ideally you'd have a SQL server set up somewhere. If not you'll have to install sql server. In your app it's just a matter of setting up the connection string and running sql commands against it.
string connectionString = "Data Source=server //rest of connection string"
Then in c# you can do
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM SomeTable", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetString(0), reader.GetString(1), reader.GetString(2));
}
}
}
GetString can be changed to GetInt or whatever the datatable will be. This should be enough information to get you started. If you know the structure of the database its simple to put the results into your classes for the application.

How do I used a database I created in MS SQL Server 2008 R2 with a VS C# Project?

I created a new database using SQL Server 2008 R2 by using the Management Studio. The connection says (local) and I am using Windows Authentication (though I installed with mixed mode).
My questions are:
How do I connect to the DB via my C# application -
The only time I ever have done this before I just used VS Menu > Tools > Connect to DB and the drop down saw my database and connected, then right clicked on it and grabbed the connection string for use in connecting. However I'm thinking because its (local) I don't have that option.
As per Q#1 I am assuming the database file is being stored somewhere locally - I am wondering how to find that location and how I can include it with my application
Edit** Per comment: VSMenu-> View-> Server Explorer and then use add connection to connect to your local SQL Server instance and then use the database you created from the databases dropdown, and from advance settings copy the connection string created by the connection dialog
This is what I am looking for but I am missing the step during "add connection" where do I find my SQL Server I created locally? As mentioned before I have no idea where it is stored or how to find it
MSDN has an example in the SQLConnection documentation
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
You can then optionally use a SqlDataAdapter.
You need to use ADO.NET, which is comprised of a connection object (SqlConnection), command object (SqlCommand), parameters objects (SqlParameter) and data sets (DataSet) or data readers (SqlDataReader).
Read A Beginner's Tutorial for Understanding ADO.NET.

asp.net c# connect to local Db vs2008

I'm making an ASP.net with c# webapp using VS 2008, and I added a new sql database item to my project. I added tables to the databse. In the database explorer the test connection works. I guess I have two questions. One:In the application, how does one connect to the database using a connection string? or what connection string should I use? Second: How do I add a username and password to the database?
Right now I'm using this connection string in the web.config file, but when I run the app it times out and says it can't make a connection. The error is on the conn.open line.
add name="ReportsConnectionString" connectionString="Data Source=(local); Initial Catalog=REPORTS;Integrated Security=True" providerName="System.Data.SqlClient"
I have this code in one of my page's codebehind.
string sqlquery = "SELECT * FROM reportitems";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ReportsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(sqlquery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
DataSet ds = new DataSet();
adapter.Fill(ds, "reportitems");
DataRowCollection dra = ds.Tables["reportitems"].Rows;
foreach (DataRow dr in dra)
{
string DRZ = dr[0].ToString();
//more stuff here
}
}
}
}
Usually SqlServer Express is reachable on your local PC using this syntax for the Data Source parameter yourpcname\SQLEXPRESS. To be sure start Management Studio and look at the Server Name request.
For the security part of your question, I suppose that you don't want the Integrated Security option (Windows User), but you want a SQLServer user. In this case you could use the User ID and Password parameters for the connection string:
Data Source=MYPC\SQLEXPRESS;Initial Catalog=REPORTS;User Id=MYNAME;Password=MYPASS;
However, this works only after you have added this user to the SQLServer.
You could use the interface of Management Studio app or you could execute a script like this
USE [master]
GO
CREATE LOGIN [MYNAME] WITH PASSWORD=N'MYPASS', DEFAULT_DATABASE=[master]
GO
USE [REPORTS]
GO
CREATE USER [MYNAME] FOR LOGIN [MYNAME]
GO
The Integrated Security=True part of the connectionstring means that the server will use the credentials of the app pool running the site, and you don't need to specify username or password. The app pool identiy will, however, need to have access to your database.
Visit http://www.connectionstrings.com/ for a good primer on various ways to set the connection string for various applications. That'll show you why (local) didn't work but .\SQLEXPRESS did and how to add username and password to it. Here's an example lifted from http://www.connectionstrings.com/sql-server-2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
As others have said, you need a SqlExpress engine running as .mdf is not a flat file. It is a SQL server express database file and you need to connect to it.
But what have not said is that a Database in your App_Data folder needs to be attached to the SqlServer instance. This step is only done once in the first connection.
In http://www.connectionstrings.com/sql-server-2008 you will find an example in the "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance" section that looks like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
Also you can read this: http://msdn.microsoft.com/en-us/library/ms247257.aspx
I believe that you will need to run some scripts and stuff like that to create a user and assign permissions to this user in this database, and then change the connection string (once the database attached), so I don't see a point in having the database in the App_Data folder. I believe it should be better if since the beginning you create your database using the SqlServer tools and connect to it from your application.

Enable remote connections to sql express with a script

I am deploying an application with sql server express 2008. In the prerequisites section of my application I have included:
As a result when a user installs my application it will install sql express as well.
Then I will be able to connect to that database engine as:
try
{
// database should be in the same network
SqlConnection conn =
new SqlConnection(#"Data Source=.\sqlexpress; Integrated Security=True");
conn.Open();
MessageBox.Show("Connection succesfull");
}
catch
{
MessageBox.Show("Unable to connect");
}
Now when I install a different application(client version) I will like to be able to connect to that database engine. I managed to connect to it by doing something like:
try
{
SqlConnection conn =
new SqlConnection(#"Data Source=192.168.0.120\sqlexpress,22559; USER=sa; PASSWORD=*********");
conn.Open();
MessageBox.Show("Connection succesfull");
}
catch
{
MessageBox.Show("Unable to connect");
}
In order for that code to work I had to do the following:
So my question is:
How could I configure this with code? When I deploy my application I want my application to install sql express like it does but I also whant to enable tcp/IP connections, enable some ports and lastly create a password for the account "SA" because I am not able to connect to the database remotly if the sa account does not have a password.
Or maybe I am asking to much and I am doing the wrong thing. perhaps I should do all this just for the database that I am planing on deploying not the database engine. whatever is easier. I have had a hard time deploying this maybe it will be eassier to deoploy a local database along with a wcf service in order to create CRUD operations on the local database remotely.
EIDT
I found this 3 links that claim on doing something similar and I still cannot make it work.
1) http://support.microsoft.com/kb/839980
2) http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/c7d3c3af-2b1e-4273-afe9-0669dcb7bd02/
3) http://www.sql-questions.com/microsoft/SQL-Server/34211977/can-not-connect-to-sql-2008-express-on-same-lan.aspx
downloaded sql server express 2008 (SQLEXPR32_x86_ENU.exe) and place it in the root of my c drive. then I install it with the following parameters:
C:\SQLEXPR32_x86_ENU.exe /q /hideconsole /action=Install /features=SQL /instancename=SQLEXPRESS /enableranu=1 /sqlsvcaccount="NT Authority\Network Service" /AddCurrentUserAsSqlAdmin /skiprules=RebootRequiredCheck /TCPENABLED=1
I add /TCPENABLED=1 in order to enable TCP/IP
I suggest you to create modified bootstrapper package to install Sql Server 2005 Express with customzation.
As an alternative, you can also use a custom action in your installer to change the targeted server using SMO.
Something like this:
Server server = new Server( "ServerName\\InstanceName" );
server.ConnectionContext.Connect();
server.Settings.LoginMode = ServerLoginMode.Mixed;
server.Settings.Alter();
We use SMO object to create user login and associate user to our created application database.. even run sql script to create database if database is not available..
Refer these links:
Configuring SQL Express During Installation
Configuring SQL Server when included as a requirement
Note: Create your sql server connection string settings in App.config file rather than putting hardcore in code.. this will help you customize application first run customization e.g. database creation.
These might be of some help, I've had it on my todo list for a while for the computers I have to setup for my app to run with Sql Server 2008 Express. It's basically a way to setup a script that the SQL08exp installer will read and automate a lot of the setup according to what you set in the script.
http://digitalformula.net/articles/how-to-perform-an-unattended-installation-of-sql-server-2008-express/
http://blogesh.wordpress.com/2008/09/23/silent-install-of-sql-server-2008/

Categories