Beispiel #1
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void verifyTransaction(TransactionIdStore transactionIdStore, TransactionMetadataCache positionCache, byte[] additionalHeader, int masterId, int authorId, long timeStarted, long latestCommittedTxWhenStarted, long timeCommitted, LogicalTransactionStore store) throws java.io.IOException
        private void VerifyTransaction(TransactionIdStore transactionIdStore, TransactionMetadataCache positionCache, sbyte[] additionalHeader, int masterId, int authorId, long timeStarted, long latestCommittedTxWhenStarted, long timeCommitted, LogicalTransactionStore store)
        {
            TransactionMetadata expectedMetadata;

            using (TransactionCursor cursor = store.GetTransactions(TransactionIdStore_Fields.BASE_TX_ID + 1))
            {
                bool hasNext = cursor.next();
                assertTrue(hasNext);
                CommittedTransactionRepresentation tx          = cursor.get();
                TransactionRepresentation          transaction = tx.TransactionRepresentation;
                assertArrayEquals(additionalHeader, transaction.AdditionalHeader());
                assertEquals(masterId, transaction.MasterId);
                assertEquals(authorId, transaction.AuthorId);
                assertEquals(timeStarted, transaction.TimeStarted);
                assertEquals(timeCommitted, transaction.TimeCommitted);
                assertEquals(latestCommittedTxWhenStarted, transaction.LatestCommittedTxWhenStarted);
                expectedMetadata = new TransactionMetadata(masterId, authorId, tx.StartEntry.StartPosition, tx.StartEntry.checksum(), timeCommitted);
            }

            positionCache.Clear();

            TransactionMetadata actualMetadata = store.GetMetadataFor(transactionIdStore.LastCommittedTransactionId);

            assertEquals(expectedMetadata, actualMetadata);
        }
Beispiel #2
0
        private ImmutableTransaction BuildTestTransaction(string uri = null, string guid = null, int?statusCode = null, int?subStatusCode = null, IEnumerable <ErrorData> transactionExceptionDatas = null)
        {
            var transactionMetadata = new TransactionMetadata();

            if (uri != null)
            {
                transactionMetadata.SetUri(uri);
            }
            if (statusCode != null)
            {
                transactionMetadata.SetHttpResponseStatusCode(statusCode.Value, subStatusCode, _errorService);
            }
            if (transactionExceptionDatas != null)
            {
                transactionExceptionDatas.ForEach(data => transactionMetadata.TransactionErrorState.AddExceptionData(data));
            }

            var name     = TransactionName.ForWebTransaction("foo", "bar");
            var segments = Enumerable.Empty <Segment>();
            var metadata = transactionMetadata.ConvertToImmutableMetadata();

            guid = guid ?? Guid.NewGuid().ToString();

            var attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));

            return(new ImmutableTransaction(name, segments, metadata, DateTime.UtcNow, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), guid, false, false, false, 0.5f, false, string.Empty, null, attribDefSvc.AttributeDefs));
        }
