We create an Sql DB Bakup through application using the code below:
ServerConnection srvConn = new ServerConnection(HostName);
srvConn.LoginSecure = true;
Server srvSql = new Server(srvConn);
string FileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
+"//Closing Back-Up");
bkpDatabase.Database = database;
BackupDeviceItem bkpDevice = new BackupDeviceItem(FileName, DeviceType.File);
bkpDatabase.Devices.Add(bkpDevice);
bkpDatabase.SqlBackup(srvSql);
It works fine for Drives excluding the Drive where OS is installed due to right problems. In the drive with OS it says:Cannot open backup device. I searched it on internet and SO, but it suggests to manually change Built-In account from "Network Service" to "Local System" using SQL Server Configuration Manager.
But we distribute our software online and via CD's for self installation, so it is impossible to instruct each and every client to do so as they may not be technically well-versed with it.
So the question is, can we change the built-in account via Script ? Or is there any other solution that we can perform via program or script ?
Thank you.
Edit:
We distribute SQL Server 2008 Express as a pre-requisite and downloaded from same folder as my application. The prerequisite doesn't ask for any account settings or instance-name etc settings, which we find in SQL Server manual installation procedure.
Not sure this will work or not but You can try to run the program as administrator through code. There is a good article how to run program with admin rights.
How to force my C# Winforms program run as administrator on any computer?
Related
I'm currently running Microsoft SQL Server 2022 Express Edition in a Docker container on Ubuntu. I'm running the following query using C# with the Microsoft.Data.SqlClient namespace:
BACKUP DATABASE [DBName] TO DISK = N'/path/to/dir/DBName.bak' WITH NOFORMAT, NOINIT, NAME = 'DBName', SKIP, NOREWIND, NOUNLOAD, STATS = 10;
The backup is successfully created with the following permissions:
-rw-r----- 1 root root 16900096 Feb 2 11:14 DBName.bak
Is there a way I can configure SQL Server to write the backup file with certain permissions (basically the equivalent of running sudo chmod on the file)? I specifically want all users to have read/write/execute permissions.
I COULD just have my code run a shell script that sets the permissions after the file is created, but I would prefer a platform-independent solution. I was hoping that SQL Server may have some way of configuring the backup file output.
I currently use Jenkins to build my solution and run some Selenium Tests against my website. At the minute this points to a hard-coded URL on a different server, however, I have changed this to load the website in an IIS Express instance on the Jenkins server allowing the Selenium tests to run against the current version of the code.
The process goes as follows:
Commit happens on branch, Bitbucket lets Jenkins know and then Jenkins jumps into action.
Solution is built
Selenium Tests are started
A Process is created in C# pointing to the local IISExpress.exe and loads website code into it
We have a DB Project in Visual Studio which is loaded using Dacpac into (localdb)\MSSQLLocalDB
The newly created DB is populated with all the required data
The individual tests then run
Once complete the database is deleted
Currently the website is loaded in IIS Express successfully, the database is created and populated, but once the Website tries to access the database it receives an access denied error.
The error recieved is:
Cannot open database XXX request by the login. The login failed. Login failed for user 'NT AUTHORITY\SYSTEM'.
I have added logging throughout the solution and have found that the account which creates the database successfully when running from Jenkins is 'NT AUTHORITY\SYSTEM', and then the account which is running the IIS Express instance (which is started from Jenkins) is also 'NT AUTHORITY\SYSTEM', so am I am not entirely sure why it can create the database and populated it, but then fails access if via IIS Express.
The connection is set to use Integrated Security, and does run fine when run locally using Visual Studio. I have attempted to not use Integrated Security and instead create a SQL User, but I receive the same error.
We use NUnit to run the selenium tests and IIS Express and the DB are created from a SetUpFixture class which runs once on setup and once on teardown.
IIS Express is run using the following code:
string programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
_iisProcess = new Process();
_iisProcess.StartInfo.FileName = programFiles + #"\IIS Express\iisexpress.exe";
_iisProcess.StartInfo.Arguments = $"/path:\"{_applicationPath}\" /port:{_port}";
if (!_showConsoleWindow)
{
_iisProcess.StartInfo.CreateNoWindow = true;
_iisProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
_iisProcess.Start();
I know this works as once the tests start I can remote onto the Jenkins box and view the website.
The local DB is being created with the following code:
string connectionString = $#"Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True;";
DacServices instance = new DacServices(connectionString);
string dacpacPath = Path.GetFullPath(
Path.Combine(
TestContext.CurrentContext.TestDirectory,
dacpacRelativePath
));
using (DacPackage dacpac = DacPackage.Load(dacpacPath))
{
instance.Deploy(dacpac, _databaseName, true,
new DacDeployOptions {
CreateNewDatabase = true,
IgnorePermissions = true,
IgnoreLoginSids = true,
IgnoreRoleMembership = true,
IgnoreUserSettingsObjects = true
});
}
I know this works as I can view the folder for the user NT AUTHORITY\SYSTEM and can see that the Database is there.
As IIS Express is being run by the same user that the Database is created using, I would expect it to not have an issue accessing the database. I have set Selenium to take a number of screenshots when running the tests and the 2 errors I receive when the website is attempting to access the Local DB are:
No process is on the other end of the pipe
Cannot open database XXX requested by the login. The login failed.
Generally the first few tests to run receive the first error, then every test after that receives the second.
Has anybody ever had this issue before or can provide any suggestions of what I could try to resolve it?
#BugFinder that has solved the issue.
Looking into the documentation for LocalDB here I found the following point:
An instance of LocalDB owned by the built-in accounts such as NT
AUTHORITY\SYSTEM can have manageability issues due to windows file
system redirection. Instead use a normal windows account as the owner.
Changing this to a windows account has allowed it to work as expected.
Thanks for the help!
I am creating a POS system in Windows Forms (C#) in which I use a SQL Server database file (.mdf) to store items (completely offline). When I install the application on my computer, it works fine, but when I install it on my clients PC, an error happens:
(provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation"
I read somewhere that the problem is caused due to the fact that the connection string of the database of my client's PC is different. I tried to add the connection string dynamically on runtime but again it only worked on my computer.
Another reason that might be causing the problem is that I used 'server-based database' since local database option isn't available in Visual Studio 2017 for some reason.
Another solution I looked up stated that I should install SQL Server Express on my client's PC. That also failed (maybe I have to set it up in a way or something).
I also tried adding the database.mdf and database_log files in the setup folder.
Lastly I tried installing 3rd party installers (Advanced installers 15.8 and InstallShield Wizard in VS 2015) which also failed.
(I have provided the code for the connection of database taking place and the connection string)
public void ConnectToDB()
{
DBConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\SAIM NASSER\Desktop\app layer\data layer\Database1.mdf; Integrated Security = True");
DBConnection.Open();
ResultSet = new DataSet();
}
If I understand you correct, you want to use LocalDB
That means using Sql Server without installing a full sql server, but just the localdb part from sql server express.
For this to work you need to install the LocalDB Driver, which can be found here
https://www.microsoft.com/en-us/download/details.aspx?id=29062
You need only the ENU\x64\SqlLocalDB.MSI
This is the only thing you need to install in your clients computer, I believe it can also be installed silent, you have to research a bit for that.
And yes, you also should change the connection string on the clients computer, you need to alter it so it points to the MDF file on the clients computer, because that location will probably be different then on your computer
EDIT
To get the connection string working, you can try this
On the clients computer, create a text file and rename the extension to .udl
So for example you have a file test.udl
Now from explorer, double click it, this will open the datalink editor.
From here you can enter/choose different settings, and click on the test connection button.
Once you get a working connection, save it, and open this file with notepad.
Inside you will find the working connection string
Hope this helps
I'm getting the error below while starting the storage emulator. By mistake I deleted the mdf and log files in users/admin folder. It's holding reference someplace and not allowing me to create the DB again. Please help me.
Added reservation for 127.0.0.1:10000/ in user account RaviBorra-PC\Ravi Borra.
Added reservation for 127.0.0.1:10001/ in user account RaviBorra-PC\Ravi Borra.
Added reservation for 127.0.0.1:10002/ in user account RaviBorra-PC\Ravi Borra.
Found SQL Instance (localdb)\v11.0.
Creating database DevelopmentStorageDb201206 on SQL instance '(localdb)\v11.0'.
Cannot create database 'DevelopmentStorageDb201206' : Database 'DevelopmentStorageDb201206' already exists. Choose a different database name..
One or more initialization actions have failed. Resolve these errors before attempting to run the storage emulator again. Please refer to http://go.microsoft.com/fwlink/?LinkID=248088 for more details.
Thank you,
Ravi Krishna B.
Do these steps:
Open cmd.exe (Command Prompt)
Write this:
SqlLocalDb stop "v11.0"
SqlLocalDb delete "v11.0"
and press Enter
Note that "v11.0" is MyInstance.
For more details, visit this link.
This problem may occur if you delete the data file C:\Users\<Username>\DevelopmentStorageDb201206.mdf but do not delete the corresponding database on the LocalDB server instance. One possible solution is:
Connect to the (localdb)\v11.0 instance from SQL Server Management Studio.
Delete the DevelopmentStorageDb201206 database. There will be the error message that the database deletion ended with an error. Ignore this message and refresh the database list manually.
Now you can start the Azure Storage Emulator.
This is not a problem related with Azure components rather LocalDB instance is reporting back to Azure request that DB still exist. Check LocalDB instances in your machine using "sqllocaldb i" first and the delete the instance using "sqllocaldb d 'instance_name'". I could not test it in my machine but this may unblock you if localdb instance is blocking you.
In Windows Azure SDK 1.7, Windows Azure Storage Emulator uses LocalDB instance specific configuration at following location:
%LocalAppData%\DevelopmentStorage\DevelopmentStorage.201206.config
And based on that you will see that v11.0 instance is Windows Azure Storage Emulator specific so verify if that is running and deleting it will let DSInit to create the DB again in LocalDB.
If you have Sql Express installed on your local box then (localdb)\v11.0 is most likely not your local Sql instance. It is more likely {MyComputerName}\SQLEXPRESS.
Going to:
C:\Users\<yourloginname>\AppData\Local\DevelopmentStorage\DevelopmentStorage.201206.config
And changing:
<SQLInstance>(localdb)\v11.0</SQLInstance>
To:
<SQLInstance>{MyComputerName}\SQLEXPRESS</SQLInstance>
solved this error for me.
I hope this helps..
If you already tried and failed perform:
SQLLocalDB stop v11.0
SQLLocalDB delete v11.0
Delete all the files in C:\Users\<accontname>\WAStorageEmulatorDb* (usually one mdf and one ldf)
Create a new account (I called it Azure, with administrative rights)
Run again the installation
Installation completed!
For me this works... I had tried to format the PC before use this way. I supposte my problem is related to my username that contains "invalid" characters like Name 'NickName' Surname while the "Azure" account seems to be OK for him.
I figure it out 'cause somewhere in the log I have a property destination path set to "C:\Users\Name$_" that is far away for the path of my user account folder.
After that you can go on CMD.exe and prompt:
control userpasswords2
From the control you can delete the Azure login without delete the file folders!
Hope it helps!
I simply deleted all the mdf's and ldf's in C:\Users\accountname\ that started with DevelopmentStorage... or WAStorageEmulator.
Re-ran the install and it worked.
This can also be caused by the folder not existing for localDB. It looks like Visual Studio / Azure will not automatically create containing folders. I just copied the path from the error code into explorer and created the directory up to the .MDF file.
In visual studio go to Tools -> Options -> Database Tools-> Data connections and change a localdb instance name from v11.0 to some other name.
I did have SQL Express installed, as Brian Ogden suggested in his answer, but I wanted to try & point Azure Storage Emulator to my SQL Express instance without modifying configuration files.
I did this by running the initialization process for Storage Emulator & passing my server\instance details for SQL Express using the available switches. Below example of the command I executed (from an elevated command prompt):
AzureStorageEmulator.exe init -server MY-PC-NAME -instance MYSQLINST
This created the database successfully (in my SQL Express instance) & got my Storage Emulator working.
I am using a named instance, but I'm thinking this same approach can be used for default instances by omitting the -instance switch.
I want to make a database backup with this C# code:
connect = new SqlConnection(con);
connect.Open();
// Execute SQL
SqlCommand command = new SqlCommand
(
#"backup database MY_database to disk='d:\SQLBackup\wcBackUp1.bak' with init, stats=10",
connect
);
command.ExecuteNonQuery();
connect.Close();
When I run it, the following error message shows up:
Cannot open backup device 'd:\SQLBackup\wcBackUp1.bak'.
Operating system error 3(The system cannot find the path specified.).
If I change the path to d:\wcBackUp1.bak it seems to be ok, is without error, but the file does not exist, it was not generated.
If I run in SQL the command I have the message that it was 100% processed, but I didn`t see the file.
Could someone help me please?
Make sure the location "d:\SQLBackup\" exist in your database server and not on your client machine.
Two things to check.
The Sql Service may not have access to the d:\sqlbackup folder. Old Sql installs used to default to install the service with full access to the machine, but newer instances tighten that up. You could try changing the path to the directory where the default backups are stored.
Secondly, if the sql server is not on the same machine that you are running this program, then you must remember that the D: will be the D: on the sql server and not your local machine
Fundamentally, the Windows account that the SQL Server service runs under must have write permissions on the specified folder.
You can check what account this is by looking in SQL Server Configuration Manager, under SQL Server Services (look at the Log On As column)
Check what permissions that account actually has on the target folder using Explorer -> right click folder -> properties -> security -> advanced -> effective permissions.
One way to check that this is the problem is to change your code to back up to your SQL instance's backup folder, where the permissions are likely to be correct. For example
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup