// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Data; using System.Data.Common; using Apache.NMS; using Apache.NMS.ActiveMQ; namespace Tx.XAMQDB.ADONET { public class AlmostBut : MQDB { public override IConnection GetSourceConnection() { IConnectionFactory cf = new ConnectionFactory(new Uri("tcp://localhost:61616")); IConnection con = cf.CreateConnection(); con.Start(); return con; } public override IDbConnection GetTargetConnection() { IDbConnection con = DbProviderFactories.GetFactory("Npgsql").CreateConnection(); con.ConnectionString = "Host=localhost;Database=Test;Username=postgres;Password=hemmeligt"; con.Open(); return con; } public override void Test() { for(int i = 0; i < 10; i++) { using(IConnection srccon = GetSourceConnection()) { using(ISession srcses = srccon.CreateSession(AcknowledgementMode.Transactional)) { using(IQueue qin = srcses.GetQueue("Qin")) { using(IMessageConsumer receiver = srcses.CreateConsumer(qin)) { using(IDbConnection trgcon = GetTargetConnection()) { using(IDbCommand trgcmd = trgcon.CreateCommand()) { trgcmd.Connection = trgcon; IDbTransaction trgtx = trgcon.BeginTransaction(); trgcmd.Transaction = trgtx; try { IMessage msg = receiver.Receive(); trgcmd.CommandText = "UPDATE tbltrg SET val = val + 1 WHERE id = 1"; trgcmd.ExecuteNonQuery(); srcses.Commit(); if(i % 2 != 0) throw new Problem(); trgtx.Commit(); } catch(Problem) { srcses.Rollback(); trgtx.Rollback(); Console.WriteLine("Problem"); } } } } } } } } } public static void Main(string[] args) { Demo(new AlmostBut()); Console.ReadKey(); } } }