I've encountered a quite strange behavior of ADO.NET / Access 2007.
I run my C# 2008 program (target framework .NET 2.0) on PC1.
PC1 has a network share on PC2 (\PC2\Temp mapped as X:)
On PC2 in Temp there is the access database file xy.mdb
The program opens a OleDbConnection to X:\xy.mdb. Works fine.
Then while the program is still running I drop the share on PC2.
(Windows Explorer on PC1 tells me the share X: is lost)
I renamed the database file on PC2, so no new connection should be possible.
But the program can still query the database !
(via OleDbCommand.ExecuteReader() or ExecuteNonQuery())
Has anyone an explanation for me ?
Is the whole database latched ?
And can I prevent this so that I get an OleDbException when the share is dropped and I try to query the no longer available database ?
Thanks for any help,
Ralf
I tried to reproduce the issue with the following code and a sample access db...not matter how I tried (sahre or mapped drive) i always got the exception:
Unhandled Exception:
System.Data.OleDb.OleDbException: The
Microsoft Jet database engine cannot
find the input table or query
'somejunk'. Make sure it exists and
that its name is spelled correctly.
which is expected. You should re-examine you environment to be 100%.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
namespace AccessOverShare
{
class Program
{
static void Main(string[] args)
{
int ct = 0;
using(OleDbConnection oleDbConnection = new OleDbConnection())
{
//oleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\127.0.0.1\\share\\test.mdb.";
oleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\\test.mdb.";
oleDbConnection.Open();
using(OleDbCommand oleDbCommand = oleDbConnection.CreateCommand())
{
oleDbCommand.CommandType = CommandType.Text;
oleDbCommand.CommandText = "select junkid, junktext from somejunk";
using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader(CommandBehavior.Default))
{
ct = 0;
while(oleDbDataReader.Read())
{
ct++;
Console.WriteLine("{0:0000}", oleDbDataReader["junkid"]);
}
}
Console.WriteLine();
Console.WriteLine(ct);
}
Console.WriteLine();
Console.WriteLine();
Console.Write("kill the share then press enter to continue");
Console.ReadLine();
using (OleDbCommand oleDbCommand = oleDbConnection.CreateCommand())
{
oleDbCommand.CommandType = CommandType.Text;
oleDbCommand.CommandText = "select junkid, junktext from somejunk";
using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader(CommandBehavior.Default))
{
ct = 0;
while (oleDbDataReader.Read())
{
ct++;
Console.WriteLine("{0:0000}", oleDbDataReader["junkid"]);
}
}
Console.WriteLine();
Console.WriteLine(ct);
}
}
}
}
}
Related
MySQLBackup.net works fine on Windows applications, but not in Xamarin (tested with exact same code).
Is there any workaround or alternatives that I can use ? I'm really lost...
I want to backup my database from a Linux (Debian9) MariaDB server, so I found MySqlBackup.NET, but nothing can make it work with Xamarin.
There's my code to backup (works in windows console app):
// Use MySqlBackup.Net to backup database
using (var conn = new MySqlConnection("myconnstring"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
conn.Open();
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
mb.ExportToFile(Constants.EXPORT_PATH + "/dolibarr_" + identifier + "dataBackup.sql");
conn.Close();
}
}
}
Getting exception: The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
I have a MySQL 5.7.20-log server running on Windows Server 2012.
I have created two simple applications:
1. C# Windows Forms application (.NET) using 6.10.4 Connector (NuGet package)
private void Form1_Load(object sender, EventArgs e)
{
TestMySqlConnection();
}
private void TestMySqlConnection()
{
string dbConnectionString =
" Data source = 192.168.0.12;" +
" Database = rcp;" +
" User Id = rcp;" +
" Password = *******;" +
" SslMode = None;";
using (MySqlConnection dbConnection = new MySqlConnection(dbConnectionString))
{
dbConnection.Open();
}
}
This application runs without problems.
2. Universal Windows Platform application (UWP /.NetCore) using 6.10.4 Connector (NuGet package)
private void Page_Loaded(object sender, RoutedEventArgs e)
{
TestMySqlConnection();
}
private void TestMySqlConnection()
{
string dbConnectionString =
" Data source = 192.168.0.12;" +
" Database = rcp;" +
" User Id = rcp;" +
" Password = *******;" +
" SslMode = None;";
using (MySqlConnection dbConnection = new MySqlConnection(dbConnectionString))
{
dbConnection.Open();
}
}
This application does not work and throws an Exception.
Exception:
Exception has been thrown by the target of an invocation.
InnerException:
FileNotFoundException: Could not load file or assembly 'System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Any help would be appreciated.
Connecting to MySql database directly in UWP is a new feature which is introduced from .NET Standard 2.0.
For the previous Universal Windows Platform, it only supports .NET Standard 1.4.
So, that's the issue you're facing. I also can reproduce it on my side if I set my project's target version is 16299, but min version is the previous version (15063,14393 etc).
To solve this issue, you would need to make the project's target version and min version are 16299.
I've developed web applications in PHP for a few years and would like to learn about ASP.Net. I've installed VS2013 and have created an ASP.Net Web Application. I tried playing around with something that I found on wait for it W3Schools just because I knew it would be as simple as simple could be but it caused me some errors. I was trying to "connect" to an Access file in the wwwroot directory by using System.Data.OleDb but I had some problems.
My question is: Is there a simplistic way like in PHP where you have PHPMyAdmin to manage the database and then connect via something simple like $conn = new mysqli('localhost', 'user', 'password', 'db'); but for ASP.Net?
I'm struggling to find beginner level support for this on the web and would like to figure it out asap!
David, isnt's going to be "simple" as PHP, remember that VS2013 it's a server side language, more strong and complex.
I recommend to you the next:
Work with objects.
Here is some code may help you.
C#:
public System.Data.DataSet GetQuery(string _QueryComm){
System.Data.DataSet objResult = new System.Data.DataSet();
OleDbDataAdapter objAdapter;
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;";
objCon = new OleDbConnection(strProvider);
objCon.Open();
try
{
objAdapter = new OleDbDataAdapter(_QueryComm, objCon);
objAdapter.Fill(objResult);
objAdapter.Dispose();
objCon.Close();
}
catch (Exception e)
{
// Some exception handler
}
return objResult;}
Usage:
DataSet datainfo = GetQuery("select * from table");
VB:
Public Function GetQuery(strCommandQuery as String) As System.Data.DataSet
Dim objResult As System.Data.DataSet = New System.Data.DataSet
Dim objAdapter As OleDbDataAdapter
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;"
objCon = New OleDbConnection(strProvider)
objCon.Open()
Try
objAdapter = New OleDbDataAdapter(strCommandQuery, objCon)
objAdapter.Fill(objResult)
objAdapter.Dispose()
objCon.Close()
Catch ex As System.Exception
' Some exception handler
End Try
Return objResult End Function
Usage:
Dim datainfo as DataSet = GetQuery("select * From table")
Let me know if it's work for you.
I've been searching for a solution for days now and I still cant seem to find one. I have a problem acquiring a connection in my Script component. I need to query my database to retrieve an Id to be used before I insert it in the
public override void AcquireConnections(object Transaction)
{
connMgr = base.Connections.Connection;
conn = (SqlConnection)connMgr.AcquireConnection(null);
}
I get an exception here.
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
Any solutions?
For those that want to be able to do this in a Script Component:
Double Click the Script component to open the "Script Transformation Editor"
Click the "Connection Managers" list item.
Add a new Connection Manager. Select an existing ADO.NET connection manager.
Click on the "Script" list item and then the "Edit Script..." button.
You can do something like this inside your script:
using (SqlConnection connection = this.Connections.Connection.AcquireConnection(null) as SqlConnection)
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT [Value] FROM dbo.MyTable";
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ProfanityWords.Add(reader.GetValue(0).ToString());
}
}
}
this.Connections.Connection.ReleaseConnection(connection);
}
ADO.NET connection manger should be created and refer into the code to type cast to the SqlConnection. If you dont have the ADO.NET connection in your SSIS pakcage you will get the TypeCast exception. Following steps should be used if you want to use the SqlConnection.
Create the ADO.NET connection.
Use the following line in your code.
var connObj = Dts.Connections["ADO.NETConnectionName"].AcquireConnection(null);
var sqlConn = (SqlConnection)connObj;
Once you done with your SQL connection. Use the following code to Close/ Release your connection.
Dts.Connections["ADO.NETConnectionName"].ReleaseConnection(connObj);
Hope this helps.
I have a huge collection of visual foxpro dbf files that I would like to convert to csv.
(If you like, you can download some of the data here. Click on the 2011 link for Transaction Data, and prepare to wait a long time...)
I can open each table with DBF View Plus (an awesome freeware utility), but exporting them to csv takes a few hours per file, and I have several dozen files to work with.
Is there a program like DBF View plus that will allow me to set up a batch of dbf-to-csv conversions to run overnight?
/Edit: Alternatively, is there a good way to import .dbf files straight into SQL Server 2008? They should all go into 1 table, as each file is just a subset of records from the same table and should have all the same column names.
Load up your list of FoxPro files in an array/list then call the ConvertDbf on each to convert them from FoxPro to csv files. See the c# console application code below...
Credit c# datatable to csv for the DataTableToCSV function.
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
namespace SO8843066
{
class Program
{
static void Main(string[] args)
{
string connectionString = #"Provider=VFPOLEDB.1;Data Source=C:\";
string dbfToConvert = #"C:\yourdbffile.dbf";
ConvertDbf(connectionString, dbfToConvert, dbfToConvert.Replace(".dbf", ".csv"));
Console.WriteLine("End of program execution");
Console.WriteLine("Press any key to end");
Console.ReadKey();
}
static void DataTableToCSV(DataTable dt, string csvFile)
{
StringBuilder sb = new StringBuilder();
var columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => field.ToString()).ToArray();
for (int i =0;i < fields.Length;i++)
{
sb.Append("\"" + fields[i].Trim() );
sb.Append((i != fields.Length - 1) ? "\"," : "\"");
}
sb.Append("\r\n");
}
File.WriteAllText(csvFile, sb.ToString());
}
static void ConvertDbf(string connectionString, string dbfFile, string csvFile)
{
string sqlSelect = string.Format("SELECT * FROM {0}", dbfFile);
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(sqlSelect, connection))
{
DataSet ds = new DataSet();
da.Fill(ds);
DataTableToCSV(ds.Tables[0], csvFile);
}
}
}
}
}
In that case, SQL-Server I think has a capability of connecting to foxpro tables. I'm not exactly sure how as I've never done it recently (last time using SQL-Server about 8+ yrs ago). I'm sure there are other threads out there that can point you to connecting SQL-Server to VFP.
I quickly searched and saw this thread
In addition, you might need the latest OleDb provider to establish the connection which I've also posted in a thread here. This thread also shows a sample of the connection string information you may need from SQL-Server. The data source information should point to the PATH where the .DBF files are found, and not the specific name of the .DBF you are trying to connect to.
Hope this helps you out.
This works very well and thanks for the solution. I used this to convert some visual foxpro dbf tables to flat files. With these tables, there is the additional challenge of converting fields of type Currency.
Currency fields are a 64-bit (8 byte) signed integer amidst a 36 element byte array starting at the 27th position. The integer is then divided by 1000 to get 4-decimal precision equivalent.
If you have this type of field, try this inside the fields FOR loop
if (("" + fields[i]).Equals("System.Byte[]"))
{
StringBuilder db = new StringBuilder();
byte[] inbytes = new byte[36];
inbytes = ObjectToByteArray(fields[i]);
db.Append("" + (double)BitConverter.ToInt64(inbytes,27)/1E4);
sb.Append("\"" + db);
}
With the following helper method
private static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
Check out my answer to Foxbase to postrgresql data transfer. (dbf files reader).