Connect to a local database via user input - c#

I have a program where on a click event SQL will open and connect to a server instance and database however. I am wanting to make to program a bit more dynamic and allow user input but I am struggling to get this to work as wanted.
The old code is as follows and this works:
Process.Start("ssms.exe", "-S .\\SQLEXPRESS -d master -E ");
I tried the following but this just opens SQL but states will not use the details enterd to connect to a database.
Process.Start("ssms.exe", DataBaseNameInput.Text);
Edit
The error SQl shows is The following files where specified on the command line: These files could not be found and will not be loaded.

For this you would need to use SqlConnectionStringBuilder(), this allows you to build a string whitch can then be passed.
var Connection = new SqlConnectionStringBuilder();
Connection.DataSource = ServerNameTextBox.Text;
Connection.InitialCatalog = DatabaseTextbox.Text;
Connection.UserID = UserNameTextBox.Text;
Connection.Password = PasswordTextBox.Text;
var connString = Connection.ConnectionString;

This was done by the following information
Ssms Utility

Related

Synchronize two SQL Server database using Dotmim sync framework

I have a WinForms database driven application that I want to make it work in online/offline mode using Dotmim sync framework that I find an article by their author here.
The documentation for the library is here
this is my code to sync the two SQL Server databases one is localdb and the other one is now on the SQL Server Management Studio for the testing purpose:
string connect = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=bright_square_db;Integrated Security=SSPI;AttachDBFilename=D:\Folder\project_file\bright_square_db.mdf";
string constring = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlSyncProvider serverProvider = new SqlSyncProvider(constring);
SqlSyncProvider clientProvider = new SqlSyncProvider(connect);
SyncAgent agent = new SyncAgent(clientProvider, serverProvider, new string[] { "I have listed all the tables here" });
var progress = new SynchronousProgress<ProgressArgs>(s => MessageBox.Show($"{s.Context.SyncStage}:\t{s.Message}"));
var syncContext = await agent.SynchronizeAsync(progress);
MessageBox.Show(syncContext.ToString());
But, when I try to run the code. I am getting this error
The columns that indicated in the error are for a table that created by the sync process named "scope_info" inside the SQL Server database.
I have solved the problem by swapping the client and server connection string link in the third and fourth line of the above code. I don't know what exactly cause the problem, but lastly this changed makes the code work for me.

Firebird ConnectionString Change during runtime

I'm working on an app that has a live network database and a contingency local database, and it detects whether the live network db is accessible, and, if not, it times out after three seconds, changing the connectionstring to the local contingency database.
Following tips here on SO, I managed to alter the connectionstring on app.config during run time and reload the settings.
This is the method the app calls when a change on the connection string is needed:
public static void ChangeConnectionString(string connectionstring)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings[0].ConnectionString = connectionstring;
var connectionStrings = config.ConnectionStrings;
foreach (ConnectionStringSettings connectionString in connectionStrings.ConnectionStrings)
{
connectionString.ConnectionString = connectionstring;
}
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
PDV_WPF.Properties.Settings.Default.Save();
PDV_WPF.Properties.Settings.Default.Reload();
//Ensures the configuration is saved and reloaded.
FbConnection.ClearAllPools();
//Closes all currently open connections which might be using the old connection string.
Debug.WriteLine("==========Ran ChangeConnectionString");
Debug.WriteLine("==========FDBConnString is:");
Debug.WriteLine("==========" + PDV_WPF.Properties.Settings.Default.FDBConnString);
After I disconnect my computer form the network, whenever I check the current FDBConnString, it correctly points to the local contingency database. However, on the very next line, when it tries to run a query, I get the following exception:
Inner Exception 1:
IscException: Unable to complete network request to host "dbserver".
Inner Exception 2:
SocketException: Este host não é conhecido //(This host is unknown)
Full exception details: https://pastebin.com/3syLvsQf
It seems that, even after I successfully change the connection string, and successfully reload the application config file, it still tries to open a connection using the old connection string. Even if I call Debug to print the current Properties.Settings.Default.FDBConnString right on the line above the call for FbConnection.Open(), it shows the new string rather than the incorrect, old one.
Any insights on what might be going on?
I found what was the issue.
I am instancing a inherited table adapter from the generated xsd file. When I declare a table adapter on my class it also inherits the connection string stored on app.config at the time of declaration. So it doesn't matter if I change app.config, as the declared table adapter is already stuck with the previous connection string.
So, the solution was, rather than changing the connection string stored on app.config, I just had to change the connection string on the declared table adapter:
tB_STOCKTableAdapter1.Connection.ConnectionString = Properties.Settings.Default.ContingencyDB;
tB_STK_PRODUCTTableAdapter1.Connection.ConnectionString = Properties.Settings.Default.ContingencyDB;
or
tB_STOCKTableAdapter1.Connection.ConnectionString = Properties.Settings.Default.NetworkDB;
tB_STK_PRODUCTTableAdapter1.Connection.ConnectionString = Properties.Settings.Default.NetworkDB;
Both ContingencyDB and NetworkDB are strings stored on app.config as a user-scoped string, which can be changed via a given "Settings" window presented to the user.

