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}'."));
        }
Example #3
0
        /// <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);
        }
Example #4
0
        /// <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);
        }
        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));
        }
        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());
        }
Example #7
0
        /// <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);
        }
Example #9
0
        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());
                }
        }
        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());
                }
        }
        /// <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);
        }
Example #12
0
        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));
                }
            }
        }
            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);
                }
            }
Example #14
0
        internal static IDtcTransaction GetOletxTransaction(Transaction transaction)
        {
            IDtcTransaction dtcTransaction = null;

            if (null != transaction)
            {
                dtcTransaction = TransactionInterop.GetDtcTransaction(transaction);
            }
            return(dtcTransaction);
        }
Example #15
0
        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));
        }
Example #16
0
        public TxnBatch(IBTTransportProxy transportProxy, ControlledTermination control, CommittableTransaction transaction, ManualResetEvent orderedEvent, bool makeSuccessCall) : base(transportProxy, makeSuccessCall)
        {
            this.control = control;

            this.comTxn = TransactionInterop.GetDtcTransaction(transaction);

            //  the System.Transactions transaction - must be the original transaction - only that can be used to commit
            this.transaction = transaction;

            this.orderedEvent = orderedEvent;
        }
        public static KtmTransactionHandle CreateKtmTransactionHandle(Transaction managedTransaction)
        {
            IDtcTransaction    dtcTransaction = TransactionInterop.GetDtcTransaction(managedTransaction);
            IKernelTransaction ktmInterface   = (IKernelTransaction)dtcTransaction;

            IntPtr ktmTxHandle;
            int    hr = ktmInterface.GetHandle(out ktmTxHandle);

            HandleError(hr);

            return(new KtmTransactionHandle(ktmTxHandle));
        }
 public void CreateFileStreamWhenGivenAmbientTransactionAndTransactionalFileSystemSupported()
 {
     TransactionalFile._operatingSystem = OperatingSystemExtensionsFixture.Windows7;
     using (new TransactionScope())
     {
         // grab kernel level transaction handle
         var dtcTransaction    = TransactionInterop.GetDtcTransaction(Transaction.Current);
         var kernelTransaction = (IKernelTransaction)dtcTransaction;
         var file = TransactionalFile.Create(_filename, 1024, kernelTransaction);
         file.Should().BeOfType <FileStream>();
     }
 }
 public IDtcTransaction Promote()
 {
     try
     {
         return(TransactionInterop.GetDtcTransaction(this.systemTx));
     }
     catch (TransactionException exception)
     {
         this.MapTxExceptionToHR(exception);
     }
     return(null);
 }
 public Guid GetIdentifier()
 {
     try
     {
         ITransaction dtcTransaction = (ITransaction)TransactionInterop.GetDtcTransaction(this.systemTx);
         return(this.systemTx.TransactionInformation.DistributedIdentifier);
     }
     catch (TransactionException exception)
     {
         this.MapTxExceptionToHR(exception);
     }
     return(Guid.Empty);
 }
Example #21
0
 public void CreateFileStreamWhenGivenAmbientTransactionAndTransactionalFileSystemSupported()
 {
     FileTransacted._operatingSystem = OperatingSystemExtensionsFixture.Windows7;
     using (new TransactionScope())
     {
         // grab kernel level transaction handle
         var dtcTransaction = TransactionInterop.GetDtcTransaction(Transaction.Current);
         // ReSharper disable once SuspiciousTypeConversion.Global
         var kernelTransaction = (IKernelTransaction)dtcTransaction;
         var file = FileTransacted.Create(_filename, 1024, kernelTransaction);
         Assert.That(file, Is.TypeOf <FileStream>());
     }
 }
        public static uint GetTimeoutFromTransaction(Transaction transaction)
        {
            // For transactions created inside this process, we can ask ITransactionOptions
            IDtcTransaction     dtcTransaction     = TransactionInterop.GetDtcTransaction(transaction);
            ITransactionOptions transactionOptions = (ITransactionOptions)dtcTransaction;

            XACTOPT options;

            transactionOptions.GetOptions(out options);

            // For transactions not created inside this process, this will return zero
            return(options.ulTimeout);
        }
        protected IDtcTransaction GetNativeTransaction(MsmqTransactionMode transactionMode)
        {
            Transaction current = Transaction.Current;

            if (current != null)
            {
                return(TransactionInterop.GetDtcTransaction(current));
            }
            if (transactionMode == MsmqTransactionMode.CurrentOrThrow)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("MsmqTransactionRequired")));
            }
            return(null);
        }