Beispiel #3
0
        private IInternalTransaction BuildTestTransaction(bool isWebTransaction = true, string uri = null, string referrerUri = null, string guid = null, int?statusCode = null, int?subStatusCode = null, string referrerCrossProcessId = null, string transactionCategory = "defaultTxCategory", string transactionName = "defaultTxName", ErrorData exceptionData = null, ErrorData customErrorData = null, bool isSynthetics = true, bool isCAT = true, bool includeUserAttributes = false, float priority = 0.5f, bool sampled = false, string traceId = "traceId")
        {
            var name = isWebTransaction
                ? TransactionName.ForWebTransaction(transactionCategory, transactionName)
                : TransactionName.ForOtherTransaction(transactionCategory, transactionName);

            var segments = Enumerable.Empty <Segment>();

            var placeholderMetadataBuilder = new TransactionMetadata();
            var placeholderMetadata        = placeholderMetadataBuilder.ConvertToImmutableMetadata();

            var immutableTransaction = new ImmutableTransaction(name, segments, placeholderMetadata, DateTime.UtcNow, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), guid, false, false, false, priority, sampled, traceId, null, _attribDefs);

            var internalTransaction = new Transaction(Mock.Create <IConfiguration>(), immutableTransaction.TransactionName, _timerFactory.StartNewTimer(), DateTime.UtcNow, Mock.Create <ICallStackManager>(), Mock.Create <IDatabaseService>(), priority, Mock.Create <IDatabaseStatementParser>(), Mock.Create <IDistributedTracePayloadHandler>(), Mock.Create <IErrorService>(), _attribDefs);

            var adaptiveSampler = Mock.Create <IAdaptiveSampler>();

            Mock.Arrange(() => adaptiveSampler.ComputeSampled(ref priority)).Returns(sampled);
            internalTransaction.SetSampled(adaptiveSampler);

            var transactionMetadata = internalTransaction.TransactionMetadata;

            PopulateTransactionMetadataBuilder(transactionMetadata, uri, statusCode, subStatusCode, referrerCrossProcessId, exceptionData, customErrorData, isSynthetics, isCAT, referrerUri, includeUserAttributes);

            return(internalTransaction);
        }
        public async Task<ByteString> PostTransaction(ByteString rawMutation, IReadOnlyList<SignatureEvidence> authentication)
        {
            Mutation mutation;
            try
            {
                // Verify that the mutation can be deserialized
                mutation = MessageSerializer.DeserializeMutation(rawMutation);
            }
            catch (InvalidProtocolBufferException)
            {
                throw new TransactionInvalidException("InvalidMutation");
            }

            if (!mutation.Namespace.Equals(this.ledgerId))
                throw new TransactionInvalidException("InvalidNamespace");

            if (mutation.Records.Count == 0)
                throw new TransactionInvalidException("InvalidMutation");

            if (mutation.Records.Any(record => record.Key.Value.Count > MaxKeySize))
                throw new TransactionInvalidException("InvalidMutation");

            ValidateAuthentication(authentication, MessageSerializer.ComputeHash(rawMutation.ToByteArray()));

            ParsedMutation parsedMutation = ParsedMutation.Parse(mutation);

            // All assets must have an overall zero balance

            IReadOnlyDictionary<AccountKey, AccountStatus> accounts =
                await this.store.GetAccounts(parsedMutation.AccountMutations.Select(entry => entry.AccountKey));

            var groups = parsedMutation.AccountMutations
                .GroupBy(account => account.AccountKey.Asset.FullPath)
                .Select(group => group.Sum(entry => entry.Balance - accounts[entry.AccountKey].Balance));

            if (groups.Any(group => group != 0))
                throw new TransactionInvalidException("UnbalancedTransaction");

            DateTime date = DateTime.UtcNow;

            await this.validator.Validate(parsedMutation, authentication, accounts);

            TransactionMetadata metadata = new TransactionMetadata(authentication);

            byte[] rawMetadata = SerializeMetadata(metadata);

            Transaction transaction = new Transaction(rawMutation, date, new ByteString(rawMetadata));
            byte[] serializedTransaction = MessageSerializer.SerializeTransaction(transaction);

            try
            {
                await this.store.AddTransactions(new[] { new ByteString(serializedTransaction) });
            }
            catch (ConcurrentMutationException)
            {
                throw new TransactionInvalidException("OptimisticConcurrency");
            }

            return new ByteString(MessageSerializer.ComputeHash(serializedTransaction));
        }
Beispiel #5
0
        public async Task <DomainValidationResult <ITransaction> > MarkAccountTransactionAsCanceledAsync(
            IAccount account,
            TransactionMetadata metadata,
            CancellationToken cancellationToken = default
            )
        {
            var result = new DomainValidationResult <ITransaction>();

            if (!account.TransactionExists(metadata))
            {
                result.AddFailedPreconditionError("Transaction does not exists.");
            }

            if (result.IsValid)
            {
                var transaction = account.FindTransaction(metadata);

                transaction.MarkAsCanceled();

                await _accountRepository.CommitAsync(true, cancellationToken);

                return(transaction.Cast <Transaction>());
            }

            return(result);
        }
