Transaction for different databases - c#

I use 2 different dlls to connect to 2 database in my project . each dll has it's own DAL layer .
now in a page I need to insert a set of related data into these 2 databases . I want to use transaction to make sure data are inserted correctly . but as I just have access to public methods of Insert() of each assembly , not the ADO.net codes . how can I handle this situation ? is there anything like this in c# ?
beginTransaction(){
dll1.class.Insert(data);
dll2.className.Insert(relatedData);
....
}

You are looking for the TransactionScope class:
Makes a code block transactional.
Example usage:
using (var tx = new TransactionScope())
{
dll1.class.Insert(data);
dll2.className.Insert(relatedData);
tx.Complete(); // if not executed, transaction will rollback
}
As #Anders Abel commented, the servers running the databases involved in the transaction will need the MSDTC service to be running and configured correctly on both the DB servers and the client machines. The DTCPing utility is very helpful in this regard.
As Steve B commented, there is an assumption here that all the databases and the associated drivers support distributed transaction enlistment. Check your documentation...

Related

How to use Transaction Scope rollback for multiple database connections within the same NUnit database test

I am creating a test that injects data in two separate databases(in separate sql servers), then do some action and verify data on a third database.
Now I would like to teardown all the test data from the three databases after each test, but I am unable to use Transaction Scope when my tests interact with multiple databases
Can anyone please help in how to use transaction scope / rollback feature for multiple connections?
I tried using Transaction scope using the following code, this works fine on the tests where only one database connection is created however this does not work on the test where it creates three connections. I use Nunit 3 and .Net core for one project & .Net Framework 4.7 for another separate project, the below error is when using .Net Core
private TransactionScope transaction;
[SetUp]
public void BeforeTest()
{
transaction = new TransactionScope();
}
[TearDown]
public void AfterTest()
{
transaction.Dispose();
}
I get an error " System.PlatformNotSupportedException : This platform does not support distributed transactions." In my test I use Entity Framework DBcontext to interact with databases. Any help would be highly appreciated. Thanks

How to implement single transaction in Entity Framework 5 with both context SQL DB and DB2

I am trying to implement both DbContext (SQLDBContext & DB2Context) in single transaction but every time facing an issue related to DB2.
It works fine with SQL but throws error when trying to access DB2.
The exception is :
Error in DB2Entities getter.Communication with the underlying transaction manager has failed.
The MSDTC transaction manager was unable to pull the transaction from the source transaction manager due to communication problems. Possible causes are: a firewall is present and it doesn't have an exception for the MSDTC process, the two machines cannot find each other by their NetBIOS names, or the support for network transactions is not enabled for one of the two transaction managers. (Exception from HRESULT: 0x8004D02B)
Please help me to implement both the DB transactions under single Transaction OR
if one of them fails then both should rollback.
Code is like:
var option = new TransactionOptions
{
IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
Timeout = TimeSpan.FromSeconds(60)
};
using (var scopeOuter = new TransactionScope(TransactionScopeOption.Required, option))
{
SQLDBContext.Table.AddSomething();
SQLDBContext.SaveChanges();
using (var scopeInner = new TransactionScope(TransactionScopeOption.Required, option))
{
DB2Context.Table.AddSomething();
DB2Context.SaveChanges();
scopeInner.Complete();
}
scopeOuter.Complete();
}
Thank you!
With DB2, you will have to enable XA Transactions for MSDTC. Since you are also using multiple databases, you may have to also enable Network DTC Access (see image below).
To change these settings open the Component Services management snap-in (Administrative Tools -> Component Services, or run comexp.msc). Then under Computers -> My Computer -> Distributed Transaction Coordinator, right click on "Local DTC" and hit properties. You will get the screen below.

Error - LINQ/TransactionScope with multiple database connections

