Accessing legacy Visual FoxPro database from C# - c#

I have a legacy Visual FoxPro database from which I need to get the data from.
I have DBC, DCT, DCX & FPT files in the database folder.
I installed the Visual FoxPro provider & driver and wrote a short C# program to access the data.
I also made sure the program is running in 32bit mode, since I understood that the VFP driver is 32bit.
However I'm getting the following error:
Additional information: Connectivity error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I made sure that the driver name ("Microsoft Visual FoxPro Driver") as appears in the Windows ODBC 32bit administration tool is specified in the connection string, but it doesn't seem to help.
The code:
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;DRIVER=Microsoft Visual FoxPro Driver;Data Source=mydatabase.dbc;Mode=Read;Collating Sequence=machine");
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from tablename";
var command = yourConnectionHandler.CreateCommand();
command.CommandText = mySQL;
var res = command.ExecuteReader(); // throws the error
yourConnectionHandler.Close();
}
I've been stuck on this for a long time, and have tried everything I could find on the net.
Any idea?

You are saying provider and trying to use OleDbConnection (which is right) but defining an ODBC driver within the connection string. In other words, your connection string is wrong.
using (OleDbConnection cn = new OleDbConnection(
#"Provider=VFPOLEDB;Data Source=c:\MyPath\mydatabase.dbc;Mode=Read;Collating Sequence=machine"))
using (OleDbCommand cmd = new OleDbCommand("select * from tablename", cn))
{
cn.Open();
var reader = cmd.ExecuteReader();
// do something with the reader. ie:
// someDataTable.Load(reader);
cn.Close();
}
It works wonderfully well. In connectionstring you don't need to use the database name, you can just use the tables' path as the data source.

Related

Unspecified Error thrown when opening connection to excel file using OLEDB

I am working on reading in excel files (both .xls and .xlsx) into my program which is being written into a data table. When running the code on one computer it works perfectly fine, when I attempt to run it on another computer I get the following exception:
System.Data.OleDb.OleDbException (0x80004005): Unspecified error at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
This exception is thrown when the program attempts to open the connection to the excel file to read the data in. I have installed 2010 Access Database Engine on the other computer but I still receive the same error when running the code. I was trying to get around the use of the Excel Interop services as it took too long to read in some of the file I am working with. I have done some searching around and have tried various different solutions such as different modifications to the connection string and changing with OLEDB driver I am using to open the connection to the file. This is the code I am using,
private static DataTable ReadExcelData(String path, String TableName)
{
string ConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={path};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
DataTable dt = new DataTable(TableName);
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
DataTable table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String sheetName = table.Rows[0]["TABLE_NAME"].ToString();
using (OleDbCommand comm = new OleDbCommand("SELECT * FROM [" + sheetName + "$]", conn))
using (OleDbDataAdapter da = new OleDbDataAdapter(comm))
da.Fill(dt);
conn.Close();
}
return dt;
}
Figured out the issue, I had to installed the 2016 version of the driver and not the 2010 version which allowed it to work properly.

Can i make sql Database part of c# Project

I have made a sample c# application (First project ive done) Its quite a simple application which uses a database to store data and edit data.
The problem i am having is the program works perfectly fine on my computer but if i publish the application and put it on another computer it cannot use the database as it is not part of the project.
I used connection string
private SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\Ryan\\Documents\\Visual Studio 2015\\Projects\\youtubeLoginTut\\youtubeLoginTut\\data.mdf\"; Integrated Security = True; Connect Timeout = 30");
Which is obviously the path to the database on my computer and will not be the same on the next computer. Is there anyway i could include the database in the package so its referenced from where ever the application sits.
Ive tried shortening the path to for example ..\data.mdf but to no avail and i cant find anything on google so im all out of ideas.
Go easy im very new to c#
Cheers
Ryan
There is a way to get the location of your project in every computer : (inside the bin/debug/)
string path = AppDomain.CurrentDomain.BaseDirectory //example : C:/Users/Ryan/Documents/Visual Studio 2015/Projects/Youtubetut/bin/debug
you just need add the location of the database inside of the project's folder to this path. path will replace your "C:\Users\Ryan\Documents\Visual Studio 2015\Projects\youtubeLoginTut" and make sure to move your database inside the debug folder.
Afeter publiching your database with your project you get the Installtion Path From Deployment byuse :
string sourcePath =System.Reflection.Assembly.GetExecutingAssembly().Location
sourcePath =sourcePath +"\data.mdf";
If it's a simple application you can try to use embeded DB like SQLite. I use it in my application and it works fine.
If you want to use SQLite, let's go step by step.
download the dynamic library System.Data.SQLite.dll for your version of the .NET Framework
link System.Data.SQLite.dll to your project
write a code something like this
Create a table
SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=True;", "./db/mydatabase.sdb"));
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = #"CREATE TABLE Books (BookId int, BookName varchar(255), PRIMARY KEY (BookId));";
cmd.ExecuteNonQuery();
con.Close();
Read the data
using(SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=False;", "./db/mydatabase.sdb")) {
con.Open();
using (SQLiteCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT BookName FROM Books WHERE BookId=1 LIMIT 1;";
using (SQLiteDataReader reader = cmd.ExecuteReader()) {
if (reader.HasRows && reader.Read()) {
oResult = Convert.ToString(reader["BookName"]);
}
reader.Close();
}
}
con.Close();
}

