コード例 #1
0
        public void TransactionId_Serialization()
        {
            TransactionId transactionId = new TransactionId(Guid.NewGuid().ToString());

            string output = JsonConvert.SerializeObject(transactionId);

            TransactionId deserializedTransactionId = JsonConvert.DeserializeObject <TransactionId>(output);

            deserializedTransactionId.ShouldBe(transactionId);
        }
コード例 #2
0
        /// <summary>
        /// Saves metadata to the beginning of the stream
        /// </summary>
        /// <param name="stream"></param>
        public void Save(Stream stream)
        {
            stream.Position = 0;
            BinaryWriter writer = new BinaryWriter(stream);

            writer.Write(TransactionId.ToByteArray());
            writer.Write(StreamLength);
            writer.Write(SegmentCount);
            writer.Write(TransactionCompleted);
        }
コード例 #3
0
        public int CompareTo(TransactionalResourceVersion other)
        {
            var result = TransactionId.CompareTo(other.TransactionId);

            if (result == 0)
            {
                result = WriteNumber.CompareTo(other.WriteNumber);
            }
            return(result);
        }
コード例 #4
0
ファイル: Response.cs プロジェクト: mishun/Modbus
 /// <inheritdoc/>
 public override int GetHashCode()
 {
     return(base.GetHashCode() ^
            TransactionId.GetHashCode() ^
            DeviceId.GetHashCode() ^
            Function.GetHashCode() ^
            Address.GetHashCode() ^
            Count.GetHashCode() ^
            Data.GetHashCode());
 }
            /// <summary>
            /// Compares two SetChargingPoolAvailabilityStatus responses for equality.
            /// </summary>
            /// <param name="SetChargingPoolAvailabilityStatusResponse">A SetChargingPoolAvailabilityStatus response to compare with.</param>
            /// <returns>True if both match; False otherwise.</returns>
            public override Boolean Equals(SetChargingPoolAvailabilityStatusResponse SetChargingPoolAvailabilityStatusResponse)
            {
                if ((Object)SetChargingPoolAvailabilityStatusResponse == null)
                {
                    return(false);
                }

                return(TransactionId.Equals(SetChargingPoolAvailabilityStatusResponse.TransactionId) &&
                       RequestStatus.Equals(SetChargingPoolAvailabilityStatusResponse.RequestStatus));
            }
コード例 #6
0
        /// <summary>
        ///     Creates a new local transaction ID
        /// </summary>
        public TransactionId CreateLocalTransactionId()
        {
            var id = new TransactionId
            {
                ConnectionId = ConnectionId,
                Value        = Interlocked.Increment(ref _localTransactionCounter)
            };

            return(id);
        }
コード例 #7
0
 /// <summary>
 /// Return the HashCode of this object.
 /// </summary>
 /// <returns>The HashCode of this object.</returns>
 public override Int32 GetHashCode()
 {
     unchecked
     {
         return(TransactionId.GetHashCode() * 7 ^
                RequestStatus.GetHashCode() * 5 ^
                ServiceSessionId.GetHashCode() * 3 ^
                SessionActionId.GetHashCode());
     }
 }
コード例 #8
0
            /// <summary>
            /// Compares two SetEVSESyntheticStatus responses for equality.
            /// </summary>
            /// <param name="SetEVSESyntheticStatusResponse">A SetEVSESyntheticStatus response to compare with.</param>
            /// <returns>True if both match; False otherwise.</returns>
            public override Boolean Equals(SetEVSESyntheticStatusResponse SetEVSESyntheticStatusResponse)
            {
                if ((Object)SetEVSESyntheticStatusResponse == null)
                {
                    return(false);
                }

                return(TransactionId.Equals(SetEVSESyntheticStatusResponse.TransactionId) &&
                       RequestStatus.Equals(SetEVSESyntheticStatusResponse.RequestStatus));
            }