I'm having a helluva time wrapping a couple transactions to 2 different databases on the same SQL Server. I initially was having trouble with network DTC access and I resolved that. Now, the error that I continue to get is "Communication with the underlying transaction manager has failed."
We have some customer profiles in a database and when these profiles become outdated we want to move them to an 'archive' database for storage. The move is simply (italics for humor) adding them to the archive database and deleting them from the main/live database. I have a DataContext for each database. The code below performs the Add and then gets the error on the Delete when trying to use the second DataContext. I've only been working with LINQ for a few months and I've scoured articles for the past couple of days. I'd like to know if anything is wrong with my code or if there is still something not configured properly with the DTC or ???
We're running on VMware for my workstation and the server.
- Workstation is Windows 7 SP1
- Server is Windows and SQL Server 2008R2
Routine for the 'Move':
private int MoveProfileToArchiveDB( int iProfileId )
{
int rc = RC.UnknownError;
// get new Archive profile object
ProfileArchive.ProfileInfo piArchive = new ProfileArchive.ProfileInfo();
// 'Live' DataContext
using ( ProfileDataContext dbLive = new ProfileDataContext() )
{
// get Live profile
ProfileInfo piLive = ProfileInfo.GetProfile( dbLive, iProfileId );
// copy Live data to Archive profile object... including the id
ProfileArchive.ProfileInfo.CopyFromLive( piLive, piArchive, true );
}
bool bArchiveProfileExists = ProfileArchive.ProfileInfo.ProfileExists( piArchive.id );
// make the move a transaction...
using ( TransactionScope ts = new TransactionScope() )
{
// Add/Update to Archive db
using ( ProfileArchiveDataContext dbArchive = new ProfileArchiveDataContext() )
{
// if this profile already exists in the Archive db...
if ( bArchiveProfileExists )
{
// update the personal profile in Archive db
rc = ProfileArchive.ProfileInfo.UpdateProfile( dbArchive, piArchive );
}
else
{
// add this personal profile to the archive db
int iArchiveId = 0;
piArchive.ArchiveDate = DateTime.Now;
rc = ProfileArchive.ProfileInfo.AddProfile( dbArchive, piArchive, ref iArchiveId );
}
// if Add/Update was successful...
if ( rc == RC.Success )
{
// Delete from the Live db
using ( ProfileDataContext dbLive = new ProfileDataContext() )
{
// delete the personal profile from the Profile DB
rc = ProfileInfo.DeleteProfileExecCmd( dbLive, iProfileId ); // *** ERROR HERE ***
if ( rc == RC.Success )
{
// Transaction End (completed)
ts.Complete();
}
}
}
}
}
return rc;
}
NOTES:
I have a few different methods for the Delete and they all work outside the TransactionScope.
ProfileInfo is the main profile table and is roughly the same for both Live and Archive databases.
Any help is greatly appreciated! Thanks much...
Rather than continue criss cross comments, I decided to post this as an answer instead.
don't use error codes. That's what exceptions are for. The code flow is more difficult to read and error code returns invite to be ignored. Exceptions make the code easier to read and far less error prone.
If you use a TransactionScope, remember to always set the isolation level explicitly. See using new TransactionScope() Considered Harmful. The implicit isolation level of SERIALIZABLE is almost never called for and has tremendous negative scale impact.
Transaction escalation. Whenever multiple connections are opened inside a transaction scope they can escalate the transaction to a distributed transaction. The behavior differ from version to version, some have tried to document it, eg. TransactionScope: transaction escalation behavior:
SQL Server 2008 is much more intelligent then SQL Server 2005 and can
automatically detect if all the database connections in a certain
transaction point to the same physical database. If this is the case,
the transaction remains a local transaction and it is not escalated to
a distributed transaction. Unfortunately there are a few caveats:
If the open database connections are nested, the transaction is still
escalated to a distributed transaction.
If in the transaction, a
connection is made to another durable resource, the transaction is
immediately escalated to a distributed transaction.
Since your connection (from the two data contextes used) point to different databases, even on SQL Server 2008 your TransactionScope will escalate to a distributed transaction.
Enlisting your application into DTC is harmful in at least two ways:
throughput will sink through the floor. A database can support few thousand local transactions per second, but only tens (maybe low hundreds) of distributed transactions per second. Primarily this is because of the complexity of two phase commit.
DTC requires a coordinator: MSDTC. The [security enhancements made to MSDTC] make configuration more challenging and it certainly is unexpected for devs to discover that MSDTC is required in their app. The steps described in the article linked are probably what you're missing right now. For Windows Vista/Windows 7/Windows Server 2008/Windows Server 2008R2 the steps are described in MSDTC in Windows Vista and Windows Server 2008, in How to configure DTC on Windows 2008 and other similar articles.
Now if you fix MSDTC communication following the articles mentioned above, your code should be working, but I still believe this archiving should not occur in the client code running EF. There are far better tools, SSIS being a prime example. A nightly scheduled job running SSIS would transfer those unused profiles far more efficiently.

How to know the state of an sql instance in a c# program

I have one database with one mirror in high-safety mode (using a witness server at the moment but planing to take him out), this database will be used to store data gathered by a c# program.
I want to know how can I check in my program the state of all the SQL instances and to cause/force a manual failover.
is there any c# API to help me with this?
info: im using sql server 2008
edit: I know I can query sys.database_mirroring but for this I need the principal database up and runing, I would like to contact each sql instance and check their status.
Use SQL Server Management Objects (SMO).
SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server. SQL Server Replication Management Objects (RMO) is a collection of objects that encapsulates SQL Server replication management.
I have used SMO in managed applications before - works a treat.
To find out the state of an instance, use the Server object - is has a State and a Status properties.
after playing around a bit I found this solution (i'm not if this is a proper solution, so leave comments plz)
using Microsoft.SqlServer.Management.Smo.Wmi;
ManagedComputer mc = new ManagedComputer("localhost");
foreach (Service svc in mc.Services) {
if (svc.Name == "MSSQL$SQLEXPRESS"){
textSTW.Text = svc.ServiceState.ToString();
}
if (svc.Name == "MSSQL$TESTSERVER"){
textST1.Text = svc.ServiceState.ToString();
}
if (svc.Name == "MSSQL$TESTSERVER3") {
textST2.Text = svc.ServiceState.ToString();
}
}
this way i'm just looking for the state of the services (Running/Stoped) and is much faster, am I missing something?

DotNetNuke UserController.GetUser(PortalId,UserId, False) inside TransactionScope throws TransactionAbortedException

Either DotNetNuke UserController.GetUser(PortalId,UserId,false) or UserController.ValidateUser(...) inside TransactionScope is causing TransactionAbortedException and the innerException is TransactionPromotionException. The symptoms are the same as this.
Could anyone suggest me the solution to this issue?
Thanks a lot !
using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
{
DotNetNuke.Entities.Users.UserInfo ui = DotNetNuke.Entities.Users.UserController.GetUser(PortalId, UserId, false);
ts.Complete();
}
By default DotNetNuke uses the ASP.NET 2.0 membership provider. As you pointed, Membership.GetUser() opens another database connection, which causes the exception inside TransactionScope.
If you want to use GetUser() inside TransactionScope, you'll either have to enable MSDTC or use SQL Server 2008. SQL 2008 allows multiple connections within a single TransactionScope, if the connections are to the same DBMS and are not open at the same time.
See Also:
TransactionScope automatically escalating to MSDTC on some machines?

Categories