Beispiel #6
0
        public ActionResult TransactionCompleate(TransactionMetadata transactionMetadata, string command)
        {
            var transaction = GetTransactionSession();

            transaction.InvoiceNumber   = transactionMetadata.InvoiceNumber;
            transaction.TransactionDate = transactionMetadata.TransactionDate;
            SetTransactionSession(transaction);
            switch (command)
            {
            case "Add SKU":
                return(RedirectToAction("SkuList"));

            case "Save":
                if (_transaction.TransctionCompleate(transaction))
                {
                    ResetSession();
                    return(RedirectToAction("Home", "Dashboard"));
                }
                return(View("Transaction", transactionMetadata));

            default:
                ResetSession();
                return(RedirectToAction("Home", "Dashboard"));
            }
        }
Beispiel #7
0
        public async Task WithdrawAsync_WithWrongBundle_ShouldBeOfTypeValidationResultWithErrors()
        {
            // Arrange
            var account = new Account(new UserId());

            var metadata = new TransactionMetadata
            {
                { "UserId", account.Id.ToString() },
                { "Email", "*****@*****.**" }
            };

            var service = new AccountService(TestMock.AccountRepository.Object, TestValidator);

            // Act
            var result = await service.CreateTransactionAsync(
                account,
                Money.Twenty.Amount,
                CurrencyType.Money,
                TransactionType.Withdraw,
                metadata);

            // Assert
            result.Should().BeOfType <DomainValidationResult <ITransaction> >();

            result.Errors.Should().NotBeEmpty();
        }
