private void Enlist(Transaction transaction) { if (transaction == null) { // no enlistment as we are not in a TransactionScope return; } // try to enlist as a PSPE if (!transaction.EnlistPromotableSinglePhase(this)) { // our enlistmente fail so we need to enlist ourselves as durable. // we create a transaction directly instead of using BeginTransaction that GraphClient // doesn't store it in its stack of scopes. var localTransaction = new Neo4jTransaction(_client); localTransaction.ForceKeepAlive(); _transactionId = localTransaction.Id; var resourceManager = GetResourceManager(); var propagationToken = TransactionInterop.GetTransmitterPropagationToken(transaction); var transactionExecutionEnvironment = new TransactionExecutionEnvironment(_client.ExecutionConfiguration) { TransactionId = localTransaction.Id, TransactionBaseEndpoint = _client.TransactionEndpoint }; resourceManager.Enlist(transactionExecutionEnvironment, propagationToken); localTransaction.Cancel(); } _enlistedInTransactions.Add(transaction); }
private void Enlist(Transaction transaction) { if (transaction == null) { // no enlistment as we are not in a TransactionScope return; } // try to enlist as a PSPE if (!transaction.EnlistPromotableSinglePhase(this)) { // our enlistmente fail so we need to enlist ourselves as durable. // we create a transaction directly instead of using BeginTransaction that GraphClient // doesn't store it in its stack of scopes. var localTransaction = new BoltNeo4jTransaction(((BoltGraphClient)client).Driver); var propagationToken = TransactionInterop.GetTransmitterPropagationToken(transaction); var transactionExecutionEnvironment = new BoltTransactionExecutionEnvironment(client.ExecutionConfiguration) { Session = this.transaction.Session, DriverTransaction = this.transaction.DriverTransaction, TransactionId = this.transactionId // TransactionId = localTransaction.Id, // TransactionBaseEndpoint = client.TransactionEndpoint }; ResourceManager.Enlist(transactionExecutionEnvironment, propagationToken); localTransaction.Cancel(); } enlistedInTransactions.Add(transaction); }
public void SyncDTCTransaction(byte[] token) { Transaction tran = TransactionInterop.GetTransactionFromTransmitterPropagationToken(token); using (TransactionScope transactionScope = new TransactionScope(tran)) { DbContextNet2 dbContextNet2 = new DbContextNet2(); dbContextNet2.School.Add(new School() { Name = "dtc" }); dbContextNet2.SaveChanges(); transactionScope.Complete(); } // using (var dbContextNet2 = new DbContextNet2()) //using (var command = dbContextNet2.Database.GetDbConnection().CreateCommand()) //{ // command.CommandText = sql; // dbContextNet2.Database.OpenConnection(); // using (var result = command.ExecuteReader()) // { // var x = ""; // } //} // return true; // exexute logic with in the distributed trnsaction }
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { return(Task.Factory.StartNew(() => { try { if (actionContext.Request.Headers.Contains(TransactionId)) { var values = actionContext.Request.Headers.GetValues(TransactionId); if (values != null && values.Any()) { byte[] transactionToken = Convert.FromBase64String(values.FirstOrDefault()); var transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(transactionToken); var transactionScope = new TransactionScope(transaction); actionContext.Request.Properties.Add(TransactionId, transactionScope); } } } catch (Exception ex) { _logService.LogMessage(ex); } })); }
/// <summary> /// Read a file with transaction /// </summary> /// <param name="path">Path to file</param> /// <returns>Donnes lu</returns> public object ReadFileTransacted(string path) { if (!File.Exists(path)) { return(null); } SafeTransactionHandle txHandle = null; SafeFileHandle fileHandle = null; object raw = null; try { IKernelTransaction kernelTx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(System.Transactions.Transaction.Current); kernelTx.GetHandle(out txHandle); fileHandle = CreateFileTransacted( path , SafeTransactionHandle.FileAccess.GENERIC_READ , SafeTransactionHandle.FileShare.FILE_SHARE_READ , IntPtr.Zero , SafeTransactionHandle.FileMode.OPEN_ALWAYS , 0 , IntPtr.Zero , txHandle , IntPtr.Zero , IntPtr.Zero); if (fileHandle.IsInvalid) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } using (FileStream stream = new FileStream(fileHandle, FileAccess.Read, 1024, false)) { BinaryFormatter reader = new BinaryFormatter(); raw = reader.Deserialize(stream); } } catch { raw = null; } finally { if (fileHandle != null && !fileHandle.IsInvalid) { fileHandle.Close(); fileHandle.Dispose(); } if (txHandle != null && !txHandle.IsInvalid) { txHandle.Close(); txHandle.Dispose(); } } return(raw); }
/// <summary> /// Write a file with transaction /// </summary> /// <param name="data">Data to write</param> /// <param name="path">Path to file</param> /// <returns>Statut de l'opration</returns> public static bool WriteStateFileTransacted(string path, XmlSerializer stateSerializer, AtomState atomState, System.Transactions.Transaction transaction) { if (atomState == null) { return(false); } SafeTransactionHandle txHandle = null; SafeFileHandle fileHandle = null; bool response = true; try { IKernelTransaction kernelTx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(transaction); kernelTx.GetHandle(out txHandle); fileHandle = CreateFileTransacted( path , SafeTransactionHandle.FileAccess.GENERIC_WRITE , SafeTransactionHandle.FileShare.FILE_SHARE_NONE , IntPtr.Zero , SafeTransactionHandle.FileMode.CREATE_ALWAYS , 0 , IntPtr.Zero , txHandle , IntPtr.Zero , IntPtr.Zero); if (fileHandle.IsInvalid) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } using (FileStream stateFile = new FileStream(fileHandle, FileAccess.Write, 1024, false)) { stateSerializer.Serialize(stateFile, atomState); } } catch { transaction.Rollback(); response = false; } finally { if (fileHandle != null && !fileHandle.IsInvalid) { fileHandle.Close(); fileHandle.Dispose(); } if (txHandle != null && !txHandle.IsInvalid) { txHandle.Close(); txHandle.Dispose(); } } return(response); }
public object GetRealObject(StreamingContext context) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), "IObjectReference.GetRealObject"); } if (this.propagationTokenForDeserialize == null) { if (DiagnosticTrace.Critical) { InternalErrorTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), System.Transactions.SR.GetString("UnableToDeserializeTransaction")); } throw TransactionException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), System.Transactions.SR.GetString("UnableToDeserializeTransactionInternalError"), null); } if (null != this.savedLtmPromotedTransaction) { if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), "IObjectReference.GetRealObject"); } return(this.savedLtmPromotedTransaction); } Transaction transactionFromTransmitterPropagationToken = TransactionInterop.GetTransactionFromTransmitterPropagationToken(this.propagationTokenForDeserialize); this.savedLtmPromotedTransaction = transactionFromTransmitterPropagationToken; if (DiagnosticTrace.Verbose) { TransactionDeserializedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), transactionFromTransmitterPropagationToken.internalTransaction.PromotedTransaction.TransactionTraceId); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), "IObjectReference.GetRealObject"); } return(transactionFromTransmitterPropagationToken); }
internal static SafeTransactionHandle Create(Transaction managedTransaction) { if (managedTransaction == null) { throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NeedTransaction); } // MSDTC is not available on WinPE machine. // CommitableTransaction will use DTC APIs under the covers to get KTM transaction manager interface. // KTM is kernel Transaction Manager to handle file, registry etc and MSDTC provides an integration support // with KTM to handle transaction across kernel resources and MSDTC resources like SQL, MSMQ etc. // We need KTMRM service as well. WinPE doesn’t have these services installed if (Utils.IsWinPEHost() || PsUtils.IsRunningOnProcessorArchitectureARM()) { throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); } IDtcTransaction dtcTransaction = TransactionInterop.GetDtcTransaction(managedTransaction); IKernelTransaction ktmInterface = dtcTransaction as IKernelTransaction; if (null == ktmInterface) { throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); } IntPtr ktmTxHandle; int hr = ktmInterface.GetHandle(out ktmTxHandle); HandleError(hr); return(new SafeTransactionHandle(ktmTxHandle)); }
public void CaptureOfInboundMessagePiggiesBackKernelTransaction() { using (new TransactionScope()) using (var stream = new MemoryStream()) { MessageMock.Object.BodyPart.Data = stream; var transaction = TransactionInterop.GetDtcTransaction(Transaction.Current); PipelineContextMock.As <IPipelineContextEx>() .Setup(pc => pc.GetTransaction()) // ReSharper disable once SuspiciousTypeConversion.Global .Returns((IKernelTransaction)transaction); var sut = MessageBodyTracker.Create(new MicroComponent.ActivityTracker.Context(PipelineContextMock.Object, MessageMock.Object, ActivityTrackingModes.Body)); sut.SetupTracking(); ClaimStoreMock.Verify( cs => cs.SetupMessageBodyCapture( It.IsAny <TrackingStream>(), It.IsAny <ActivityTrackingModes>(), // ReSharper disable once SuspiciousTypeConversion.Global It.Is <Func <IKernelTransaction> >(ktf => ReferenceEquals(ktf(), transaction))), Times.Once()); } }
public byte[] Promote() { #pragma warning disable PC001 return(TransactionInterop.GetTransmitterPropagationToken(new CommittableTransaction())); #pragma warning restore PC001 }
/// <summary> /// Enables a transaction for the pipeline execution /// </summary> /// <returns>Object to control the transaction lifetime</returns> public TransactionControl EnableTransactionSupport() { CommittableTransaction tx = new CommittableTransaction(); _transaction = TransactionInterop.GetDtcTransaction(tx); return(new TransactionControl(tx)); }
public static uint GetTimeoutFromTransaction(Transaction transaction) { XACTOPT xactopt; ((ITransactionOptions)TransactionInterop.GetDtcTransaction(transaction)).GetOptions(out xactopt); return(xactopt.ulTimeout); }
public void CaptureOfOutboundMessageDoesNotPiggyBackKernelTransaction() { MessageMock.Setup(m => m.GetProperty(BtsProperties.OutboundTransportLocation)).Returns("outbound-transport-location"); using (new TransactionScope()) using (var stream = new MemoryStream()) { MessageMock.Object.BodyPart.Data = stream; var transaction = TransactionInterop.GetDtcTransaction(Transaction.Current); PipelineContextMock.As <IPipelineContextEx>() .Setup(pc => pc.GetTransaction()) .Returns((IKernelTransaction)transaction); var sut = MessageBodyTracker.Create(new MicroComponent.ActivityTracker.Context(PipelineContextMock.Object, MessageMock.Object, ActivityTrackingModes.Body)); sut.SetupTracking(); ClaimStoreMock.Verify( cs => cs.SetupMessageBodyCapture( It.IsAny <TrackingStream>(), It.IsAny <ActivityTrackingModes>(), It.Is <Func <IKernelTransaction> >(ktf => ktf == null)), Times.Once()); } }
static byte[] CreateFixedPropagationToken() { if (fixedPropagationToken == null) { CommittableTransaction tx = new CommittableTransaction(); byte[] token = TransactionInterop.GetTransmitterPropagationToken(tx); // Don't abort the transaction. People notice this and do not like it. try { tx.Commit(); } catch (TransactionException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } Interlocked.CompareExchange <byte[]>(ref fixedPropagationToken, token, null); } byte[] tokenCopy = new byte[fixedPropagationToken.Length]; Array.Copy(fixedPropagationToken, tokenCopy, fixedPropagationToken.Length); return(tokenCopy); }
protected override void InnerBegin() { // we have a ongoing current transaction, join it! if (System.Transactions.Transaction.Current != null) { var ktx = (IKernelTransaction)TransactionInterop .GetDtcTransaction(System.Transactions.Transaction.Current); SafeTransactionHandle handle; ktx.GetHandle(out handle); // even though _TransactionHandle can already contain a handle if this thread // had been yielded just before setting this reference, the "safe"-ness of the wrapper should // not dispose the other handle which is now removed _TransactionHandle = handle; IsAmbient = true; } else { _TransactionHandle = createTransaction(string.Format("{0} Transaction", theName)); } if (!_TransactionHandle.IsInvalid) { return; } throw new TransactionException( "Cannot begin file transaction. CreateTransaction failed and there's no ambient transaction.", LastEx()); }
private void InnerBegin() { Contract.Ensures(_State == TransactionState.Active); // we have a ongoing current transaction, join it! if (System.Transactions.Transaction.Current != null) { var ktx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(System.Transactions.Transaction.Current); SafeKernelTransactionHandle handle; ktx.GetHandle(out handle); // even though _TransactionHandle can already contain a handle if this thread // had been yielded just before setting this reference, the "safe"-ness of the wrapper should // not dispose the other handle which is now removed _TransactionHandle = handle; //IsAmbient = true; // TODO: Perhaps we created this item and we need to notify the transaction manager... } else { _TransactionHandle = NativeMethods.CreateTransaction(string.Format("{0} Transaction", _Name)); } if (!_TransactionHandle.IsInvalid) { _State = TransactionState.Active; return; } throw new TransactionException( "Cannot begin file transaction. CreateTransaction failed and there's no ambient transaction.", LastEx()); }
internal virtual bool TryMoveFile(string sourceFilePath, string targetFilePath) { if (sourceFilePath.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(sourceFilePath)); } if (targetFilePath.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(targetFilePath)); } var transaction = Transaction.Current; if (transaction == null) { return(TryIoOperation(() => File.Move(sourceFilePath, targetFilePath), $"Failed to move file from '{sourceFilePath}' to '{targetFilePath}'.")); } // ReSharper disable once SuspiciousTypeConversion.Global var kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(transaction); return(TryIoOperation( () => TransactionalFile.Move(sourceFilePath, targetFilePath, kernelTransaction), $"Failed to transactionally move file from '{sourceFilePath}' to '{targetFilePath}'.")); }
public static void AddTransactionPropagationToken(this HttpRequestMessage request) { if (Transaction.Current != null) { var token = TransactionInterop.GetTransmitterPropagationToken(Transaction.Current); request.Headers.Add("TransactionToken", Convert.ToBase64String(token)); } }
public static void AddTransactionToken(this HttpClient client) { if (Transaction.Current != null) { var token = TransactionInterop.GetTransmitterPropagationToken(Transaction.Current); client.DefaultRequestHeaders.Add("TransactionToken", Convert.ToBase64String(token)); } }
/// <summary> /// Enlists the specified SSO object into the specified transaction. /// </summary> /// <remarks> /// The IPropertyBag interface is supported on the Single Sign-On objects: /// SSOAdmin, SSOMapper, SSOMapping, SSOLookup, SSOConfigStore. /// Note: /// This methods sets a DTC ITransaction pointer (as a VT_UNKNOWN) on the object model /// instance so that subsequent actions using that object are scoped within the DTC /// transaction. /// </remarks> /// <param name="ssoObj">Instance of the SSO object implementing the IPropertyBag interface to be enlisted.</param> /// <param name="tx">Transaction.</param> private static void Enlist(IPropertyBag ssoObj, Transaction tx) { object dtcTx = TransactionInterop.GetDtcTransaction(tx); object secretServerObj = SSOManager.SSOSecrectServer; ssoObj.Write("CurrentSSOServer", ref secretServerObj); ssoObj.Write("Transaction", ref dtcTx); }
public LoadOrCreateAsyncResult(PersistenceProviderDirectory ppd, InstanceKey key, Guid suggestedIdOrId, bool canCreateInstance, ICollection <InstanceKey> associatedKeys, Transaction transaction, bool loadAny, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { bool flag; this.ppd = ppd; this.key = key; this.suggestedIdOrId = suggestedIdOrId; this.canCreateInstance = canCreateInstance; this.associatedKeys = associatedKeys; this.transaction = transaction; this.loadAny = loadAny; this.timeoutHelper = new TimeoutHelper(timeout); if ((this.associatedKeys != null) && (this.associatedKeys.Count == 0)) { this.associatedKeys = null; } base.OnCompleting = onComplete; if (this.transaction != null) { TransactionInterop.GetDtcTransaction(this.transaction); } Exception exception = null; try { this.result = this.loadAny ? null : this.ppd.LoadFromCache(this.key, this.suggestedIdOrId, this.canCreateInstance); if (this.result != null) { flag = true; } else { if ((this.ppd.store == null) && !this.canCreateInstance) { if (this.key != null) { throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InstanceKeyNotReadyException(null, this.key)); } throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InstanceNotReadyException(null, this.suggestedIdOrId)); } IAsyncResult result = this.ppd.BeginReserveThrottle(this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleReserveThrottle), this); flag = base.SyncContinue(result); } } catch (Exception exception2) { if (Fx.IsFatal(exception2)) { throw; } exception = exception2; flag = true; } if (flag) { base.Complete(true, exception); } }
public static void MoveToSubQueue( this MessageQueue queue, string subQueueName, Message message) { var fullSubQueueName = @"DIRECT=OS:.\" + queue.QueueName + ";" + subQueueName; IntPtr queueHandle = IntPtr.Zero; var error = NativeMethods.MQOpenQueue(fullSubQueueName, NativeMethods.MQ_MOVE_ACCESS, NativeMethods.MQ_DENY_NONE, ref queueHandle); if (error != 0) { throw new TransportException("Failed to open queue: " + fullSubQueueName, new Win32Exception(error)); } try { if (MsmqTransactionStrategy.Current != null) { //var trans = _internalTransaction.GetValue(MsmqTransactionStrategy.Current, null); error = NativeMethods.MQMoveMessage(queue.ReadHandle, queueHandle, message.LookupId, null); if (error != 0) { throw new TransportException("Failed to move message to queue: " + fullSubQueueName, new Win32Exception(error)); } return; } Transaction current = Transaction.Current; IDtcTransaction transaction = null; if (current != null && queue.Transactional) { transaction = TransactionInterop.GetDtcTransaction(current); } error = NativeMethods.MQMoveMessage(queue.ReadHandle, queueHandle, message.LookupId, transaction); if (error != 0) { throw new TransportException("Failed to move message to queue: " + fullSubQueueName, new Win32Exception(error)); } } finally { error = NativeMethods.MQCloseQueue(queueHandle); if (error != 0) { throw new TransportException("Failed to close queue: " + fullSubQueueName, new Win32Exception(error)); } } }
static private byte[] GetTransactionCookie(Transaction transaction, byte[] whereAbouts) { byte[] transactionCookie = null; if (null != transaction) { transactionCookie = TransactionInterop.GetExportCookie(transaction, whereAbouts); } return(transactionCookie); }
//======================================================================================= void ForcePromotion(Transaction transaction) { // Force promotion. This may throw TransactionException. // We used to check the DistributedIdentifier property first, but VSWhidbey bug 547901 // prevents us from doing so reliably in multi-threaded scenarios (there is a ---- // in the System.Transactions code that can cause a NullReferenceException if we ask // for the identifier while the transaction is being promoted) TransactionInterop.GetTransmitterPropagationToken(transaction); }
//======================================================================================= void ForcePromotion(Transaction transaction) { // Force promotion. This may throw TransactionException. // We used to check the DistributedIdentifier property first, but VSWhidbey TransactionInterop.GetTransmitterPropagationToken(transaction); }
private static TransactionScope CreateDistributedTransactionScope() { var scope = new TransactionScope(); // // Forces promotion to distributed transaction // TransactionInterop.GetTransmitterPropagationToken(System.Transactions.Transaction.Current); return(scope); }
public byte[] Promote(INpgsqlTransactionCallbacks callbacks) { CommittableTransaction tx = new CommittableTransaction(); DurableResourceManager rm = new DurableResourceManager(this, callbacks, tx); byte[] token = TransactionInterop.GetTransmitterPropagationToken(tx); _transactions.Add(rm.TxName, tx); rm.Enlist(tx); return(token); }
internal static IDtcTransaction GetOletxTransaction(Transaction transaction) { IDtcTransaction dtcTransaction = null; if (null != transaction) { dtcTransaction = TransactionInterop.GetDtcTransaction(transaction); } return(dtcTransaction); }
public void MarshalAsCoordinationContext(Transaction transaction, out CoordinationContext context, out RequestSecurityTokenResponse issuedToken) { uint num; IsolationFlags flags; string str2; WsatExtendedInformation information; string str3; Guid distributedIdentifier = transaction.TransactionInformation.DistributedIdentifier; string contextId = null; context = new CoordinationContext(this.protocolVersion); OleTxTransactionFormatter.GetTransactionAttributes(transaction, out num, out flags, out str2); context.IsolationFlags = flags; context.Description = str2; if (TransactionCache <Transaction, WsatExtendedInformation> .Find(transaction, out information)) { context.Expires = information.Timeout; if (!string.IsNullOrEmpty(information.Identifier)) { context.Identifier = information.Identifier; contextId = information.Identifier; } } else { context.Expires = num; if (context.Expires == 0) { context.Expires = (uint)TimeoutHelper.ToMilliseconds(this.wsatConfig.MaxTimeout); } } if (context.Identifier == null) { context.Identifier = CoordinationContext.CreateNativeIdentifier(distributedIdentifier); contextId = null; } if (!this.wsatConfig.IssuedTokensEnabled) { str3 = null; issuedToken = null; } else { CoordinationServiceSecurity.CreateIssuedToken(distributedIdentifier, context.Identifier, this.protocolVersion, out issuedToken, out str3); } AddressHeader refParam = new WsatRegistrationHeader(distributedIdentifier, contextId, str3); context.RegistrationService = this.wsatConfig.CreateRegistrationService(refParam, this.protocolVersion); context.IsolationLevel = transaction.IsolationLevel; context.LocalTransactionId = distributedIdentifier; if (this.wsatConfig.OleTxUpgradeEnabled) { context.PropagationToken = TransactionInterop.GetTransmitterPropagationToken(transaction); } }
public static bool DeleteFiles(FileArgs args) { bool response = true; string message = String.Empty; return(TransactionActionHelper.DoActionWithCheckOnTransaction((ref string s) => { foreach (var file in args.Files) { if (!response) { return false; } if (!TransactionActionHelper.CheckConditions((ref string mes) => { if (!File.Exists(file)) { mes = "Wrong path or file exists"; Transaction.Current.Rollback(); return false; } return true; }, ref s)) { return false; } SafeTransactionHandle txHandle = null; try { IKernelTransaction kernelTx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current); kernelTx.GetHandle(out txHandle); if (!DeleteFileTransacted(file, txHandle)) { Transaction.Current.Rollback(); response = false; } } catch (Exception ex) { response = false; s = ex.Message; Transaction.Current.Rollback(); } finally { if (txHandle != null && !txHandle.IsInvalid) { txHandle.Dispose(); } } } return response; }, ref message)); }