Distributed Transaction Coordinator - msdtc

I am trying make a database transaction(inserting records) across multiple system. So, I decided to use System.Transaction Namespace in .net. I configured MSDTC on both system(But i dont know whether i configured correctly). My transaction has two insert query one will execute at local system. another, will execute at some other system in a local network.
First insert query work successfully but second one raise a error like :
Message = "The transaction has already been implicitly or explicitly committed or aborted."
Here is my Code
using (TransactionScope txSc = new TransactionScope())
{
//vrm = new VolatileRM();
//vrm.SetMemberValue(3);
try
{
using (SqlConnection cn = new SqlConnection(connStr1))
{
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "Insert into empdetail Values ('YYY')";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "Insert into stu Values ('23','senthil')";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
txSc.Complete();
}
catch (Exception e)
{
txSc.Dispose();
}
}

First check that the DTC is actually running (on local and remote system), and then try setting both DTC's authentication to 'anonymous' to see if it's a permissions problem.
Also, check the firewall settings on remote and local machine.
Check out this FAQ: Distributed Transaction Coordinator(MSDTC) and Transaction FAQ
Configuring MS DTC Services
Enable Network Access Securely for MS DTC
Enable Firewall Exceptions for MS DTC
Related to this SO question: HRESULT: 0x8004D00E using TransactionScope - C#

Related

Entity Framework Core manual sql query within an existing transaction

Similar to the question answered here https://stackoverflow.com/a/42932812/1321510 we need to execute a raw sql query. For the query we don't have any db context model (so any .FromSql answers won't work for us). However we need to execute it within an existing transaction (created with context.Database.BeginTransaction()). All solutions found on SO do not work with existing transactions.
Example:
var connection = context.Database.GetDbConnection();
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.Transaction = context.Database.CurrentTransaction.GetDbTransaction();
var executeReader = command.ExecuteReader();
var values = new object[executeReader.FieldCount];
if (!executeReader.Read())
{
return values;
}
executeReader.GetValues(values);
return values;
}
}
Commiting the transaction then throws System.InvalidOperationException: 'This MySqlConnection is already in use. See https://fl.vu/mysql-conn-reuse'.
The provided link in the exception doesn't seem helpful at all, since we're neither using async nor using the connection whilst reading from it.
We're using Pomelo.EntityFrameworkCore.MySql as the database connector.

Why there are many connections in this case (MySQLNonTransientConnectionException)

I am getting an exception using PreparedStatement to select.
Got an exception accessing TestCase data! null
Problem to connect.
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Too many connections
Here is my code:
public Integer getTypeByInputAndProblemId(String inputTestCase, Long problemId) {
String sql = "SELECT type FROM test_case where problem_id= ? and input= ?";
Integer type = 0;
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1, problemId);
ps.setString(2, inputTestCase);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
type = new Integer(rs.getInt("type"));
}
rs.close();
ps.close();
} catch (Exception e) {
System.err.println("Got an exception accessing TestCase data! " + e.getMessage());
}
return type;
}
In line PreparedStatement ps = connection.prepareStatement(sql);
my problem is because connection sometimes is Null (the debug shows this).
I'm guessing this is because of many connections, but I don't know why this is happening.
I would like some help, please!
Yes, the issue happens because your server is reaching the max number of multiple connections accepted by your MySQL Server.
First, you need to see if you have a proper number configured in MySQL for multiple connections: max_connections. If this look low to you, you can increase this number in order to "fix" this issue.
Secondly, if the number makes sense, you're probably using more connections than you think you are. Probably because you're opening connections in your application and not closing them.
Check how many multiple connections your server have used so far.
show status like 'Max_used_connections';
This number is reset when you restart your database service.

ClassNotFoundException: com.mysql.jdbc.GoogleDriver