コード例 #9
0
        public override void UpdateLocalTransactionCacheEntry(TransactionId transactionId, WalletTransactionCache.TransactionStatuses status, long gossipMessageHash)
        {
            base.UpdateLocalTransactionCacheEntry(transactionId, status, gossipMessageHash);

            AccountId targetAccountId = transactionId.Account;

            TotalAPI total = this.GetAccountBalance(targetAccountId, true);

            this.centralCoordinator.PostSystemEvent(NeuraliumSystemEventGenerator.NeuraliumAccountTotalUpdated(targetAccountId.SequenceId, targetAccountId.AccountType, total));
        }
コード例 #10
0
 /// <summary>
 /// Return the HashCode of this object.
 /// </summary>
 /// <returns>The HashCode of this object.</returns>
 public override Int32 GetHashCode()
 {
     unchecked
     {
         return(HeartbeatPeriod.GetHashCode() * 7 ^
                CurrentTime.GetHashCode() * 5 ^
                TransactionId.GetHashCode() * 3 ^
                RequestStatus.GetHashCode());
     }
 }
コード例 #11
0
        /// <summary>
        /// Compares two SetSessionEventReport responses for equality.
        /// </summary>
        /// <param name="SetSessionEventReportResponse">A SetSessionEventReport response to compare with.</param>
        /// <returns>True if both match; False otherwise.</returns>
        public override Boolean Equals(SetSessionEventReportResponse SetSessionEventReportResponse)
        {
            if (SetSessionEventReportResponse is null)
            {
                return(false);
            }

            return(TransactionId.Equals(SetSessionEventReportResponse.TransactionId) &&
                   RequestStatus.Equals(SetSessionEventReportResponse.RequestStatus));
        }
コード例 #12
0
        public void RecordException(Exception e, Serializer <OrleansTransactionAbortedException> sm)
        {
            if (OriginalException == null)
            {
                var exception = (e as OrleansTransactionAbortedException)
                                ?? new OrleansTransactionAbortedException(TransactionId.ToString(), e);

                OriginalException = sm.SerializeToArray(exception);
            }
        }
コード例 #13
0
        /// <summary>
        /// Compares two start transaction responses for equality.
        /// </summary>
        /// <param name="StartTransactionResponse">A start transaction response to compare with.</param>
        /// <returns>True if both match; False otherwise.</returns>
        public override Boolean Equals(StartTransactionResponse StartTransactionResponse)
        {
            if (StartTransactionResponse is null)
            {
                return(false);
            }

            return(TransactionId.Equals(StartTransactionResponse.TransactionId) &&
                   IdTagInfo.Equals(StartTransactionResponse.IdTagInfo));
        }
コード例 #14
0
ファイル: Transaction.cs プロジェクト: llenroc/BEx
 public override int GetHashCode()
 {
     return
         (Amount.GetHashCode()
          ^ CompletedTime.GetHashCode()
          ^ Pair.GetHashCode()
          ^ UnixCompletedTimeStamp.GetHashCode()
          ^ TransactionId.GetHashCode()
          ^ SourceExchange.GetHashCode());
 }
コード例 #15
0
        public async Task <ActionResult <TransactionStateResponse> > GetState([FromRoute] TransactionId transactionId)
        {
            if (transactionId == null)
            {
                throw RequestValidationException.ShouldBeNotNull(nameof(transactionId));
            }

            var state = await _transactionsStateProvider.GetStateAsync(transactionId);

            return(Ok(new TransactionStateResponse(state)));
        }
コード例 #16
0
 internal Transaction(AccountId accId, TransactionId id, TransactionLabel label, ITransactionAmount amount, TransactionMetadata meta, TransactionDescription descr, DateTime createdOn, DateTime updatedOn)
 {
     AccountId   = accId;
     Id          = id;
     Label       = label;
     Amount      = amount;
     Metadata    = meta;
     Description = descr;
     CreatedOn   = createdOn;
     UpdatedOn   = updatedOn;
 }
コード例 #17
0
        public byte[] GetCombinedByteString()
        {
            var data = TransactionId.ToString().ToUpper() + Result.ToString() + CertificateFingerprint + ServerIP + ServerURI;

            Console.WriteLine(data);
            using (var hash = SHA256.Create())
            {
                PrintByteArray(hash.ComputeHash(Encoding.UTF8.GetBytes(data)));
            }
            return(Encoding.UTF8.GetBytes(data));
        }