"Data source name not found and no default driver specified" for creating access connection

This is my connection to an access database in .NET:
OdbcConnection conn = new OdbcConnection("Driver={Microsoft Access Driver (*.mdb)};Dbq=" + path + "\\Access.mdb;Uid=;Pwd=;");
And I got this problem:
base {System.Data.Common.DbException} = {"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"}
I have tried couple of database connection strings from here: http://www.connectionstrings.com/access but none of them working.
Any suggestions for this?
Thanks in advance.
There is an easy way to get the connection string, try it as follow:
Create a text file and change it's extension to .udl.
Open the new file by double click it and choose to open it with any text editor, notepad for example.
In the opened window, choose your provider and your database and click OK.
Open this file with notepad as a text and you will find the connectoin string inside it.
See This for more details.
as you can see in the same site you have linked above, the default way to connect to access database is specifying the Microsoft.Jet.OLEDB.4.0 Provider:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=;
does this work and if not what kind of errors do you get?
First, is path a valid field?
Second, try to output the String you are using to connect with the database file, as a sanity check. Make sure the output string matches what you are expecting, and that the file specified exists.
Try this
http://www.connectionstrings.com/
More specifically this one
http://www.connectionstrings.com/access
I would change your code to the following:
OdbcConnectionStringBuilder sb = new OdbcConnectionStringBuilder();
sb.Driver = "Microsoft Access Driver (*.mdb)";
sb.Add("Dbq", "C:\\info.mdb");
sb.Add("Uid", "Admin");
sb.Add("Pwd", "pass!word1");
OdbcConnection con = new OdbcConnection(sb.ConnectionString);
web.config add
add name="odbcConnectionString"
connectionString="Driver={Microsoft Access Driver (*.mdb)};DBQ=|DataDirectory|info.mdb; "
providerName="System.Data.OleDb"

C# Recovering Database stuck in 'Restoring...'

