How to open firebird database files in C#? - 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();
}

Related

C# - XLSX to SQL Server - OpenRecordSet not working in C# but works in MS SQL Server Management Studio

The following script works within a SQL Server 2014 Management Studio in a Stored Procedure but not when I call the stored proc via a C# app .NET Framework 4.8.
SQL Code:
create proc getData
as
Insert INTO tmpLeaveImport ([CarName], Year, Make , Model)
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.15.0',
'Excel 12.0;Database=E:\Cars\Cars.xlsx',
'SELECT * FROM [Car Report$]')
From C# I get the following error:
System.Data.SqlClient.SqlException: 'Cannot initialize the data source
object of OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked server
"(null)". OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked server
"(null)" returned message "Unspecified error".'
When this code is executed in C#:
//Tried the conn strign with Integrated Security=yes and SSPI
string ConnString = #"Data Sournce=MySQLServerDB;Initial Catalog=DBName;Integrated Security=true;";
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "getData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
conn.Open();
}
Short Version
According to this possibly duplicate question the Excel file may be open. Or this could be a more serious error.
Don't use OPENROWSET to import Excel data into SQL Server. Use a library like ExcelDataReader to read it without using the Access Engine and insert it to the target table with SqlBulkCopy. You'll avoid a lot of pain.
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
using (var bcp = new SqlBulkCopy(connString))
{
bcp.DestinationTableName ="SomeTable";
bcp.WriteToServer(reader);
}
}
}
Long Version
In both cases, the stored procedure runs on SQL Server, not on the client. SSMS is just another client as far as SQL Server is concerned. Assuming the same server is used in both cases, what's different is that the account that executes the stored procedure is different in each case.
With SSMS, it's the developer's account which quite often has sysadmin privileges on the server. With C#, the account may be the end user's, or the application pool account that runs a web site, which has very restricted privileges. SQL Server's default service account is a restricted account too.
This matters because the Access Engine is a COM component. To use it, applications need to look it up in the registry, which requires its own permissions. If you search SO for the error you got you'll see questions where the choice of service account affected whether Access Engine can be used or not. In other cases, the file was open.
Another potential problem is that ACE must target the same architecture as any previous Office components installed on a machine. If you have a x86 Office application, you can only install the x86 version of ACE. That's because you can't use COM component created for one architecture from a process that targets another one.
This also means you can't use an x86 ACE in a x64 installation of SQL Server, which is the most common installation option in the last 10+ years.

Publish C# application with SQL Server database

My application does basic CRUD operations over an external .mdf file. The database file is created separately in SSMS. On my PC, everything works perfectly fine. When I install it on someone else's computer, it refuses to connect to the database. The other PC also has the same database at the exact same location.
The connection string I am using is (in app.config):
conString=Data Source =.\sqlexpress; Initial Catalog = dbName;
Integrated Security = True; Pooling = False
In my code:
dbConnection = new SqlConnection(Settings.Default.conString);
The other PC has SQL Server installed as well. Tried going through almost all the results but almost all of them suggest either
Adding the existing database with the project. I can't seem to do that because when I try that I get an error:
permission denied
I can't rewrite the whole code with a service based database pre-attached to it.

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.

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.

Database backup error

I have this code snippet that creates backup of db:
try
{
string connStr = "<valid connection string>";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
string sqlStmt = String.Format("BACKUP DATABASE InventoryDB TO DISK='{0}'",
DBBackupSaveFileDialog.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
bu2.ExecuteNonQuery();
}
...
problem is that it works fine on developer pc but when i try on different machine it will give this error
Cannot open backup device 'C:\User\Saleh\Documents\12.bak'. Operating system error 5 (failed to rerieve text for this error. Reason: 15105).
You need to make sure the SQL Server service account has write access to C:\Users\Saleh\
First, see what account SQL Server is running as. Control Panel > Administrative Tools > Services, right-click the relevant SQL Server service, hit Properties, and see the account listed on the Log On tab. Now go to Windows Explorer, right-click the folder, hit Properties, and on the Security tab, you can add this user account to the list, and make sure they have write access. If you have further problems with this, your question should probably to to superuser.com as it's becoming a Windows / permissions problem, not a programming one.
Better yet, stop running backups to user folders - use SQL Server's backup folder, which SQL Server already has permissions to write to. If you need to move it later, do that separately.

Categories