コード例 #18
0
        public void SuspendResumeRollback()
        {
            o_region1 = new RegionOperation(cstxRegions[0]);
            o_region2 = new RegionOperation(cstxRegions[1]);

            CacheHelper.CSTXManager.Begin();
            o_region1.PutOp(1, null);

            o_region2.PutOp(1, null);


            Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(CacheHelper.CSTXManager.TransactionId), false, "Transaction should not be suspended");
            Assert.AreEqual(CacheHelper.CSTXManager.Exists(CacheHelper.CSTXManager.TransactionId), true, "Transaction should exist");
            Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit");
            Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit");

            TransactionId tid = CacheHelper.CSTXManager.Suspend();

            Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), true, "Transaction should be suspended");
            Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist");
            Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend");
            Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend");


            CacheHelper.CSTXManager.Resume(tid);
            Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended");
            Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist");
            Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit");
            Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit");

            o_region2.PutOp(2, null);

            Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region before commit");
            Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region before commit");

            CacheHelper.CSTXManager.Rollback();
            Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended");
            Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), false, "Transaction should NOT exist");
            Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "Transaction should not be resumed");
            Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid, 3000), false, "Transaction should not be resumed");
            Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after rollback");
            Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after rollback");
            bool resumeEx = false;

            try
            {
                CacheHelper.CSTXManager.Resume(tid);
            }
            catch (IllegalStateException)
            {
                resumeEx = true;
            }
            Assert.AreEqual(resumeEx, true, "The transaction should not be resumed");
        }
コード例 #19
0
        public TransactionState RemoveTransactionState(TransactionId id)
        {
            TransactionState ret = null;

            if (transactions.TryGetValue(id, out ret))
            {
                transactions.Remove(id);
            }

            return(ret);
        }
コード例 #20
0
        public static TransactionId GetTransactionIdByStr(string id)
        {
            var list   = id.Split('.');
            var result = new TransactionId
            {
                Index   = int.Parse(list[1]) - 1,
                PoolSeq = long.Parse(list[0])
            };

            return(result);
        }
コード例 #21
0
        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomSetServiceAuthorisationRequestSerializer">A delegate to serialize custom set EVSE busy status request XML elements.</param>
        /// <param name="CustomMeterReportSerializer">A delegate to serialize custom MeterReport XML elements.</param>
        public XElement ToXML(CustomXMLSerializerDelegate<SetServiceAuthorisationRequest>  CustomSetServiceAuthorisationRequestSerializer  = null,
                              CustomXMLSerializerDelegate<MeterReport>                     CustomMeterReportSerializer                     = null)
        {

            var XML = new XElement(eMIPNS.Authorisation + "eMIP_FromIOP_SetServiceAuthorisationRequest",

                          TransactionId.HasValue
                              ? new XElement("transactionId",            TransactionId.                ToString())
                              : null,

                          new XElement("partnerIdType",                  PartnerId.Format.             AsText()),
                          new XElement("partnerId",                      PartnerId.                    ToString()),

                          new XElement("operatorIdType",                 OperatorId.Format.            AsText()),
                          new XElement("operatorId",                     OperatorId.                   ToString()),

                          new XElement("targetOperatorIdType",           TargetOperatorId.Format.      AsText()),
                          new XElement("targetOperatorId",               TargetOperatorId.             ToString()),

                          new XElement("EVSEIdType",                     EVSEId.Format.                AsText()),
                          new XElement("EVSEId",                         EVSEId.                       ToString()),

                          new XElement("userIdType",                     UserId.Format.                AsText()),
                          new XElement("userId",                         UserId.                       ToString()),

                          new XElement("requestedServiceId",             RequestedServiceId.           ToString()),
                          new XElement("serviceSessionId",               ServiceSessionId.             ToString()),
                          new XElement("authorisationValue",             AuthorisationValue.           ToString()),
                          new XElement("intermediateCDRRequested",       IntermediateCDRRequested ? "1" : "0"),

                          UserContractIdAlias.HasValue
                              ? new XElement("userContractIdAlias",      UserContractIdAlias.          ToString())
                              : null,

                          MeterLimits.Any()
                              ? new XElement("meterLimitList",           MeterLimits.Select(meterreport => meterreport.ToXML(CustomMeterReportSerializer: CustomMeterReportSerializer)))
                              : null,

                          Parameter.IsNotNullOrEmpty()
                              ? new XElement("parameter",                Parameter)
                              : null,

                          BookingId.HasValue
                              ? new XElement("bookingId",                BookingId.                    ToString())
                              : null

                      );


            return CustomSetServiceAuthorisationRequestSerializer != null
                       ? CustomSetServiceAuthorisationRequestSerializer(this, XML)
                       : XML;

        }