How to import .sql dump file from MySQL to SQLite WPF

I am developing a WPF application.
I created a local SQLite database (using System.Data.SQLite):
SQLiteConnection conn = new SQLiteConnection("Data Source=test.db");
And need to fill it with a MySQL database located in a server. I already got to download the .sql dump file from the server, the problem is that how can i import this file to my local database?
I already searched on the web and found this question the problem is that this mention android...
Any information is welcome.
UPDATE 1:
Opening the .sql file and executing a SQLite command does not import the .sql, here is my code:
string lines = "";
try
{
using (StreamReader sr = new StreamReader(databaseFile))
{
lines += sr.ReadToEnd();
}
} catch (Exception)
{
}
SQLiteConnection conn = new SQLiteConnection("Data Source=test.db");
conn.Open();
var command = conn.CreateCommand();
command.CommandText = lines;
command.ExecuteNonQuery();
conn.Close();
The application crashes with the next error:
Additional information: SQL logic error or missing database
near "AUTO_INCREMENT": syntax error
They are different SQL dialects so that solution is going to give you quite a bit of a headache.
If this is a one time activity I would use a (free) tool like:
http://www.sql-workbench.net/
that has a Data Pump tool that allows you to move data across different databases.

Connection String Problem Oracle .Net

I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.

The 'Microsoft .Jet.OLEDB.4.0' provider is not registered on the local machine

I'm trying to import some data from excel into a database . i got the following code from http://www.davidhayden.com/blog/dave/archive/2006/05/31/2976.aspx . I have a x86 arhitecture so that's not the problem . when i run the code the program says at connection.Open(); that The 'Microsoft .Jet.OLEDB.4.0' provider is not registered on the local machine. Any ideas ?
string excelConnectionString = #"Provider=Microsoft
.Jet.OLEDB.4.0;Data Source=C://suc.xls;Extended
Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select ID,Data FROM [Data$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=.;Initial Catalog=Test;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelData";
bulkCopy.WriteToServer(dr);
}
}
}
If you are running the code on a 64 bit machine, and its a web project, then open IIS, right click on the Application pool and click on Advanced settings. Set the second property from the top: Enable 32 bit application to True, that should fix the problem.
I assume that both that the correct version of Excel and the Interop.Excel.dll file is present on the machine generating this error? Since the Jet provider is found in the interop DLL I think that is the most likely explanation.

Categories