Beispiel #8
0
        public async Task WithdrawAsync_WithCurrencyMoney_ShouldBeOfTypeValidationResult()
        {
            // Arrange
            var account      = new Account(new UserId());
            var moneyAccount = new MoneyAccountDecorator(account);
            var transaction  = moneyAccount.Deposit(Money.OneHundred);

            transaction.MarkAsSucceeded();

            TestMock.AccountRepository.Setup(accountRepository => accountRepository.CommitAsync(true, It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            var metadata = new TransactionMetadata
            {
                { "UserId", account.Id.ToString() },
                { "Email", "*****@*****.**" }
            };

            var service = new AccountService(TestMock.AccountRepository.Object, TestValidator);

            // Act
            var result = await service.CreateTransactionAsync(
                moneyAccount,
                Money.OneHundred.Amount,
                CurrencyType.Money,
                TransactionType.Withdraw,
                metadata);

            // Assert
            result.Should().BeOfType <DomainValidationResult <ITransaction> >();

            TestMock.AccountRepository.Verify(accountRepository => accountRepository.CommitAsync(true, It.IsAny <CancellationToken>()), Times.Once());
        }
        public bool TransctionCompleate(TransactionMetadata transactionMetadata)
        {
            var transaction = new Entitys.Transaction
            {
                InvoiceNumber   = transactionMetadata.InvoiceNumber,
                TransactionDate = transactionMetadata.TransactionDate,
                IsSales         = transactionMetadata.IsSales
            };
            var totalAmount = transactionMetadata.Products.Sum(x => x.Amount);

            if (transactionMetadata.IsSales)
            {
                transaction.SalesAmount = totalAmount;
            }
            else
            {
                transaction.PurchaseAmount = totalAmount;
            }
            foreach (var product in transactionMetadata.Products)
            {
                var skuId             = Convert.ToInt64(product.SkuId);
                var transctionHistory = new TransactionHistory
                {
                    Amount      = product.Amount,
                    BrandId     = Convert.ToInt64(product.BrandId),
                    CompnayId   = Convert.ToInt64(product.CompanyId),
                    ProductId   = Convert.ToInt64(product.ProductId),
                    Quantity    = product.Quantity,
                    Rate        = product.Rate,
                    SkuId       = skuId,
                    Transaction = transaction
                };
                _basicUnit.TransactionHistorys.Add(transctionHistory);
                var stockInfo = _basicUnit.Stocks.GetStockBySkuId(skuId);
                if (transactionMetadata.IsSales)
                {
                    stockInfo.Quantity -= product.Quantity;
                }
                else
                {
                    stockInfo.Quantity += product.Quantity;
                }
                stockInfo.Rate = product.Rate;
            }
            _basicUnit.Transactions.Add(transaction);

            try
            {
                _basicUnit.Save();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #10
0
        public void Build_HasEmptyPathHashIfNeverSet()
        {
            var transactionMetadata = new TransactionMetadata();
            var immutableMetadata   = transactionMetadata.ConvertToImmutableMetadata();

            NrAssert.Multiple(
                () => Assert.AreEqual(null, immutableMetadata.CrossApplicationPathHash),
                () => Assert.AreEqual(0, immutableMetadata.CrossApplicationAlternatePathHashes.Count())
                );
        }
Beispiel #11
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;
 }
        public virtual TransactionMetadata CacheTransactionMetadata(long txId, LogPosition position, int masterId, int authorId, long checksum, long timeWritten)
        {
            if (position.ByteOffset == -1)
            {
                throw new Exception("StartEntry.position is " + position);
            }

            TransactionMetadata result = new TransactionMetadata(masterId, authorId, position, checksum, timeWritten);

            _txStartPositionCache.put(txId, result);
            return(result);
        }
Beispiel #13
0
        public void Build_HasZeroAlternatePathHashesIfSetOnce()
        {
            var metadata = new TransactionMetadata();

            metadata.SetCrossApplicationPathHash("pathHash1");
            var immutableMetadata = metadata.ConvertToImmutableMetadata();

            NrAssert.Multiple(
                () => Assert.AreEqual("pathHash1", immutableMetadata.CrossApplicationPathHash),
                () => Assert.AreEqual(0, immutableMetadata.CrossApplicationAlternatePathHashes.Count())
                );
        }
Beispiel #14
0
        public void Getters_CATContentLength()
        {
            var metadata = new TransactionMetadata();

            Assert.AreEqual(-1, metadata.GetCrossApplicationReferrerContentLength());

            metadata.SetCrossApplicationReferrerContentLength(44444);
            Assert.AreEqual(44444, metadata.GetCrossApplicationReferrerContentLength());

            metadata.SetCrossApplicationReferrerContentLength(5432);
            Assert.AreEqual(5432, metadata.GetCrossApplicationReferrerContentLength());
        }
Beispiel #15
0
        public void Getters_QueueTime()
        {
            var metadata = new TransactionMetadata();

            Assert.IsNull(metadata.QueueTime);

            metadata.SetQueueTime(TimeSpan.FromSeconds(20));
            Assert.AreEqual(20, metadata.QueueTime?.Seconds);

            metadata.SetQueueTime(TimeSpan.FromSeconds(55));
            Assert.AreEqual(55, metadata.QueueTime?.Seconds);
        }
        private byte[] SerializeMetadata(TransactionMetadata metadata)
        {
            Messages.TransactionMetadata transactionMetadataBuilder = new Messages.TransactionMetadata();
            transactionMetadataBuilder.Signatures.Add(metadata.Signatures.Select(
                                                          signature => new Messages.TransactionMetadata.Types.SignatureEvidence()
            {
                PublicKey = Google.Protobuf.ByteString.Unsafe.FromBytes(signature.PublicKey.ToByteArray()),
                Signature = Google.Protobuf.ByteString.Unsafe.FromBytes(signature.Signature.ToByteArray())
            }));

            return(transactionMetadataBuilder.ToByteArray());
        }
Beispiel #17
0
        private ImmutableTransaction BuildTestImmutableTransaction(bool isWebTransaction = true, string guid = null, float priority = 0.5f, bool sampled = false, string traceId = "traceId", bool isDTParticipant = false)
        {
            var name = TransactionName.ForWebTransaction("category", "name");

            var segments = Enumerable.Empty <Segment>();

            var placeholderMetadataBuilder = new TransactionMetadata();
            var placeholderMetadata        = placeholderMetadataBuilder.ConvertToImmutableMetadata();

            var immutableTransaction = new ImmutableTransaction(name, segments, placeholderMetadata, DateTime.UtcNow, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), guid, false, false, false, priority, sampled, traceId, BuildMockTracingState(isDTParticipant), _attribDefs);

            return(immutableTransaction);
        }
        public static IInternalTransaction CreateDefaultTransaction(bool isWebTransaction          = true, string uri     = null,
                                                                    string guid                    = null, int?statusCode = null, int?subStatusCode = null, string referrerCrossProcessId = null,
                                                                    string transactionCategory     = "defaultTxCategory", string transactionName = "defaultTxName", bool addSegment = true,
                                                                    IEnumerable <Segment> segments = null, bool sampled = false, IConfigurationService configurationService         = null, Exception exception = null)
        {
            var name = isWebTransaction
                ? TransactionName.ForWebTransaction(transactionCategory, transactionName)
                : TransactionName.ForOtherTransaction(transactionCategory, transactionName);

            segments = segments ?? Enumerable.Empty <Segment>();

            var placeholderMetadataBuilder = new TransactionMetadata();
            var placeholderMetadata        = placeholderMetadataBuilder.ConvertToImmutableMetadata();

            var immutableTransaction = new ImmutableTransaction(name, segments, placeholderMetadata, DateTime.Now, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), guid, false, false, false, 0.5f, false, string.Empty, null, _attribDefSvc.AttributeDefs);
            var priority             = 0.5f;

            var configuration = configurationService?.Configuration ?? GetDefaultConfiguration();
            var errorService  = configurationService != null ? new ErrorService(configurationService) : new ErrorService(Mock.Create <IConfigurationService>());

            var internalTransaction = new Transaction(configuration, immutableTransaction.TransactionName, Mock.Create <ITimer>(), DateTime.UtcNow, Mock.Create <ICallStackManager>(),
                                                      _databaseService, priority, Mock.Create <IDatabaseStatementParser>(), Mock.Create <IDistributedTracePayloadHandler>(),
                                                      errorService, _attribDefSvc.AttributeDefs);

            if (exception != null)
            {
                internalTransaction.NoticeError(exception);
            }

            if (segments.Any())
            {
                foreach (var segment in segments)
                {
                    internalTransaction.Add(segment);
                }
            }
            else if (addSegment)
            {
                internalTransaction.Add(SimpleSegmentDataTests.createSimpleSegmentBuilder(TimeSpan.Zero, TimeSpan.Zero, 0, null, new MethodCallData("typeName", "methodName", 1), Enumerable.Empty <KeyValuePair <string, object> >(), "MyMockedRootNode", false));
            }

            var adaptiveSampler = Mock.Create <IAdaptiveSampler>();

            Mock.Arrange(() => adaptiveSampler.ComputeSampled(ref priority)).Returns(sampled);
            internalTransaction.SetSampled(adaptiveSampler);
            var transactionMetadata = internalTransaction.TransactionMetadata;

            PopulateTransactionMetadataBuilder(transactionMetadata, errorService, uri, statusCode, subStatusCode, referrerCrossProcessId);

            return(internalTransaction);
        }
        public KeyValuePair <bool, TransactionMetadata> AddSkuToInvoice(TransactionMetadata transactionMetadata, SkuForTransactionMetadata skuForTransactionMetadata)
        {
            if (transactionMetadata.Products == null)
            {
                transactionMetadata.Products = new List <StockMetaData>();
            }

            var skuFortansaction = transactionMetadata.Products.FirstOrDefault(x => x.SkuId == skuForTransactionMetadata.SkuId);

            if (skuFortansaction != null)
            {
                if (transactionMetadata.IsSales)
                {
                    if (skuForTransactionMetadata.SkuId != null)
                    {
                        var stackInfo = _basicUnit.Stocks.GetStockBySkuId((Int64)skuForTransactionMetadata.SkuId);
                        if ((skuFortansaction.Quantity + skuForTransactionMetadata.TransactionQuantity) > stackInfo.Quantity)
                        {
                            return(new KeyValuePair <bool, TransactionMetadata>(false, transactionMetadata));
                        }
                    }
                }

                skuFortansaction.Quantity       += skuForTransactionMetadata.TransactionQuantity;
                skuForTransactionMetadata.Rate   = skuForTransactionMetadata.TransactionRate;
                skuForTransactionMetadata.Amount = skuForTransactionMetadata.TransactionAmount;
                return(new KeyValuePair <bool, TransactionMetadata>(true, transactionMetadata));
            }
            if (skuForTransactionMetadata.SkuId != null)
            {
                var skuInfo = _basicUnit.Skus.GetSkuById((Int64)skuForTransactionMetadata.SkuId);

                transactionMetadata.Products.Add(new StockMetaData
                {
                    Amount      = skuForTransactionMetadata.TransactionAmount,
                    BrandId     = skuInfo.BrandId,
                    SkuName     = skuInfo.SkuName,
                    BrandName   = skuInfo.BrandName,
                    CompanyId   = skuInfo.CompanyId,
                    CompanyName = skuInfo.CompanyName,
                    ProductId   = skuInfo.ProductId,
                    ProductName = skuInfo.ProductName,
                    Quantity    = skuForTransactionMetadata.TransactionQuantity,
                    Rate        = skuForTransactionMetadata.TransactionRate,
                    SkuId       = skuForTransactionMetadata.SkuId
                });
                return(new KeyValuePair <bool, TransactionMetadata>(true, transactionMetadata));
            }
            return(new KeyValuePair <bool, TransactionMetadata>(false, transactionMetadata));
        }
            public override bool Equals(object o)
            {
                if (this == o)
                {
                    return(true);
                }
                if (o == null || this.GetType() != o.GetType())
                {
                    return(false);
                }
                TransactionMetadata that = ( TransactionMetadata )o;

                return(MasterIdConflict == that.MasterIdConflict && AuthorIdConflict == that.AuthorIdConflict && ChecksumConflict == that.ChecksumConflict && TimeWrittenConflict == that.TimeWrittenConflict && Objects.Equals(StartPositionConflict, that.StartPositionConflict));
            }
Beispiel #21
0
        private ImmutableTransaction BuildTestTransaction(bool ignoreAutoBrowserMonitoring = false, bool ignoreAllBrowserMonitoring = false)
        {
            var name     = TransactionName.ForWebTransaction("foo", "bar");
            var segments = Enumerable.Empty <Segment>();
            var metadata = new TransactionMetadata().ConvertToImmutableMetadata();
            var guid     = Guid.NewGuid().ToString();

            _internalTransaction = Mock.Create <IInternalTransaction>();
            Mock.Arrange(() => _internalTransaction.IgnoreAllBrowserMonitoring).Returns(ignoreAllBrowserMonitoring);
            Mock.Arrange(() => _internalTransaction.IgnoreAutoBrowserMonitoring).Returns(ignoreAutoBrowserMonitoring);

            var attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));

            return(new ImmutableTransaction(name, segments, metadata, DateTime.UtcNow, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), guid, ignoreAutoBrowserMonitoring, ignoreAllBrowserMonitoring, false, 0.5f, false, string.Empty, null, attribDefSvc.AttributeDefs));
        }