コード例 #22
0
        public IDictionary <string, string> GetEventProperties()
        {
            IDictionary <string, string> properties = new Dictionary <string, string>();

            properties.Add("UnitId", UnitId.ToString());
            properties.Add("TransactionId", TransactionId.ToString());
            properties.Add("Direction", Direction.ToString());
            properties.Add("VrtuTimestamp", DateTime.UtcNow.ToString("dd-MM-yyyyThh:mm:ss.ffff"));

            return(properties);
        }
コード例 #23
0
        public async Task <TransactionId> Post(CreateTransactionRequest request)
        {
            var id                 = Guid.NewGuid().ToString();
            var transactionId      = new TransactionId("transaction-" + id);
            var transactionRecord  = new Transaction(request.EmployeeId, transactionId, request.Date, request.Salary);
            var transactionCommand = new TransactionAddCommand(transactionId, transactionRecord);

            await CommandBus.PublishAsync(transactionCommand, CancellationToken.None).ConfigureAwait(false);

            return(transactionId);
        }
コード例 #24
0
 public bool CanVoid(CMSDataContext db)
 {
     return(db.Gateway().CanVoidRefund &&
            Approved == true &&
            !CanCredit(db) &&
            Voided != true &&
            Credited != true &&
            (Coupon ?? false) == false &&
            TransactionId.HasValue() &&
            Amt > 0);
 }
コード例 #25
0
 public bool CanCredit(CMSDataContext db)
 {
     return(db.Gateway().CanVoidRefund &&
            Approved == true &&
            Voided != true &&
            Credited != true &&
            (Coupon ?? false) == false &&
            TransactionId.HasValue() &&
            Batchtyp == "eft" || Batchtyp == "bankcard" &&
            Amt > 0);
 }
コード例 #26
0
 public Deposit GetDepositByTransactionId(TransactionId transactionId)
 {
     foreach (var deposit in _deposits)
     {
         if (deposit.TransactionId.Value == transactionId.Value)
         {
             return(deposit);
         }
     }
     return(null);
 }
コード例 #27
0
        public int CompareTo(TransactionOutput other)
        {
            if (other == null)
            {
                return(1);
            }

            var comp = TransactionId.CompareTo(other.TransactionId);

            return(comp != 0 ? comp : OutIndex - other.OutIndex);
        }
コード例 #28
0
ファイル: JournalFile.cs プロジェクト: dkardach/ravendb
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = ScratchPos.GetHashCode();
         hashCode = (hashCode * 397) ^ JournalPos.GetHashCode();
         hashCode = (hashCode * 397) ^ TransactionId.GetHashCode();
         hashCode = (hashCode * 397) ^ JournalNumber.GetHashCode();
         return(hashCode);
     }
 }
コード例 #29
0
 internal CreateTransaction(AccountId accId, TransactionId id, TransactionLabel label,
                            CreateAmount amount, string signature, TransactionDescription?description = null, TransactionMetadata?metadata = null)
 {
     AccountId   = accId;
     Id          = id;
     Label       = label;
     Amount      = amount;
     Metadata    = metadata ?? new TransactionMetadata();;
     Description = description ?? new TransactionDescription();
     Signature   = signature;
 }
コード例 #30
0
		 public override void TransactionCommitted( long transactionId, long checksum, long commitTimestamp )
		 {
			 lock ( this )
			 {
				  TransactionId current = _committedTransactionId.get();
				  if ( current == null || transactionId > current.TransactionIdConflict() )
				  {
						_committedTransactionId.set( new TransactionId( transactionId, checksum, commitTimestamp ) );
				  }
			 }
		 }