Example #24
0
        /// <summary>
        ///     Get KTM transaction from the specified managed <paramref name="managedTransaction" />
        /// </summary>
        /// <param name="managedTransaction">
        ///     Owning managed transaction
        /// </param>
        /// <remarks>
        ///     Currently this will require MS DTC service running. The created transaction should not be committed
        ///     or rolled back itself explicitly. Use the owning managed transaction to control it.
        ///     http://msdn.microsoft.com/en-us/library/cc303707.aspx
        /// </remarks>
        public static KtmTransactionHandle GetFromManaged(Transaction managedTransaction)
        {
            IKernelTransaction tx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
            IntPtr             txHandle;

            tx.GetHandle(out txHandle);

            if (txHandle == IntPtr.Zero)
            {
                throw new Win32Exception("Could not get KTM transaction handle.");
            }

            return(new KtmTransactionHandle(txHandle));
        }
Example #25
0
        protected IDtcTransaction GetNativeTransaction(MsmqTransactionMode transactionMode)
        {
            Transaction transaction = Transaction.Current;

            if (transaction != null)
            {
                return(TransactionInterop.GetDtcTransaction(transaction));
            }
            if (transactionMode == MsmqTransactionMode.CurrentOrThrow)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MsmqTransactionRequired)));
            }
            return(null);
        }
        public static void GetTransactionAttributes(Transaction transaction, out uint timeout, out IsolationFlags isoFlags, out string description)
        {
            XACTOPT             xactopt;
            XACTTRANSINFO       xacttransinfo;
            IDtcTransaction     dtcTransaction = TransactionInterop.GetDtcTransaction(transaction);
            ITransactionOptions options        = (ITransactionOptions)dtcTransaction;
            ISaneDtcTransaction transaction3   = (ISaneDtcTransaction)dtcTransaction;

            options.GetOptions(out xactopt);
            timeout     = xactopt.ulTimeout;
            description = xactopt.szDescription;
            transaction3.GetTransactionInfo(out xacttransinfo);
            isoFlags = xacttransinfo.isoFlags;
        }
 public void TransactionRollbackWithAmbientTransaction()
 {
     using (new TransactionScope())
     {
         // ReSharper disable once SuspiciousTypeConversion.Global
         var kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
         using (var file = FileTransacted.Create(_filename, 1024, kernelTransaction))
         {
             Assert.That(file, Is.TypeOf <FileStream>());
             file.Write(_buffer, 0, _buffer.Length);
         }
         // this is the root scope and failing to cast a vote will abort the ambient transaction
     }
     Assert.That(File.Exists(_filename), Is.False);
 }
Example #28
0
        public void TransactionRollbackWithAmbientTransaction()
        {
            using (new TransactionScope())
            {
                var kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
                using (var file = TransactionalFile.Create(_filename, 1024, kernelTransaction))
                {
                    file.Should().BeOfType <FileStream>();
                    file.Write(_buffer, 0, _buffer.Length);
                }
                // this is the root scope and failing to cast a vote will abort the ambient transaction
            }

            File.Exists(_filename).Should().BeFalse();
        }
Example #29
0
        public void TransactionCommitWithAmbientTransaction()
        {
            using (var scope = new TransactionScope())
            {
                var kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
                using (var file = TransactionalFile.Create(_filename, 1024, kernelTransaction))
                {
                    file.Should().BeOfType <FileStream>();
                    file.Write(_buffer, 0, _buffer.Length);
                }
                // this is the root scope and it has to cast a vote
                scope.Complete();
            }

            File.Exists(_filename).Should().BeTrue();
        }
Example #30
0
        public static FileStream GetTransactedFileStream(string fileName)
        {
            var ktx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);

            SafeTransactionHandle txHandle;

            ktx.GetHandle(out txHandle);

            SafeFileHandle fileHandle = NativeMethods.CreateFileTransacted(
                fileName, GenericWrite, 0,
                IntPtr.Zero, CreateAlways, FileAttributeNormal,
                IntPtr.Zero,
                txHandle, IntPtr.Zero, IntPtr.Zero);

            return(new FileStream(fileHandle, FileAccess.Write));
        }