I wonder how come this error is thrown while hosting my project in APP ENGINE, I have added lots of logging just for analysis sake. When I use the com.mysql.jdbc.Driver using ip from my local it works. Kindly help !!
String name = "Vinodh";
String url = null;
try {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://xxxxxxx:xxxxxx/vinodh?user=root&password=xxxxxx";
// Statements allow to issue SQL queries to the database
log.info("Initiate Connection");
Connection conn = DriverManager.getConnection(url);
log.info("Got Connection");
Statement statement = conn.createStatement();
// Result set get the result of the SQL query
ResultSet resultSet = statement
.executeQuery("select * from Family");
log.info("Entering While");
while(resultSet.next()){
log.info("Entered While");
String test = resultSet.getString("Name");
System.out.println(test);
name = test+test+test;
}
As shwown in this tutorial, during development you should use the normal mysql driver and only appengine use the Google mysql driver
if (SystemProperty.environment.value() ==
SystemProperty.Environment.Value.Production) {
// Load the class that provides the new "jdbc:google:mysql://" prefix.
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://your-project-id:your-instance-name/guestbook?user=root";
} else {
// Local MySQL instance to use during development.
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://127.0.0.1:3306/guestbook?user=root";
}
Also double check that you have enabled MySQL Connector/J for your application (it's not done by default)
https://developers.google.com/appengine/docs/java/cloud-sql/#enable_connector_j
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
...
<use-google-connector-j>true</use-google-connector-j>
</appengine-web-app>
Appearently they removed this quietly. It's not even in the docs of appengine-web.xml anymore.
Use the standard com.mysql.jdbc.Driver but update your JDBC url for:
jdbc:mysql://google/[your-db-schema]
?user=root
&password=[your-db-passord]
&socketFactory=com.google.cloud.sql.mysql.SocketFactory
&cloudSqlInstance=[your-db-project-id]:[your-db-region]:[your-db-intance]
Add also to your gradle:
dependencies {
...
implementation("mysql:mysql-connector-java:8.0.29")
implementation("com.google.cloud.sql:mysql-socket-factory-connector-j-8:1.5.0")
}
Note the "google" in the URI. There's no place in the docs saying that you need it, but you have to.
Github official page guide

MySqlClient: SaveChanges in ASP.NET doesn't update DB table

I'm using MySql database in ASP.NET MVC 4 project with MySqlClient (MySQL Connector .NET ).
In the References are dlls: MySql.Data, MySql.Data.Entry, MySql.Web
Selects from MySql database executes successfully, but inserts and updates are doesn't executes. No errors, no exceptions.
code №1:
var connectionString = "Server=my_server;Uid=my_login;Pwd=my_password;Old Guids=true;persist security info=True;database=clientest;allow zero datetime=True;convert zero datetime=True";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
String commandText = "update testdb.visit set doctor_spec='dentist' where visit_id = 2;";
MySqlCommand cmd = new MySqlCommand(commandText, conn);
cmd.CommandType = System.Data.CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
}
No errors, no exception, but the table hasn't updates
code №2
using (var db = new MySqlDBEntities())
{
var vx = (from v in db.visit where v.visit_id == 1 select v).FirstOrDefault();
vx.doctor_spec = "dentist";
db.SaveChanges();
}
No errors, no exception, but the table hasn't updates.
What's wrong? Maybe another way for using MySql in ASP.NET MVC projects?
P.S. Sorry for my poor English :(
check connection in web config and find Correctly Data File
After Do Save Change Successfully any Edited Or New Entity Changes is Update
check this code too
* from v in db.visit /* db.visits */ where *

I need to write an Access 97 .mdb file

I need to export data from a SQL server 2005 DB to an Access 97 .mdb file. The client that needs it, needs it to be Access 97 because the system that they're importing it into requires Access 97 file format (don't get me started). Any suggestions how to write an old-timey Access file from SQL or .Net (or VB6 or Ruby or Python..)?
Thanks in advance,
Lee
I'd let Sql 2005 do it for you.
In the Sql Management Stuidio, right-click on your source database, then Tasks, then Export Data. You can use this to export directly into your Access database, just follow the prompts. Or you can output it to a file format you can use to put into Access.
What you need to do is export into an Access file for whatever Access version you have installed (as long as it's 2000...2003; Access 2007 can't write to Access 97 files). I assume you already know how to do this.
Then you can create an Access object via COM and ask it to convert your new .mdb file into a new Access 97 database. In VBScript, the code looks like this (adjust as necessary if you're using VBA, VB.Net, or another language):
const acFileFormatAccess97 = 8
dim app
set app = CreateObject("Access.Application")
app.ConvertAccessProject "y:\mydatabase.mdb", "y:\mydatabase97.mdb", acFileFormatAccess97
If you have Access 97 installed, the above command won't work, because Access didn't have the ConvertAccessProject function in that version. Of course, you don't need to convert the file in that case anyway.
This might give you a starting point.
And this article is a bit old, but you might be able to pick up something. I can only find those using Jet 4.0 which is compatible w/ Access 2000 as in the previous article. Using the MS Access driver might give you what you want.
After you created the database, use regular ODBC / OLE DB related stuffs in ADO.NET to create your table and populate them w/ your data.
This is a great question! I've actually wanted to be able to do this kind of thing in a programmatic way, but in the past I've had nothing but trouble coming up with it. However, have matured a bit in my .NET skills over the years, I thought I would take a shot at writing a solution that could be executed as a Console app. This can be implemented either as a scheduled task on the windows server or sql server (using the Sql Server agent). I don't see why this couldn't be automated from the Sql Server without the following code, but I really had fun with this, so I just have to put it out there. The table in both Sql and Access is a list of dogs, with an ID, a name, a breed, and a color. Generic stuff. This actually works on my desktop between a local instance of Sql Server and Access (2007, but I don't know why it wouldn't work with 97). Please feel free to critique.
BTW, has the following:
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
Here:
static void Main(string[] args)
{
SqlConnectionStringBuilder cstrbuilder = new SqlConnectionStringBuilder();
cstrbuilder.DataSource = "localhost";
cstrbuilder.UserID = "frogmorton";
cstrbuilder.Password = "lillypad99";
cstrbuilder.InitialCatalog = "Dogs";
SqlConnection sconn = new SqlConnection(cstrbuilder.ToString());
sconn.Open();
SqlCommand scmd = new SqlCommand("select * from Dogs", sconn);
SqlDataReader reader = scmd.ExecuteReader();
if (reader.HasRows)
{
OleDbConnectionStringBuilder sb = new OleDbConnectionStringBuilder();
sb.Provider = "Microsoft.Jet.OLEDB.4.0";
sb.PersistSecurityInfo = false;
sb.DataSource = #"C:\A\StackOverflog\DogBase.mdb";
OleDbConnection conn = new OleDbConnection(sb.ToString());
conn.Open();
OleDbCommand cmd = new OleDbCommand("Delete from Dogs", conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
OleDbConnection conn2 = new OleDbConnection(sb.ToString());
conn2.Open();
OleDbCommand icmd = new OleDbCommand("Insert into dogs (DogID, DogName, Breed, Color) values ({0}, '{1}', '{2}', '{3}');", conn2);
icmd.CommandType = CommandType.Text;
while (reader.Read())
{
string insertCommandString =
String.Format("Insert into dogs (DogID, DogName, Breed, Color) values ({0}, '{1}', '{2}', '{3}');"
, reader.GetInt32(0)
, reader.GetString(1)
, reader.GetString(2)
, reader.GetString(3)
);
icmd.CommandText = insertCommandString;
icmd.ExecuteNonQuery();
}
conn2.Close();
}
sconn.Close();
}
The best way to do this is via PInvoke You will need to pass the CREATE_DBV3 parameter to SqlConfigDataSource(). Here is the code taken from JetSqlUtil.cs of my OSS Project PlaneDisaster.NET:
#region PInvoke
private enum ODBC_Constants : int {
ODBC_ADD_DSN = 1,
ODBC_CONFIG_DSN,
ODBC_REMOVE_DSN,
ODBC_ADD_SYS_DSN,
ODBC_CONFIG_SYS_DSN,
ODBC_REMOVE_SYS_DSN,
ODBC_REMOVE_DEFAULT_DSN,
}
private enum SQL_RETURN_CODE : int
{
SQL_ERROR = -1,
SQL_INVALID_HANDLE = -2,
SQL_SUCCESS = 0,
SQL_SUCCESS_WITH_INFO = 1,
SQL_STILL_EXECUTING = 2,
SQL_NEED_DATA = 99,
SQL_NO_DATA = 100
}
[DllImport("ODBCCP32.DLL",CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int SQLConfigDataSource (int hwndParent, ODBC_Constants fRequest, string lpszDriver, string lpszAttributes);
[DllImport("ODBCCP32.DLL", CharSet = CharSet.Auto)]
private static extern SQL_RETURN_CODE SQLInstallerError(int iError, ref int pfErrorCode, StringBuilder lpszErrorMsg, int cbErrorMsgMax, ref int pcbErrorMsg);
#endregion
internal static string GetOdbcProviderName()
{
if (string.IsNullOrEmpty(OdbcProviderName))
{
var odbcRegKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\ODBC\\ODBCINST.INI\\ODBC Drivers", false);
var drivers = new List<string>(odbcRegKey.GetValueNames());
if (drivers.Contains("Microsoft Access Driver (*.mdb, *.accdb)"))
{
OdbcProviderName = "Microsoft Access Driver (*.mdb, *.accdb)";
}
else if (drivers.Contains("Microsoft Access Driver (*.mdb)"))
{
OdbcProviderName = "Microsoft Access Driver (*.mdb)";
}
else
{
//TODO: Condider checking for 32 versus 64 bit.
//TODO: Find a better exception type. http://stackoverflow.com/questions/7221703/what-is-the-proper-exception-to-throw-if-an-odbc-driver-cannot-be-found
throw new InvalidOperationException("Cannot find an ODBC driver for Microsoft Access. Please download the Microsoft Access Database Engine 2010 Redistributable. http://www.microsoft.com/download/en/details.aspx?id=13255");
}
}
/// <summary>
/// Creates an Access 2003 database. If the filename specified exists it is
/// overwritten.
/// </summary>
/// <param name="fileName">The name of the databse to create.</param>
/// <param name="version">The version of the database to create.</param>
public static void CreateMDB (string fileName, AccessDbVersion version = AccessDbVersion.Access2003) {
;
if (File.Exists(fileName)) {
File.Delete(fileName);
}
string command = "";
switch (version)
{
case AccessDbVersion.Access95:
command = "CREATE_DBV3";
break;
case AccessDbVersion.Access2000:
command = "CREATE_DBV4";
break;
case AccessDbVersion.Access2003:
command = "CREATE_DB";
break;
}
string attributes = String.Format("{0}=\"{1}\" General\0", command, fileName);
int retCode = SQLConfigDataSource
(0, ODBC_Constants.ODBC_ADD_DSN,
GetOdbcProviderName(), attributes);
if (retCode == 0)
{
int errorCode = 0 ;
int resizeErrorMesg = 0 ;
var sbError = new StringBuilder(512);
SQLInstallerError(1, ref errorCode, sbError, sbError.MaxCapacity, ref resizeErrorMesg);
throw new ApplicationException(string.Format("Cannot create file: {0}. Error: {1}", fileName, sbError));
}
}
If you need to do this from a 64 bit version of SQL server you will need the 64 bit version of Office 2010 or the Microsoft Access Database Engine 2010 Redistributable installed.
I think it's crazy to do it from SQL Server. Just create an ODBC DSN for your SQL Server and import the tables into your Access 97 MDB and be done with it. The only reason you might want to do it otherwise is if you want to automate it and do it repeatedly, but that can be automated in Access, too (TransferDatabase can do ODBC imports), and will take only as many lines of code as there are tables to import.