コード例 #31
0
ファイル: TransactionId.cs プロジェクト: Redi0/meijing-ui
 public virtual bool Equals(TransactionId that)
 {
     return true;
 }
コード例 #32
0
        public void Rollback()
        {
            if(InTransaction)
            {
                this.BeforeEnd();

                if(Tracer.IsDebugEnabled)
                {
                    Tracer.Debug("Rollback: "  + this.transactionId +
                                 " syncCount: " +
                                 (synchronizations != null ? synchronizations.Count : 0));
                }

                TransactionInfo info = new TransactionInfo();
                info.ConnectionId = this.session.Connection.ConnectionId;
                info.TransactionId = transactionId;
                info.Type = (int) TransactionType.Rollback;

                this.transactionId = null;
                this.session.Connection.SyncRequest(info);

                this.AfterRollback();
            }
        }
コード例 #33
0
ファイル: IAppendLog.cs プロジェクト: naasking/AppendLog
        ///// <summary>
        ///// Replay a log to an output stream.
        ///// </summary>
        ///// <param name="log"></param>
        ///// <param name="lastEvent"></param>
        ///// <param name="output"></param>
        ///// <returns></returns>
        //public static async Task<TransactionId> ReplayTo(this IAppendLog log, TransactionId lastEvent, IAppendLog target)
        //{
        //    using (var ie = log.Replay(lastEvent))
        //    {
        //        var buf = new byte[sizeof(long)];
        //        while (await ie.MoveNext())
        //        {
        //            TransactionId tx;
        //            Stream output;
        //            using (target.Append(out output, out tx))
        //            {
        //                lastEvent = ie.Transaction;
        //                Debug.Assert(tx == lastEvent);
        //                buf.Write(lastEvent.Id);
        //                await output.WriteAsync(buf, 0, buf.Length);
        //                await ie.Stream.CopyToAsync(output);
        //            }
        //        }
        //    }
        //    return lastEvent;
        //}

        /// <summary>
        /// Replay events using a callback.
        /// </summary>
        /// <param name="log"></param>
        /// <param name="lastEvent"></param>
        /// <param name="forEach"></param>
        /// <returns></returns>
        public static async Task Replay(this IAppendLog log, TransactionId lastEvent, Func<TransactionId, Stream, Task<bool>> forEach)
        {
            using (var ie = log.Replay(lastEvent))
            {
                while (await ie.MoveNext())
                {
                    if (!await forEach(ie.Transaction, ie.Stream))
                        return;
                }
            }
        }
コード例 #34
0
        public void InDoubt(Enlistment enlistment)
        {
            try
            {
                dtcControlEvent.Reset();

                Tracer.Debug("In Doubt notification received for TX id: " + this.transactionId);

                BeforeEnd();

                // Now notify the broker that Rollback should be performed.
                TransactionInfo info = new TransactionInfo();
                info.ConnectionId = this.connection.ConnectionId;
                info.TransactionId = this.transactionId;
                info.Type = (int)TransactionType.End;

                this.connection.CheckConnected();
                this.connection.SyncRequest(info);

                info.Type = (int)TransactionType.Rollback;
                this.connection.CheckConnected();
                this.connection.SyncRequest(info);

                Tracer.Debug("InDoubt Transaction Rollback Done TX id: " + this.transactionId);

                RecoveryLogger.LogRecovered(this.transactionId as XATransactionId);

                // if server responds that nothing needs to be done, then reply done.
                enlistment.Done();

                AfterRollback();
            }
            finally
            {
                this.currentEnlistment = null;
                this.transactionId = null;

                CountDownLatch latch = this.recoveryComplete;
                if (latch != null)
                {
                    latch.countDown();
                }

                this.dtcControlEvent.Set();
            }
        }