Beispiel #22
0
        private ImmutableTransaction BuildTestTransaction(IEnumerable <Segment> segments = null, DateTime?startTime = null)
        {
            var transactionMetadata = new TransactionMetadata();

            var name = TransactionName.ForWebTransaction("foo", "bar");

            segments = segments ?? Enumerable.Empty <Segment>();
            var metadata = transactionMetadata.ConvertToImmutableMetadata();

            startTime = startTime ?? DateTime.Now;
            var duration = TimeSpan.FromSeconds(1);
            var guid     = Guid.NewGuid().ToString();

            return(new ImmutableTransaction(name, segments, metadata, startTime.Value, duration, duration, guid, false, false, false, 1.23f, false, string.Empty, null, _attribDefs));
        }
Beispiel #23
0
        public void Build_OnlyRetainsACertainNumberOfAlternatePathHashes()
        {
            var maxPathHashes = PathHashMaker.AlternatePathHashMaxSize;

            var transactionMetadata = new TransactionMetadata();

            Enumerable.Range(0, maxPathHashes + 2).ForEach(number => transactionMetadata.SetCrossApplicationPathHash($"pathHash{number}"));
            var immutableMetadata = transactionMetadata.ConvertToImmutableMetadata();

            NrAssert.Multiple(
                () => Assert.AreEqual($"pathHash{PathHashMaker.AlternatePathHashMaxSize + 1}", immutableMetadata.CrossApplicationPathHash),
                () => Assert.AreEqual(PathHashMaker.AlternatePathHashMaxSize, immutableMetadata.CrossApplicationAlternatePathHashes.Count()),
                () => Assert.IsFalse(immutableMetadata.CrossApplicationAlternatePathHashes.Contains($"pathHash{PathHashMaker.AlternatePathHashMaxSize + 1}"))
                );
        }
