Open multiple files in an existing instance of SQL Server - c#

So I've written a simple exe that will extract sql files from a zipped folder and open them in SQL Server Studio. It works great except that sometimes there will be multiple sql files to open, which then causes multiple SQL Server Instances to open. How can I make the files all open in one instance?
This is what I'm trying so far:
foreach (string sqlFile in files)
{
Process sqlServer;
if (Process.GetProcessesByName("Ssms").Length > 0)
sqlServer = Process.GetProcessesByName("Ssms")[0];
else
sqlServer = new Process();
sqlServer.StartInfo.FileName = sqlFile;
sqlServer.Start();
}
Sometimes a file will magically open in an existing SQL Server window but I haven't figured out why.

I couldn't find any way to use an existing SSMS (sorry!), but fortunately, I found SSMS command line very useful. It can be fed with the name of the server and/or the instance to connect with switch -S. It also logins with Windows Authentication with switch -E. Take a look at its options via SSMS /? and choose what fits your problem best. Anyway I tested the following code with and without a pre-existing SSMS instance connected/disconnected:
string serverName = "myservername";
var sepratedFiles = string.Join(" ", files.Select(p=>"\"" +p +"\"");
Process sqlServer = new Process();
sqlServer.StartInfo.FileName = "SSMS";
sqlServer.StartInfo.Arguments = string.Format("-S {0} {1}", serverName, sepratedFiles );
sqlServer.Start();

Related

Failed to execute SSIS package in SQL Job

I have a simple SSIS package that only has 2 steps. Step 1 is a script task that will return the creation date of the last created file in the specific folder. And the second step, it will save the step 1 data into the database. Here is the complete code for step 1 in C#.
string vDir = Dts.Variables["UnitDirectory"].Value.ToString();
string vDBName = Dts.Variables["DatabaseName"].Value.ToString();
var directory = new DirectoryInfo(vDir);
var myFile = directory.GetFiles(vDBName + "*").OrderByDescending(f => f.LastWriteTime).First();
DateTime creation = File.GetCreationTime(vDir + myFile);
Dts.Variables["CreatedDate"].Value = creation;
Dts.TaskResult = (int)ScriptResults.Success;
In this case, i pass UnitDirectory variable with network sharing directory.
\\192.168.0.2\Database Backup\
The problem is, I can execute this package both from the Integration Service Catalog in SQL Server Management Studio and from Visual Studio. But, when I executed it as SQL Job, it just errors in step 1 and giving an unclear message.
Script Task:Error: Exception has been thrown by the target of an invocation.
I run SQL Job with my domain administrator credentials which have login access into network sharing directory. And this problem starts when I run in new installed SQL Server 2014. Previously this package has run normally in my old SQL Server.
Can you give me solution for this? I need your solution based on your experience. Thanks in advance.

How to open firebird database files in C#?

We get .ydb files of firebird database from client. Currenlty we created a DSN with some additional installation/drivers and then access the tables and data inside the files.
We are planning to move this process to azure cloud service (not azure VM) so to avoid creating DSN etc. we need to access the .ydb files from c# code.
I could not open directly using firebird ado.net provider, throwing exceptions.
The below are the steps used to create DSN in the machine. It is working for long time.
Firebird ODBC setup in Windows Server
DSNName-DSNName1,
Driver-IscDbc,
Database-E:\Somefolder\FileName.ydb
Client-C:\ProgramFiles\Firebird\Firebird2_5\WOW64\fbclient.dll
Database Account- SYSDBA
Password - masterkey
Role - SYSDBA
CharSet - None
Then used the below C# code to access the FileName.ydb using the DSN.
using (var connection = new OdbcConnection("DSN=DSNName1"))
{
connection.Open();
var schema = connection.GetSchema("Tables");
var tableNames = new List<string>();
}
Now to modify the above DSN creation process, I added FirebirdSql.Data.FirebirdClient nuget package in the c# solution.
string connectionString = "User=SYSDBA;" + "Password=masterkey;" +
"Database=E:\\Somefolder\\Filename.ydb;" + "Dialect=3;" + "Charset=NONE;" +
"Role=SYSDBA;";
FbConnection fbConn = new FbConnection(connectionString);
fbConn.Open();
var schema = fbConn.GetSchema("Tables");
It throws exception on fbConn.Open(); - Unable to complete network request to host "localhost".
How to open the .ydb files in C# directly without creating a DSN?
The biggest problem you seem to have is that you do not have Firebird server installed or running, so you can't actually connect to it and ask it to open the database file.
You can download Firebird from http://www.firebirdsql.org/en/downloads/ (you will probably need Firebird 2.5) and install it. Then in a project that references FirebirdSql.Data.FirebirdClient you should be able to connect with as little as:
using (var connection = new FbConnection(#"User=username;Password=password;Database=D:\data\DB\database.fdb"))
{
connection.Open();
}
If for some reason you don't want to install Firebird server, you will need to use Firebird embedded (which can also be downloaded from the link above).
You will need to make sure that your application is either running 32 bit or 64 bit, and download the right Firebird embedded package. Put it in the path, or in the folder of your executable. In the URL you need to add ServerType=1 to get Embedded support (the default is ServerType=0):
using (var connection = new FbConnection(#"ServerType=1;User=username;Password=password;Database=D:\data\DB\database.fdb"))
{
connection.Open();
}

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.

Open .sql file SQL Server Management Studio from a folder throught C# with a specfic server name

I need to open .sql files from a folder using c# . i am using this code to open .sql files
string[] Files = Directory.GetFiles(Folder);
foreach (string File in Files)
{
System.Diagnostics.Process.Start(File);
}
this code is working fine but...
I want to open SSMS in a specific server connection through c#.
Explanation: I want my c# code to open SSMS in a specfic server connection so that user dose not have to connect to a server when SSMS opens.
Thanks
Use System.Diagnostics.Process to start ssms and send the parameters
Process.Start("ssms.exe", "-S (local)\\sqlexpress -E C:\\SQLQuery1.sql");
Usage:
ssms.exe [-S server_name[\instance_name]] [-d database] [-U user] [-P password] [-E] [file_name[, file_name]] [/?]
[-S The name of the SQL Server instance to which to connect]
[-d The name of the SQL Server database to which to connect]
[-E] Use Windows Authentication to login to SQL Server
[-U The name of the SQL Server login with which to connect]
[-P The password associated with the login]
[file_name[, file_name]] names of files to load
[-nosplash] Supress splash screen
[/?] Displays this usage information
https://msdn.microsoft.com/en-us/library/h6ak8zt5%28v=vs.110%29.aspx
http://zarez.net/?p=1003

Local Database with Visual Studio 2012

I am creating a application and I want to use a local database stored on the clients local machines. I am debating over if I should use SQLITE or is there something in Visual Studio to help me. The other thing is that I want to create the database programmatically in the users directory when the application is launched.
I am see a few things online but the articles were all about SQL Server stuff and that is not want I want to do with this application. All data will need to be stored on the local machine.
You can use SQL Server Compact, which has tooling in Visual Studio. It's syntax-compatible with SQL Server, but stores its data in a local file, which you can create on the fly (at app startup, for example).
You can create the SQLite database on the fly with the libraries provided from their website. I have used it in many projects for my personal code, as well as it being used in some of the internal architecture of Data Explorer (IBM Product). Some sample C# to create a database file:
if (!Directory.Exists(Application.StartupPath + "\\data"))
{
Directory.CreateDirectory(Application.StartupPath + "\\data");
}
SQLiteConnection conGlobal;
if (!File.Exists(dbGlobal))
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";New=True;Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
firstRun = true;
}
else
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
}
try
{
conGlobal.Open();
}
catch (Exception)
{
//do stuff
}
Simply initiating a connection to the file will create it if the new=true is passed as the connection string. Then you can query it and get results just like you would any database.
You also have the ability to password protect the database files to prevent access to them from just opening them with an SQLite-Shell or a different SQLite DB viewer.
For more info on the pragma statements that are being passed in the connection string, see the following: http://www.sqlite.org/pragma.html
I'm not sure about programmatically (that's probably what you meant, right?) creating the database, but SQL Server Compact Edition has served me well in the past for simple apps. It's embedded and even runs in medium trust.

Categories