I'm trying to make a little app that would help me making my server backup. That app would run on my home PC so the main goal is to be able to connect to the external server, backup the selected database, dump the backup content to a string or something so I could write it on my PC disk and not the server's disk.
I did that which works to write on the server's disk, but I'd like to be able to write on my PC's disk the backup's result.
private bool BackupDatabase()
{
try
{
// Filename
string sFileName = string.Format("{0}\\{1}.bak", _sWhereToBackup, DatabaseName);
// Connection
string sConnectionString = String.Format(
"Data Source=tcp:{0};Initial Catalog={1};User ID={2};Pwd={3};",
DatabaseHost, DatabaseName, DatabaseUsername, DatabasePassword);
SqlConnection oSqlConnection = new SqlConnection(sConnectionString);
Server oServer = new Server(new ServerConnection(oSqlConnection));
// Backup
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = DatabaseName;
backup.Incremental = false;
backup.Initialize = true;
backup.LogTruncation = BackupTruncateLogType.Truncate;
// Backup Device
BackupDeviceItem backupItemDevice = new BackupDeviceItem(sFileName, DeviceType.File);
backup.Devices.Add(backupItemDevice);
// Start Backup
backup.SqlBackup(oServer);
}
catch (Exception ex)
{
throw ex;
}
return false;
}
Thanks so much!
This is going to get a bit hacky because you need to either
call sql functions to read the file on the server and return as a binary array to you and then convert back to a file. this will require proper permissions as the account you are running under to access the file on the server's drive.
you can use t-sql or a bit more 'advanced' .net code
t-sql can be seen in this great sql injection guide
http://www.blackhat.com/presentations/bh-europe-09/Guimaraes/Blackhat-europe-09-Damele-SQLInjection-slides.pdf
or .net:
http://www.mssqltips.com/sqlservertip/2349/read-and-write-binary-files-with-the-sql-server-clr/
map a file location (i.e. access a share/drive/ipc connection) over the network
have the server ftp the files to a location
Which sounds likely in your scenario?
I take it that you're not networked to the server? Ideally you could back it up directly to your machine using a network address but I'm guessing you would have already thought of that.
Going the route you're thinking of is going to require you to have permissions that you would not normally want to have opened up to the someone over the internet, and will be much more trouble to program than simply setting up a second process to move the file somewhere accessible to you.
Adams suggestion to have the server ftp the files is a good one. Alternatively, you may find that using DropBox (www.dropbox.com) might be the path of least resistance. Then you could just back the database up to a folder setup with dropbox and it will automatically be copied to any folder you setup on your machine to be synchronized with it.
You should look into DAC, it is mainly made for the SQL Server in Azure, but will work with a SQL Server 2008 R2 too.
http://sqldacexamples.codeplex.com/
Related
I have a problem I need to solve, but not know how exactly. I have a WinForms application (C#) which connects to an online MySQL server - no problem there. In this application I have an option to make database backups (basically I dump this database to a local file on a computer).
I would like to locally "open" this backup on client's computer (to check some old data) - I don't want to make database restore on my server, because database must still be in use for other users. I want to make clean install of MySQL on a local computer and connect to it trough localhost (like I do for testing ), but I do not have physical access to that computer. I can send MySQL installer to my client, but how to go about automatically creating user with password and database from my dump file?
I know how to create a new database if it doesn't exist, but how to do it if it's clean install of MySQL server - no user and password yet.
string connStr = "server=localhost;user=root;port=3306;password=????;";
using (var conn = new MySqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd.ExecuteNonQuery();
}
Any help and direction is appreciated.
Regards!
I don't know whether I understand your problem. However,if you install a new Mysql,you can use root user through no database.
Anyway, one thing you need to know,Connect database must has user and password for mysql or sqlserver.
You may need to be more concise description of your problem.
I am having some trouble connecting to an Access database which sits on a remote computer:
The Microsoft Access database engine cannot open or write to the file '\\ACCESSSERVER-PC\Warehouse Manager\Error Logging\Error Logging.accdb'. It is already opened exclusively by another user, or you need permission to view and write its data.
The database is not open for editing by anyone else and I should be able to connect to it.
I am using this connection string:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ACCESSSERVER-PC\Warehouse Manager\Error Logging\Error Logging.accdb;Persist Security Info=False;
And the error occurs when calling connOpen();
using (var conn = new OleDbConnection(ConnectionString))
{
try
{
conn.Open();
}
}
I gave myself full permissions for the server as well as the .accdb file iteself, and did the same for the NETWORK SERVICE account as per this post, but still not luck.
I don't have a problem connecting to databases which are stored locally, and this only seems to be happening whent rying to conect over the network.
Has anyone else experienced this and found a solution? Any help or advice is much appreciated.
I have checked this answer and can confirm that I have all the required permissions to access the file.
That question is marked as a duplicate of this question, but I don't have any programs running which would have a stream open to the file.
It turns out this was being caused by trying to work with some terrible IT infrastructure.
The issue is that \\ACCESSSERVER-PC is actually a Windows 7 machine and so can only handle a limited number of connections.
Running the IsLocked code from this answer against the database file gave me a much more useful error message:
No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept.
After getting some users to disconnect their Access runtime and mapped drives from the server and running the code again, IsLocked returned false and I was then able to connect to the database.
Here is the code I used to help me find the solution to this:
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
//
// ** OR There are already too many connections open to the
// ** "server" where the file exists!
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
The moral of the story is Don't use (or work in an environment where they use) a Windows 7 machine as a server when you need 20+ concurrent connections to the server!
I am a newbie to SQL Server and .net. Please let me know if my question is not clear before down voting.
I am working on a Windows application with C#. I should give option to users to connect to a .mdf file on a network drive. On my machine, I have Windows and SQL Server authentication. Users have SQL authentication hence I should use userid and pwd. Myself and users work on that network drive, read/write/modify. We pretty much share documents, add and delete docs from network drive.
Here is the designer
I will choose the SQL Server database .mdf file which is located in network drive and then do test connection. For Test Connection this is the code
string sTemp = System.Configuration.ConfigurationManager.AppSettings["connectionStringShare"];
string connectionString = sTemp.Replace("{AppDir}", txtDB.Text.Trim());
using (SqlConnection objSqlConnection = new SqlConnection(connectionString))
{
try
{
objSqlConnection.Open();
objSqlConnection.Close();
MessageBox.Show("Connection is successfull");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message.ToString());
}
}
This is the connection string
<add key="connectionStringShare"
value="Data Source=.\SQLEXPRESS;Initial Catalog=TableSQLExpress;AttachDBFilename={AppDir};Integrated Security=SSPI;user id=sa;password=pwd;" />
Here is the error message I got
Directory lookup for the file "S:\zrep\TableSQLExpress.mdf" failed with the operating system error 3(The system cannot find the path specified.).
Cannot attach the file 'S:\zrep\TableSQLExpress.mdf' as database 'TableSQLExpress'.
I changed connection string and tried also tired using windows authentication. No luck. Let me know if I need to provide any additional details. Since I am newbie to this field please give me detailed answer. I am glad to find this group. Thanks for everyone who looked into this.
When you use server-based SQL Server (i.e. Microsoft SQL Server Express) you are unable to share database file via network drive, it is by design. Even if you override default SQL Server behavior with a switch and enable UNC paths for databases, your data will be corrupted by multiple server instances trying to use single database MDF file. If you need to host database in serverless environment (using only a network drive), you may opt to Microsoft SQL Server Compact (SQL Server CE) edition. But be aware that in such case only one user will be able to access database file at the same time (exclusive locking -> low performance). Plus SQL Server CE does not have stored procs.
I'm trying to connect to a embedded firebird database using de following code:
var cmm = new FbCommand();
var csb = new FbConnectionStringBuilder();
csb.ServerType = FbServerType.Embedded;
csb.UserID = "SYSDBA";
csb.Password = "masterkey";
csb.Dialect = 3;
csb.Charset = "UTF8";
csb.Database = #"TESTE.FDB";
cmm.Connection = new FbConnection(csb.ConnectionString);
try
{
cmm.Connection.Open();
cmm.CommandText = "SELECT NOME FROM TESTE WHERE ID=2";
MessageBox.Show(Convert.ToString(cmm.ExecuteScalar()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cmm.Connection.Close();
}
The query execute depending of the directory of the program. If I open the program in the directory "C:\np" or other local directory, it works normally. But, if the directory is a network mapping, I receive the following error: "Unable to complete network request to host "psf". Failed to establish a connection."
What can I do to resolve this situation? Thanks.
Firebird doesn't allow opening databases on network shares by default, as this could lead to database corruption as Firebird needs either exclusive access to a database, or instances sharing a database file need to coordinate access using a lock file local to the server. Access through a network share means that multiple instances from multiple hosts could access the same database file, and that is not how Firebird is designed to be used.
If you want to access a single Firebird database from multiple hosts then you should setup a Firebird server and configure all clients to connect to that server, you should not use a network share.
However if you really want to access a database on a network share, then you can set the option RemoteFileOpenAbility in firebird.conf to 1. Given the risk of file corruption and data loss I strongly advise not to use this option, but use a Firebird server instead. Make sure you read the warning in the config file as well.
I am trying to create backup and restore of a database to new server with new name using C# and SQL server database. I can create a backup of the database but I am not able to restore it to the new server using the new name.
My query looks something like this: it doesn't work and errors out:
RESTORE DATABASE test1 FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL\BACKUP\setupdb\BackupForsetupdb.bak'
WITH MOVE 'setupdb_Data' TO '\\newserver\e$\MSSQL\DATA\test1_Data.MDF',
MOVE 'setupdb_log' TO '\\newserver\e$\MSSQL\DATA\test1_Log.LDF';
I am trying to achieve this through C# code.It looks like the database cannot be restored to the remote servers. Please throw some light on this.
Thanks!
You can't have SQL Server databases on network shares normally: local/SAN type drives only
The backup file can be on a share but the MDF and LDFs must be local
There is an MS KB article on it: it can be done but at your own risk
Your paths for the move command have to be relative to the server.
e:\MSSQL\Data\test1_data.mdf
And your restore from path has to be relative to the server as well. If the c:\ is from your local machine, you either need to point it to a UNC path (\\yourpc\c$\...) or move it to the server. But be aware that if using the UNC path option, the user the server process is running as has to have permissions to access the share as well. So you're probably better off copying to a drive on the remote computer.