コード例 #35
0
        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            try
            {
                dtcControlEvent.Reset();

                Tracer.Debug("Prepare notification received for TX id: " + this.transactionId);

                BeforeEnd();

                // Before sending the request to the broker, log the recovery bits, if
                // this fails we can't prepare and the TX should be rolled back.
                RecoveryLogger.LogRecoveryInfo(this.transactionId as XATransactionId,
                                               preparingEnlistment.RecoveryInformation());

                // Inform the broker that work on the XA'sh TX Branch is complete.
                TransactionInfo info = new TransactionInfo();
                info.ConnectionId = this.connection.ConnectionId;
                info.TransactionId = this.transactionId;
                info.Type = (int) TransactionType.End;

                this.connection.CheckConnected();
                this.connection.SyncRequest(info);

                // Prepare the Transaction for commit.
                info.Type = (int) TransactionType.Prepare;
                IntegerResponse response = (IntegerResponse) this.connection.SyncRequest(info);
                if(response.Result == XA_READONLY)
                {
                    Tracer.Debug("Transaction Prepare done and doesn't need a commit, TX id: " + this.transactionId);

                    this.transactionId = null;
                    this.currentEnlistment = null;

                    // Read Only means there's nothing to recover because there was no
                    // change on the broker.
                    RecoveryLogger.LogRecovered(this.transactionId as XATransactionId);

                    // if server responds that nothing needs to be done, then reply prepared
                    // but clear the current state data so we appear done to the commit method.
                    preparingEnlistment.Prepared();

                    // Done so commit won't be called.
                    AfterCommit();
                }
                else
                {
                    Tracer.Debug("Transaction Prepare succeeded TX id: " + this.transactionId);

                    // If work finished correctly, reply prepared
                    preparingEnlistment.Prepared();
                }
            }
            catch(Exception ex)
            {
                Tracer.DebugFormat("Transaction[{0}] Prepare failed with error: {1}",
                                   this.transactionId, ex.Message);

                AfterRollback();
                preparingEnlistment.ForceRollback();
                try
                {
                    this.connection.OnException(ex);
                }
                catch (Exception error)
                {
                    Tracer.Error(error.ToString());
                }

                this.currentEnlistment = null;
                this.transactionId = null;
            }
            finally
            {
                this.dtcControlEvent.Set();
            }
        }
コード例 #36
0
ファイル: FileLog.cs プロジェクト: naasking/AppendLog
 /// <summary>
 /// Enumerate the sequence of transactions since <paramref name="last"/>.
 /// </summary>
 /// <param name="last">The last event seen.</param>
 /// <returns>A sequence of transactions since the given event.</returns>
 public IEventEnumerator Replay(TransactionId last)
 {
     if (!ReferenceEquals(path, last.Path))
         throw new ArgumentException("last", "The given transaction is not for this log");
     return new EventEnumerator(this, last);
 }
コード例 #37
0
ファイル: FileLog.cs プロジェクト: naasking/AppendLog
 /// <summary>
 /// Atomically append data to the durable store.
 /// </summary>
 /// <param name="transaction">The transaction being written.</param>
 /// <param name="transaction">The transaction being written.</param>
 /// <returns>A stream for writing.</returns>
 /// <remarks>
 /// The <paramref name="async"/> parameter is largely optional, in that it's safe to simply
 /// provide 'false' and everything will still work.
 /// </remarks>
 public IDisposable Append(out Stream output, out TransactionId transaction)
 {
     var x = writer;
     if (x == null) throw new ObjectDisposedException(string.Format("FileLog ({0}) has been disposed.", path));
     Monitor.Enter(x);
     if (writer == null) throw new ObjectDisposedException(string.Format("FileLog ({0}) has been disposed.", path));
     transaction = new TransactionId(next, path);
     x.Seek(next, SeekOrigin.Begin);
     output = new BoundedStream(x, next, int.MaxValue);
     return new Appender(this, writeBuffer);
 }
コード例 #38
0
ファイル: FileLog.cs プロジェクト: naasking/AppendLog
 public EventEnumerator(FileLog log, TransactionId last)
 {
     Contract.Requires(log != null);
     this.log = log;
     this.file = new FileStream(log.path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true);
     this.length = last.Id;
     this.Transaction = default(TransactionId);
 }