Beispiel #24
0
        public void Build_PutsAllPathHashesIntoAlternatePathHashes_ExceptLatest()
        {
            var metadata = new TransactionMetadata();

            metadata.SetCrossApplicationPathHash("pathHash1");
            metadata.SetCrossApplicationPathHash("pathHash2");
            metadata.SetCrossApplicationPathHash("pathHash3");
            var immutableMetadata = metadata.ConvertToImmutableMetadata();

            NrAssert.Multiple(
                () => Assert.AreEqual("pathHash3", immutableMetadata.CrossApplicationPathHash),
                () => Assert.AreEqual(2, immutableMetadata.CrossApplicationAlternatePathHashes.Count()),
                () => Assert.IsTrue(immutableMetadata.CrossApplicationAlternatePathHashes.Contains("pathHash1")),
                () => Assert.IsTrue(immutableMetadata.CrossApplicationAlternatePathHashes.Contains("pathHash2"))
                );
        }
        public static ImmutableTransaction CreateTestTransactionWithSegments(IEnumerable <Segment> segments)
        {
            var uri = "sqlTrace/Uri";

            var transactionMetadata = new TransactionMetadata();

            transactionMetadata.SetUri(uri);

            var name     = TransactionName.ForWebTransaction("TxsWithSegments", "TxWithSegmentX");
            var metadata = transactionMetadata.ConvertToImmutableMetadata();
            var guid     = Guid.NewGuid().ToString();

            var transaction = new ImmutableTransaction(name, segments, metadata, DateTime.UtcNow, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), guid, false, false, false, 0.5f, false, string.Empty, null, _attribDefSvc.AttributeDefs);

            return(transaction);
        }
        public static MemoryPoolEntry CreateMemoryPoolEntry(TransactionMetadata walletTransaction, TransactionBroadcastEntry broadcastEntry)
        {
            var entry = new MemoryPoolEntry
            {
                Transaction     = walletTransaction,
                TransactionTime = DateTime.UtcNow.ToUnixTime()
            };

            if (broadcastEntry != null)
            {
                entry.BroadcastState  = broadcastEntry.State.ToBroadcastState();
                entry.MemoryPoolError = broadcastEntry.MempoolError.GetMemoryPoolError();
                entry.ConsensusError  = broadcastEntry.MempoolError.GetMemoryPoolError();
            }

            return(entry);
        }
        public void TransactionExists_WithInvalidTransactionMetadata_ShouldThrowInvalidOperationException(
            TransactionMetadata transactionMetadata,
            TransactionMetadata transactionMetadataQuery
            )
        {
            // Arrange
            var account      = new Account(new UserId());
            var moneyAccount = new MoneyAccountDecorator(account);

            moneyAccount.Deposit(Money.Fifty).MarkAsSucceeded();
            moneyAccount.Charge(Money.Ten, transactionMetadata);

            // Act
            var transactionExists = account.TransactionExists(transactionMetadataQuery);

            // Assert
            transactionExists.Should().BeFalse();
        }
        public void FindTransaction_WithValidTransactionMetadata_ShouldBeEquals(
            TransactionMetadata transactionMetadata,
            TransactionMetadata transactionMetadataQuery
            )
        {
            // Arrange
            var account      = new Account(new UserId());
            var moneyAccount = new MoneyAccountDecorator(account);

            moneyAccount.Deposit(Money.Fifty).MarkAsSucceeded();
            var expectedTransaction = moneyAccount.Charge(Money.Ten, transactionMetadata);

            // Act
            var actualTransaction = account.FindTransaction(transactionMetadataQuery);

            // Assert
            actualTransaction.Should().Be(expectedTransaction);
        }
        public void FindTransaction_WithInvalidTransactionMetadata_ShouldThrowInvalidOperationException(
            TransactionMetadata transactionMetadata,
            TransactionMetadata transactionMetadataQuery
            )
        {
            // Arrange
            var account      = new Account(new UserId());
            var moneyAccount = new MoneyAccountDecorator(account);

            moneyAccount.Deposit(Money.Fifty).MarkAsSucceeded();
            moneyAccount.Charge(Money.Ten, transactionMetadata);

            // Act
            var action = new Action(() => account.FindTransaction(transactionMetadataQuery));

            // Assert
            action.Should().Throw <InvalidOperationException>();
        }
        private ImmutableTransaction BuildTestTransaction(DateTime?startTime = null, TimeSpan?duration = null, TimeSpan?responseTime = null, string uri = null, string guid = null)
        {
            var transactionMetadata = new TransactionMetadata();

            if (uri != null)
            {
                transactionMetadata.SetUri(uri);
            }

            var name     = TransactionName.ForWebTransaction("foo", "bar");
            var segments = Enumerable.Empty <Segment>();
            var metadata = transactionMetadata.ConvertToImmutableMetadata();

            startTime = startTime ?? DateTime.Now;
            duration  = duration ?? TimeSpan.FromSeconds(1);
            guid      = guid ?? Guid.NewGuid().ToString();

            return(new ImmutableTransaction(name, segments, metadata, startTime.Value, duration.Value, responseTime, guid, false, false, false, 1.2f, false, string.Empty, null, _attribDefs));
        }
Beispiel #31
0
        public void AddUserAttribute_LastInWins()
        {
            var key    = "testKey";
            var valueA = "valueA";
            var valueB = "valueB";

            var metadata = new TransactionMetadata();

            metadata.AddUserAttribute(key, valueA);
            metadata.AddUserAttribute(key, valueB);

            var immutableTransactionMetadata = metadata.ConvertToImmutableMetadata();

            var userAttributes = immutableTransactionMetadata.UserAttributes.ToDictionary();

            var result = userAttributes[key];

            Assert.AreEqual(result, valueB);
        }
        private byte[] SerializeMetadata(TransactionMetadata metadata)
        {
            Messages.TransactionMetadata transactionMetadataBuilder = new Messages.TransactionMetadata();
            transactionMetadataBuilder.Signatures.Add(metadata.Signatures.Select(
                signature => new Messages.TransactionMetadata.Types.SignatureEvidence()
                {
                    PublicKey = Google.Protobuf.ByteString.Unsafe.FromBytes(signature.PublicKey.ToByteArray()),
                    Signature = Google.Protobuf.ByteString.Unsafe.FromBytes(signature.Signature.ToByteArray())
                }));

            return transactionMetadataBuilder.ToByteArray();
        }