C# Windows Forms and SQL Server - c#

I have to send my C# Windows Forms project (using SQL Server LocalDB on vs server explorer) to my teacher but if I send her my project with localDB as my database, it doesn't work on her system. What should I do? I really appreciate it if someone helps me.

You can send your database script to your teacher. You can do for Microsoft Sql Server like that:
Right click on your db > Tasks > Generate Scripts... > next > next > Advanced > You should change "Types of data to script" area as "Schema and data". > Click "Open in new query window" radio button. > next > next > finish.
After this process, you can save this script file and send to your teacher.

I have experienced the same scenario. I just did in this manner,
Create a database on SQL Server Management Studio and add all the tables and funcs to it
Just copy and paste the created database from C:\Program Files\Microsoft SQL Server\MSSQLSERVER\MSSQL\DATA\YourDatabase.mdf and YourDatabase_Log.ldf files to your debug folder.
Lastly, Change your SQLConnection String to connect the database on the location of the CurrentFolder which of format,
Connection String
string path = Path.GetFullPath(Environment.CurrentDirectory);
string databaseName = "YourDatabaseName.mdf";
string fullpath = path + #"\" + databaseName;
if (File.Exists(fullpath))
{
SqlConnection con = new SqlConnection(#"Data
Source(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName +
"");
return con;
}
else
{
throw new Exception("Database Not Found :(");
}

Related

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

Create Backup of attached database file

I have Database file .mdf which is installed with setup where application installed.
All database operation Insert,Update delete works fine but only problem arise in back up.
Now i want to make back up of attached mdf file to application installed path when i click on backup button.
Following is my connection string.
<add name="MyConstring" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Database=Database;Integrated Security=True;User Instance=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
Code which create back up.
string serverName = "";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();
string server = builder.DataSource;
string attachDBFilename = builder.AttachDBFilename;
string DatabaseName = "[" + builder.InitialCatalog + "]";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + #"d:\Data\" + "Aa.bak" + #"'";
string svr = "Server=" + server + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Above code give following error only if i use database file attached.
But is gives error
"Database does not exist"
Your database service engine account must have access to that physical file. As error suggest it's a operating system error. So You need to give proper permission on that folder or file.
See following link.
http://dbamohsin.wordpress.com/2009/06/03/attaching-database-unable-to-open-physical-file-access-is-denied/
Write click on folder and goto security and give proper permission to the data folder so that your SQL server user can access that folder.

Saving the filename into sql database and running ssis package at the same time

Scenario: I am developing a web application that allows users to upload Excel files into their respective tables in a SQL Server 2008 R2 database. I am also running an ETL process developed using SSIS when the user clicks on the upload button.
My development environment: Asp.net, IIS7, C#, SQL Server 2008 R2
I am currently facing the problem of saving the file name of the file into another column in the tables as I will also be creating gridview function for the user to view the files that have already been uploaded into the database and enables the users to download the error files.
Question: are there any ways I can save the file name into the same tables while running the SSIS packages during the ETL process?
Below are a sample example of my codes:
string filePath1 = Server.MapPath(System.IO.Path.GetFileName(file.FileName.ToString()));
file.SaveAs(filePath1);
package = app.LoadPackage(packageString, null);
package.Connections["Excel Connection Manager"].ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath1 + ";Extended Properties=Excel 12.0;HDR=YES;IMEX=1";
Microsoft.SqlServer.Dts.Runtime.DTSExecResult results = package.Execute();
This method allows me to retrieve the fileName :
String.Format("File : {0} uploaded.", file.FileName)
So when I execute the package, how do I save the file name to the tables at the same time?
string connectionString = DAO.GetConnectionString();
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open()
strQuery = "update uploadSummaryDB set fileName = #fileName where id in (select max(id) from uploadSummaryDB)";
SqlCommand command = new SqlCommand(strQuery,sqlConn);
command.Parameters.Add("#fileName", SqlDbType.NVarChar).Value = file.FileName.ToString(); command.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

Changing SQL Server settings programmatically

I request you to read my question carefully.
You might know when you install VS2005/2008 with SQL Server Express edition, the SQL Server operates in Windows authentication mode by default. You can use the SQL Server Management Studio to change the mode to Mixed mode (Windows and SQL Server Authentication mode).
Similarly to allow the SQL Server remote connection through TCP/IP, you need to use SQL Server Configuration Manager then select Protocol for SQLEXPRESS and then change the setting for Tcp/IP option.
What i need is to automate this process programmatically using C#. That is, i need to write a c# program to change the mode or change the tcp/ip settings etc.
Can anyone provide me help on this, how could i do that?
Thank you for sharing your valuable time.
You should use SQL Server Management Objects (SMO) - this is an API for managing SQL Server programmatically.
UPDATE:
Proves to be a bit tricky: Server.LoginMode (read/write), Server.TcpEnabled and Server.NamedPipesEnabled (get only, unfortunately). In order to modify protocols, you need to examine Microsoft.SqlServer.Management.Smo.Wmi namespace (hence going from 'the other end'):
ServerProtocol - represents server protocol
ServerProtocolCollection - a collection of all protocols defined on a given server
This function in C# will enable TCP/IP Protocol and set the Login mode to Mixed mode.
See complementary information here.
here is the code:
private static bool SetServerProperties()
{
#region standardize Connection String
string tempCatalog = "master";
string temp = #"Data Source=" + dataSource + ";Initial Catalog=" + tempCatalog + ";Integrated Security=True;MultipleActiveResultSets=True";
#endregion
SqlConnection sqlconnection = new SqlConnection(temp);
SqlCommand cmd = new SqlCommand("select ##ServerName", sqlconnection);
sqlconnection.Open();
string serverName = "";
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
serverName = dr[0].ToString();
}
catch
{
MessageBox.Show("Failed to Set SQL Server Properties for remote connections.");
}
Server srv = new Server(serverName);
srv.ConnectionContext.Connect();
srv.Settings.LoginMode = ServerLoginMode.Mixed;
ManagedComputer mc = new ManagedComputer();
try
{
Service Mysvc = mc.Services["MSSQL$" + serverName.Split('\\')[1]];
if (Mysvc.ServiceState == ServiceState.Running)
{
Mysvc.Stop();
Mysvc.Alter();
while (!(string.Format("{0}", Mysvc.ServiceState) == "Stopped"))
{
Mysvc.Refresh();
}
}
ServerProtocol srvprcl = mc.ServerInstances[0].ServerProtocols[2];
srvprcl.IsEnabled = true;
srvprcl.Alter();
Mysvc.Start();
Mysvc.Alter();
while (!(string.Format("{0}", Mysvc.ServiceState) == "Running"))
{
Mysvc.Refresh();
}
return true;
}
catch
{
MessageBox.Show("TCP/IP connectin could not be enabled.");
return false;
}
}
What about modifying the registry?
Client Protocol Settings are stored here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\SNI9.0
Check out ProtocolOrder.
Authentication Mode is stored here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\LoginMode
See:
Authentication Settings
I was able to do this with a small footprint by executing this stored procedure from C#:
USE [master]
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2
GO
It doesn't look like much but works flawlessly and instantly, without restarting services.
I think you could solve your problem making a silent installation of SQL Server Express edition using a configuration file for the install process.
In this link you can find the command line parameters for the installation.
In this one you can find how to make your configuration file.

Categories