コード例 #39
0
        public void SinglePhaseCommit(SinglePhaseEnlistment enlistment)
        {
            try
            {
                dtcControlEvent.Reset();

                Tracer.Debug("Single Phase Commit notification received for TX id: " + this.transactionId);

                if (this.transactionId != null)
                {
                    BeforeEnd();

                    // Now notify the broker that a new XA'ish transaction has completed.
                    TransactionInfo info = new TransactionInfo();
                    info.ConnectionId = this.connection.ConnectionId;
                    info.TransactionId = this.transactionId;
                    info.Type = (int) TransactionType.CommitOnePhase;

                    this.connection.CheckConnected();
                    this.connection.SyncRequest(info);

                    Tracer.Debug("Transaction Single Phase Commit Done TX id: " + this.transactionId);

                    // if server responds that nothing needs to be done, then reply done.
                    enlistment.Done();

                    AfterCommit();
                }
            }
            catch(Exception ex)
            {
                Tracer.DebugFormat("Transaction[{0}] Single Phase Commit failed with error: {1}",
                                   this.transactionId, ex.Message);
                AfterRollback();
                enlistment.Done();
                try
                {
                    this.connection.OnException(ex);
                }
                catch (Exception error)
                {
                    Tracer.Error(error.ToString());
                }
            }
            finally
            {
                this.currentEnlistment = null;
                this.transactionId = null;

                this.dtcControlEvent.Set();
            }
        }
コード例 #40
0
        public void Begin(Transaction transaction)
        {
            Tracer.Debug("Begin notification received");

            if(InNetTransaction)
            {
                throw new TransactionInProgressException("A Transaction is already in Progress");
            }

            Guid rmId = ResourceManagerGuid;

            // Enlist this object in the transaction.
            this.currentEnlistment =
                transaction.EnlistDurable(rmId, this, EnlistmentOptions.None);

            Tracer.Debug("Enlisted in Durable Transaction with RM Id: " + rmId);

            TransactionInformation txInfo = transaction.TransactionInformation;

            XATransactionId xaId = new XATransactionId();
            this.transactionId = xaId;

            if(txInfo.DistributedIdentifier != Guid.Empty)
            {
                xaId.GlobalTransactionId = txInfo.DistributedIdentifier.ToByteArray();
                xaId.BranchQualifier = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
            }
            else
            {
                xaId.GlobalTransactionId = Encoding.UTF8.GetBytes(txInfo.LocalIdentifier);
                xaId.BranchQualifier = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
            }

            // Now notify the broker that a new XA'ish transaction has started.
            TransactionInfo info = new TransactionInfo();
            info.ConnectionId = this.connection.ConnectionId;
            info.TransactionId = this.transactionId;
            info.Type = (int) TransactionType.Begin;

            this.session.Connection.Oneway(info);

            if(Tracer.IsDebugEnabled)
            {
                Tracer.Debug("Began XA'ish Transaction:" + xaId.GlobalTransactionId.ToString());
            }
        }