I am inserting a SQL Database Backup and Recovery section into my program. I have been using MSDN Examples (tryed another and it wouldnt work).
MSDN Page - http://msdn.microsoft.com/en-us/library/ms162133.aspx
I have got the Backup file working, and have tested the file in Management Studio.
But I am having trouble with the Recovery of the file.
The code seems to be working, but the database in SQL Server is stuck in "Restoring..."
if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Server sqlServer = new Server();
Restore sqlRestore = new Restore();
sqlRestore.NoRecovery = true;
sqlRestore.Action = RestoreActionType.Database;
BackupDeviceItem deviceItem = new BackupDeviceItem(openFile.FileName, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = "firstRecoverTest";
sqlRestore.SqlRestore(sqlServer);
//Add the recovered database into the Entity Table
SqlCommand intoEntity = new SqlCommand("IF NOT EXISTS(SELECT entityName FROM Entitys WHERE entityName = 'firstRecoveryTest') INSERT INTO Entitys VALUES ('firstRecoveryTest');", sqlConnection);
sqlConnection.Open();
intoEntity.ExecuteNonQuery();
Database db = default(Database);
db = sqlServer.Databases["firstRecoverTest"];
db.RecoveryModel = (RecoveryModel)1;
db.AutoClose = true;
//db.Alter();
}
In the example there is a db.Alter(); function, but that throws an error that says "Alter failed for Database 'firstRecoverTest'".
Please let me know your thoughts
Thanks in advance
UPDATE
After inserting the "ReplaceDatabase = true;" there was no change in the end result.
Also stepping though the code line by line, shows that it is making it through.
The "db.Alter();" is just that placed at the end of the code (shown as comment). It is used in the creation of the backup and works without error.
InnerError shows this information when using db.Alter();
"ALTER DATABASE is not permitted while a database is in the Restoring state"
The interesting part is the SQL Log files. I am getting 3 Logs:
"Starting up database 'firstRecoverTest'."
"The database 'firstRecoverTest' is marked RESTORING and is in a state that does not allow recovery to be run."
"Database was restored: Database: firstRecoverTest, creation date(time): 2011/09/20(15:44:48), first LSN: 37:159:37, last LSN: 37:175:1, number of dump devices: 1, device information: (FILE=1, TYPE=DISK: {'C:\Users\Administrator\Desktop\installer_backup'}). Informational message. No user action required."
However, when I do a normal recover using SQL Management Studio there is 2 more log entrys saying
"Starting up database '[databaseName]'."
"Restore is complete on database '[databaseName]'. The database is now available"
I don't have enough reputation to post a small image of how it is in SQL Management Studio unfortunatly.
You should try either dropping the database or using sqlRestore.ReplaceDatabase = true;.
http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.restore.replacedatabase.aspx
If it looks like nothing is happening you can start the process in a seperate thread and wire up the events for notification of progress changes by using these.
sqlRestore.Complete += new ServerMessageEventHandler(completionEvent);
sqlRestore.PercentCompleteNotification = 10; // Call progress event every x percent change.
sqlRestore.PercentComplete += new PercentCompleteEventHandler(progressEvent);
If that doesn't work can you please post the Alter code that wasn't working. Also check SQL server logs and permissions.
UPDATED
Ok that update makes more sense. The reason is because you are setting sqlRestore.NoRecovery = true;. This has the effect that after the restore is done the DB is kept in a recovery state so you can restore an additional differential backup in addition to the full you just restored.
While it is in this state you will not be able to do anything more to the database. I would suggest that unless you require it you leave the default which is NoRecovery = false.
See http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.backuprestorebase.norecovery.aspx
Hope that helps.

Database already exist. Choose a Different Name using CreateDatabase()

I got an issue and learned something at the same time....
I created a DBML from an existing server database.
From the DBML I wanted to create local database (an .mdf file). I created the database using DataContext.CreateDatabase("C:\xxxx.mdf") .
Then I decided to delete it (MANUALLY, which is a bad thing evidentally) because when I try to recreate the database with the same name (eventhough the files are deleted), I get the error Database already exist. Choose a Different Name using CreateDatabase()
I tried looking through the registry, no luck... I tried searching the whole hard drive for the file.. no luck.
After googling, I found that you delete a database that was created with CreateDatabase() with DeleteDatabase().... Then you can recreate the database again.
Well problem is, now I still can't recreate the old database because the system thinks the name already exists.
Is there a way to get rid of the reminents of the old databse file the "does not exist"
You need to open master database via server explorer in Visual Studio (Add New Connection + Select master database) then add a New query, type Drop Database xxxx and execute it. You can also use Sql Server Management Studio.
A solution (via here) is to use SSEUtil to detach the existing db:
try
{
// open a connection to the database for test
}
catch (SystemException ex) // Change exception type based on your underlying data provider
{
if (ex.Message.ToLower().Contains("already exists. choose a different database name"))
{
var match = Regex.Match(ex.Message, "database '(.*)' already exists.",
RegexOptions.IgnoreCase);
if (match.Success)
{
String dbFileName = match.Groups[1].Value;
Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.FileName = String.Format("{0}/Tools/SSEUtil.exe",
Environment.CurrentDirectory);
p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
p.StartInfo.Arguments = String.Format("-d \"{0}\"", dbFileName);
p.Start();
}
}
}
Here's a quick fix for a localDB mess. Just connect to (localdb)\MSSQLLocalDB in SQL Mgmt. Studio/Visual Studio.
Then delete the offender, checking "Close existing connections"
I also actually had this same problem. Previously, I deleted
(cut) the database in mysqlserver2012 and copied it to my application folder. After I made my app I got this error, and solved it by removing the Initial Catalog part of my Connection String.
Your final connection string should look something like this:
Data Source=<your server name>;AttachDbFileName=database path\databaseName.mdf;Integrated Security=True" + ";User Instance=True" + ";Context Connection=False;

Categories