コード例 #41
0
        /// <summary>
        /// Should be called from NetTxSession when created to check if any TX
        /// data is stored for recovery and whether the Broker has matching info
        /// stored.  If an Transaction is found that belongs to this client and is
        /// still alive on the Broker it will be recovered, otherwise the stored 
        /// data should be cleared.
        /// </summary>
        public void InitializeDtcTxContext()
        {
            // initialize the logger with the current Resource Manager Id
            RecoveryLogger.Initialize(ResourceManagerId);

            KeyValuePair<XATransactionId, byte[]>[] localRecoverables = RecoveryLogger.GetRecoverables();
            if (localRecoverables.Length == 0)
            {
                Tracer.Debug("Did not detect any open DTC transaction records on disk.");
                // No local data so anything stored on the broker can't be recovered here.
                return;
            }

            XATransactionId[] recoverables = TryRecoverBrokerTXIds();
            if (recoverables.Length == 0)
            {
                Tracer.Debug("Did not detect any recoverable transactions at Broker.");
                // Broker has no recoverable data so nothing to do here, delete the
                // old recovery log as its stale.
                RecoveryLogger.Purge();
                return;
            }

            List<KeyValuePair<XATransactionId, byte[]>> matches = new List<KeyValuePair<XATransactionId, byte[]>>();

            foreach(XATransactionId recoverable in recoverables)
            {
                foreach(KeyValuePair<XATransactionId, byte[]> entry in localRecoverables)
                {
                    if(entry.Key.Equals(recoverable))
                    {
                        Tracer.DebugFormat("Found a matching TX on Broker to stored Id: {0} reenlisting.", entry.Key);
                        matches.Add(entry);
                    }
                }
            }

            if (matches.Count != 0)
            {
                this.recoveryComplete = new CountDownLatch(matches.Count);

                foreach (KeyValuePair<XATransactionId, byte[]> recoverable in matches)
                {
                    this.transactionId = recoverable.Key;
                    Tracer.Info("Reenlisting recovered TX with Id: " + this.transactionId);
                    this.currentEnlistment =
                        TransactionManager.Reenlist(ResourceManagerGuid, recoverable.Value, this);
                }

                this.recoveryComplete.await();
                Tracer.Debug("All Recovered TX enlistments Reports complete, Recovery Complete.");
                TransactionManager.RecoveryComplete(ResourceManagerGuid);
                return;
            }

            // The old recovery information doesn't match what's on the broker so we
            // should discard it as its stale now.
            RecoveryLogger.Purge();
        }
コード例 #42
0
        public void Rollback(Enlistment enlistment)
        {
            try
            {
                dtcControlEvent.Reset();

                Tracer.Debug("Rollback notification received for TX id: " + this.transactionId);

                if (this.transactionId != null)
                {
                    BeforeEnd();

                    // Now notify the broker that a new XA'ish transaction has started.
                    TransactionInfo info = new TransactionInfo();
                    info.ConnectionId = this.connection.ConnectionId;
                    info.TransactionId = this.transactionId;
                    info.Type = (int) TransactionType.End;

                    this.connection.CheckConnected();
                    this.connection.SyncRequest(info);

                    info.Type = (int) TransactionType.Rollback;
                    this.connection.CheckConnected();
                    this.connection.SyncRequest(info);

                    Tracer.Debug("Transaction Rollback Done TX id: " + this.transactionId);

                    RecoveryLogger.LogRecovered(this.transactionId as XATransactionId);

                    // if server responds that nothing needs to be done, then reply done.
                    enlistment.Done();

                    AfterRollback();
                }
            }
            catch(Exception ex)
            {
                Tracer.DebugFormat("Transaction[{0}] Rollback failed with error: {1}",
                                   this.transactionId, ex.Message);
                AfterRollback();
                try
                {
                    this.connection.OnException(ex);
                }
                catch (Exception error)
                {
                    Tracer.Error(error.ToString());
                }
            }
            finally
            {
                this.currentEnlistment = null;
                this.transactionId = null;

                CountDownLatch latch = this.recoveryComplete;
                if (latch != null)
                {
                    latch.countDown();
                }

                this.dtcControlEvent.Set();
            }
        }
コード例 #43
0
        public void Begin()
        {
            if(!InTransaction)
            {
                this.transactionId = this.session.Connection.CreateLocalTransactionId();

                TransactionInfo info = new TransactionInfo();
                info.ConnectionId = this.session.Connection.ConnectionId;
                info.TransactionId = transactionId;
                info.Type = (int) TransactionType.Begin;

                this.session.Connection.Oneway(info);

                if(Tracer.IsDebugEnabled)
                {
                    Tracer.Debug("Begin:" + this.transactionId.ToString());
                }
            }
        }
コード例 #44
0
ファイル: FileLog.cs プロジェクト: naasking/AppendLog
 public async Task<bool> MoveNext()
 {
     if (log == null) throw new ObjectDisposedException("IEventEnumerator");
     var txid = Transaction.Id + length;
     if (txid == log.next || lengths.Count == 0 && await NoPreviousEntries(txid, log.next))
         return false;
     length = lengths.Peek() + EHDR_SIZE;
     Transaction = new TransactionId(txid, log.path);
     Stream = new BoundedStream(file, txid, (int)length - EHDR_SIZE);
     return true;
 }