public ActionResult AddTransaction()
 {
     ImportTransactions model = new ImportTransactions();
     TransactionInfo t = new TransactionInfo();
     t.TransactionTypes = model.GetTransactionTypes();
     t.Schedules = model.GetSchedules();
     return View("ImportTransRecord",t);
 }
 public void LoadData(Guid clientId)
 {
     ICashFlowManagerService service = new CashFlowManagerService();
     SelectedTransaction = new TransactionInfo(){StartDate=DateTime.Now};
     Transactions = service.GetTransactions(clientId);
     IncomeTransactions = new List<TransactionInfo>();
     ExpenseTransactions = new List<TransactionInfo>();
     IncomeTransactions.AddRange((from t in Transactions where t.TransactionTypeId == new Guid(StringEnum.GetStringValue(Enumerations.TransactionType.Income)) select t).ToList());
     ExpenseTransactions.AddRange((from t in Transactions where t.TransactionTypeId == new Guid(StringEnum.GetStringValue(Enumerations.TransactionType.Expense)) select t).ToList());
     Schedules = service.GetScheduleTypes();
     TransactionTypes = service.GetTransactionTypes();
 }
        public override TransactionInfo ProcessSubscription(ref SubscriptionInfo sub, GatewayInfo gateway, GatewayTypeInfo gatewayType, ICustomer customer, CreditCardInfo card, bool isTrial, bool testTransaction)
        {
            ProPayRequest request = null;
            ProPayResponse response = null;
            TransactionInfo transactionInfo = new TransactionInfo();

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;
            decimal amount = isTrial == true ? sub.TrialAmount : sub.Amount;

            request = new ProPayRequest(requestUrl, loginId, transactionKey, customer, card, amount, testTransaction);
            response = request.Process();


            sub.LastProcessedDate = DateTime.Now;

            transactionInfo.Id = Guid.NewGuid();
            transactionInfo.SubscriptionId = sub.Id;
            transactionInfo.GatewayId = sub.GatewayId;
            transactionInfo.CreateDate = DateTime.Now;
            transactionInfo.IsTrial = isTrial;
            transactionInfo.Type = TransactionType.Standard;
            transactionInfo.Amount = amount;
            transactionInfo.GatewayAmount = gateway.TransactionFee;
            transactionInfo.OrderId = sub.RefId;
            if (response == null)
            {
                sub.LastProcessingStatus = TransactionStatus.Error;
                transactionInfo.ResponseText = "";
                transactionInfo.Status = TransactionStatus.Error;
            }
            else if (response.Code == ProPayResponseCode.Success)
            {
                sub.LastProcessingStatus = TransactionStatus.Approved;
                if (isTrial)
                    sub.TrialOccurrencesDone += 1;
                else
                    sub.TotalOccurrencesDone += 1;
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Approved;
            }
            else
            {
                sub.LastProcessingStatus = TransactionStatus.Error;
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Error;
            }
            return transactionInfo;
        }
示例#4
0
        public ANetRequest(string requsetUrl, string loginId, string transactionKey, ICustomer customer, CreditCardInfo card, string transactionID, TransactionInfo transaction, bool testTransaction, decimal amount)
            : this(requsetUrl, loginId, transactionKey, customer, card, amount, testTransaction)
        {
            if (transaction != null && !string.IsNullOrEmpty(transaction.ResponseText))
            {
                string[] tokens = transaction.ResponseText.Split('|');
                this._transactionID = tokens[6];

                if (string.IsNullOrEmpty(this._transactionID))
                    this._transactionID = transactionID;
            }
            else
            {
                this._transactionID = transactionID;
            }

            
        }
        private async Task <Transaction> ConvertResponseToModelAndInsertAsync(TransactionInfo responseTransaction)
        {
            var result = new Transaction
            {
                Address       = responseTransaction.Address,
                Amount        = responseTransaction.Amount,
                Confirmations = responseTransaction.Confirmations,
                IsProcessed   = false,
                From          = responseTransaction.From,
                Memo          = responseTransaction.Memo,
                Symbol        = responseTransaction.Symbol,
                Time          = responseTransaction.Time,
                TxKey         = responseTransaction.TxKey,
                TxHash        = responseTransaction.TxHash,
                UserId        = responseTransaction.UserId
            };

            result = await _transactionsRepository.InsertAsync(result);

            return(result);
        }
        public async Task CascadingAbortTransaction()
        {
            long id1 = this.transactionManager.StartTransaction(TimeSpan.FromTicks(this.storageDelay.Ticks * 2));
            long id2 = this.transactionManager.StartTransaction(TimeSpan.FromTicks(this.storageDelay.Ticks * 4));

            var info2 = new TransactionInfo(id2);

            info2.DependentTransactions.Add(id1);

            this.transactionManager.CommitTransaction(info2);
            OrleansTransactionAbortedException abort;

            Assert.True(this.transactionManager.GetTransactionStatus(id2, out abort) == TransactionStatus.InProgress);

            this.transactionManager.AbortTransaction(id1, new OrleansTransactionAbortedException(id1));

            var e = await Assert.ThrowsAsync <OrleansCascadingAbortException>(() => WaitForTransactionCommit(id2, this.logMaintenanceInterval + this.storageDelay));

            Assert.True(e.TransactionId == id2);
            Assert.True(e.DependentTransactionId == id1);
        }
示例#7
0
        public override Task <TransactionInfo> GetFullRegistryBlock(HeightHashRequest request, ServerCallContext context)
        {
            RegistryFullBlock block = (RegistryFullBlock)_registryChainDataService.Get(new SyncHashKey(request.Height, request.Hash.ToByteArray()));

            if (block != null)
            {
                TransactionInfo transactionInfo = new TransactionInfo
                {
                    BlockType       = block.BlockType,
                    PacketType      = (uint)block.PacketType,
                    SyncBlockHeight = block.SyncBlockHeight,
                    Content         = ByteString.CopyFrom(block.RawData.ToArray())
                };

                return(Task.FromResult(transactionInfo));
            }

            return(Task.FromResult(new TransactionInfo {
                IsEmpty = true
            }));
        }
        public virtual 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);

                SignalTransactionStarted();

                if (Tracer.IsDebugEnabled)
                {
                    Tracer.Debug("Begin:" + this.transactionId);
                }
            }
        }
示例#9
0
        public static List <TransactionInfo> GetETHTransList(ref List <TransactionInfo> transList, int count)
        {
            var sql   = $"select CoinType,Height,Txid, ToAddress,Value,ConfirmCount from Transactions where CoinType in ('eth','{Config._coinname}') and ConfirmCount < {count}";
            var table = ExecuSqlToDataTable(sql);

            if (table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    var trans = new TransactionInfo();
                    trans.coinType     = table.Rows[i]["CoinType"].ToString();
                    trans.toAddress    = table.Rows[i]["ToAddress"].ToString();
                    trans.txid         = table.Rows[i]["Txid"].ToString();
                    trans.confirmCount = Convert.ToUInt32(table.Rows[i]["ConfirmCount"]);
                    trans.height       = Convert.ToUInt32(table.Rows[i]["Height"]);
                    trans.value        = Convert.ToDecimal(table.Rows[i]["Value"]);
                    transList.Add(trans);
                }
            }
            return(transList);
        }
示例#10
0
        partial void SetTransactionInfo(TransactionInfo transactionInfo)
        {
            //This instance of TransactionInfo acts as a "shared model" between this view and the order details view.
            //The scenario says that these 2 views are decoupled, so they don't share the view model, they are only tied
            //with this TransactionInfo
            this.orderDetailsViewModel.TransactionInfo = transactionInfo;

            //Bind the CompositeOrderView header to a string representation of the TransactionInfo shared instance (we expect the details view model to modify it from user interaction).
            MultiBinding binding = new MultiBinding();

            binding.Bindings.Add(new Binding("TransactionType")
            {
                Source = transactionInfo
            });
            binding.Bindings.Add(new Binding("TickerSymbol")
            {
                Source = transactionInfo
            });
            binding.Converter = new OrderHeaderConverter();
            BindingOperations.SetBinding(this, HeaderInfoProperty, binding);
        }
示例#11
0
 public DepositDetails(Deposit deposit, DataAsset dataAsset, Address consumer, byte[] pepper, uint timestamp,
                       TransactionInfo transaction, uint confirmationTimestamp = 0, bool rejected           = false,
                       EarlyRefundTicket earlyRefundTicket = null, TransactionInfo claimedRefundTransaction = null,
                       bool refundClaimed = false, string kyc = null, uint confirmations = 0, uint requiredConfirmations = 0)
 {
     Id                       = deposit.Id;
     Deposit                  = deposit;
     DataAsset                = dataAsset;
     Consumer                 = consumer;
     Pepper                   = pepper;
     Timestamp                = timestamp;
     Transaction              = transaction;
     ConfirmationTimestamp    = confirmationTimestamp;
     Rejected                 = rejected;
     EarlyRefundTicket        = earlyRefundTicket;
     ClaimedRefundTransaction = claimedRefundTransaction;
     RefundClaimed            = refundClaimed;
     Kyc                      = kyc;
     Confirmations            = confirmations;
     RequiredConfirmations    = requiredConfirmations;
 }
        public void ShouldNotMakeATradeWhenArgsDoesntConteinValidSellerIdOrBuyerId()
        {
            //Arrange
            TradingService  tradingService  = new TradingService(accountTableRepository, stockPriceTableRepository, historyTableRepository, stockOfClientTableRepository, logger);
            TransactionInfo transactionInfo = new TransactionInfo();

            transactionInfo.BuyerId          = 1;
            transactionInfo.SellerId         = 2;
            transactionInfo.TypeOfStock      = "AAA";
            transactionInfo.QuantityOfStocks = 20;
            StockPriceEntity stockPriceEntity = new StockPriceEntity()
            {
                TypeOfStock  = transactionInfo.TypeOfStock,
                PriceOfStock = 4
            };

            stockPriceTableRepository.GetStockPriceEntityByStockType(Arg.Is <string>(
                                                                         w => w == transactionInfo.TypeOfStock)).Returns(stockPriceEntity);
            //Act
            tradingService.MakeATrade(transactionInfo);
        }
示例#13
0
            public void JoinTransaction()
            {
                TransactionInfo info = TransactionContext.GetTransactionInfo();
                logger.Info($"Grain {grain} is joining transaction {info.TransactionId}.");

                // are we already part of the transaction?
                if (this.transactions.Contains(info.TransactionId))
                {
                    return;
                }

                TransactionalResourceVersion readVersion;
                if (!TryGetVersion(info.TransactionId, out readVersion))
                {
                    throw new OrleansTransactionVersionDeletedException(info.TransactionId);
                }

                if (info.IsReadOnly && readVersion.TransactionId > this.stableVersion)
                {
                    throw new OrleansTransactionUnstableVersionException(info.TransactionId);
                }

                info.RecordRead(transactionalResource, readVersion, this.stableVersion);

                writeLowerBound = Math.Max(writeLowerBound, info.TransactionId - 1);

                if (this.version.TransactionId > info.TransactionId || this.writeLowerBound >= info.TransactionId)
                {
                    throw new OrleansTransactionWaitDieException(info.TransactionId);
                }

                TransactionalResourceVersion nextVersion = TransactionalResourceVersion.Create(info.TransactionId,
                    this.version.TransactionId == info.TransactionId ? this.version.WriteNumber + 1 : 1);

                info.RecordWrite(transactionalResource, this.version, this.stableVersion);

                this.version = nextVersion;

                this.transactions.Remove(info.TransactionId);
            }
示例#14
0
        public List <TransactionInfo> RetrunListOfProducts(string filepath)
        {
            string xmlData = HttpContext.Current.Server.MapPath(filepath);
            List <TransactionInfo> results = new List <TransactionInfo>();
            TransactionInfo        addObj;
            PaymentDetailInfo      addDetail;
            DataSet l_set   = new DataSet();
            string  xmlPath = HttpContext.Current.Server.MapPath("~/FileData/");

            l_set.ReadXml(string.Concat(xmlPath, filepath));
            if (l_set != null)
            {
                DataTable l_tbl = new DataTable();
                DataTable d_tbl = new DataTable();
                l_tbl = l_set.Tables["Transaction"];
                d_tbl = l_set.Tables["PaymentDetails"];
                foreach (DataRow dr in l_tbl.Rows)
                {
                    addObj                 = new TransactionInfo();
                    addObj.Id              = dr["id"].ToString();
                    addObj.Status          = dr["Status"].ToString();
                    addObj.TransactionDate = Convert.ToDateTime(dr["TransactionDate"].ToString());
                    DataTable tblFiltered = d_tbl.AsEnumerable()
                                            .Where(row => row.Field <Int32>("Transaction_Id") == Convert.ToInt32(dr["Transaction_Id"]))
                                            .CopyToDataTable();
                    addObj.PaymentDetailInfo = new List <PaymentDetailInfo>();
                    foreach (DataRow detail in tblFiltered.Rows)
                    {
                        addDetail              = new PaymentDetailInfo();
                        addDetail.Amount       = Convert.ToDecimal(detail["Amount"].ToString());
                        addDetail.CurrencyCode = detail["CurrencyCode"].ToString();
                        addObj.PaymentDetailInfo.Add(addDetail);
                    }
                    results.Add(addObj);
                }
            }


            return(results);
        }
示例#15
0
        private static TransferTransaction ToTransferTransaction(JObject tx, TransactionInfo txInfo)
        {
            var transaction = tx["transaction"].ToObject <JObject>();
            //Bug - It seems the dotnetcore does not
            //understand the Integer.
            //The workaround it to double cast the version
            int versionValue = -1879048189;
            var version      = transaction["version"];

            try
            {
                versionValue = (int)((uint)version);
            }
            catch (Exception)
            {
                versionValue = (int)version;
            }

            var network   = TransactionMappingUtils.ExtractNetworkType(versionValue);
            var deadline  = transaction["deadline"].ToObject <UInt64DTO>().ToUInt64();
            var maxFee    = transaction["maxFee"]?.ToObject <UInt64DTO>().ToUInt64();
            var recipient = transaction["recipient"]?.ToObject <string>();
            var mosaics   = transaction["mosaics"]?.ToObject <List <MosaicDTO> >();
            var message   = transaction["message"].ToObject <JObject>();
            var signature = transaction["signature"].ToObject <string>();
            var signer    = transaction["signer"].ToObject <string>();

            return(new TransferTransaction(network,
                                           TransactionMappingUtils.ExtractTransactionVersion(versionValue),
                                           new Deadline(deadline),
                                           maxFee,
                                           Recipient.From(Address.CreateFromHex(recipient)),
                                           mosaics != null ? mosaics.Select(m => new Mosaic(new MosaicId(m.Id.ToUInt64()), m.Amount.ToUInt64())).ToList() : new List <Mosaic> {
            },
                                           GetMessage(message),
                                           signature,
                                           new PublicAccount(signer, network),
                                           txInfo
                                           ));
        }
示例#16
0
        public override Response ProcessRollbackTransaction(TransactionInfo info)
        {
            if (TrackTransactions && info != null)
            {
                ConnectionId connectionId = info.ConnectionId;
                if (connectionId != null)
                {
                    ConnectionState cs = null;

                    if (connectionStates.TryGetValue(connectionId, out cs))
                    {
                        TransactionState transactionState = cs[info.TransactionId];
                        if (transactionState != null)
                        {
                            transactionState.AddCommand(info);
                            return(new Tracked(new RemoveTransactionAction(info, this)));
                        }
                    }
                }
            }
            return(null);
        }
        private static LockFundsTransaction ToLockFundsTransaction(JObject tx, TransactionInfo txInfo)
        {
            var transaction = tx["transaction"].ToObject <JObject>();
            var version     = transaction["version"];


            //Bug - It seems the dotnetcore does not
            //understand the Integer.
            //The workaround it to double cast the version
            int versionValue;

            try
            {
                versionValue = (int)((uint)version);
            }
            catch (Exception)
            {
                versionValue = (int)version;
            }

            var network   = TransactionMappingUtils.ExtractNetworkType(versionValue);
            var txVersion = TransactionMappingUtils.ExtractTransactionVersion(versionValue);


            var deadline  = new Deadline(transaction["deadline"].ToObject <UInt64DTO>().ToUInt64());
            var maxFee    = transaction["maxFee"]?.ToObject <UInt64DTO>().ToUInt64();
            var signature = transaction["signature"].ToObject <string>();
            var signer    = new PublicAccount(transaction["signer"].ToObject <string>(), network);
            var mosaic    = new MosaicId(transaction["mosaicId"].ToObject <UInt64DTO>().ToUInt64());
            var amount    = transaction["amount"].ToObject <UInt64DTO>().ToUInt64();
            var duration  = transaction["duration"].ToObject <UInt64DTO>().ToUInt64();
            var hash      = transaction["hash"].ToObject <string>();

            return(new LockFundsTransaction(network, txVersion, deadline, maxFee,
                                            new Mosaic(mosaic, amount), duration,
                                            new SignedTransaction(string.Empty, hash, string.Empty,
                                                                  EntityType.AGGREGATE_BONDED, network),
                                            signature, signer, txInfo));
        }
示例#18
0
        internal new TransferTransaction Apply(string input)
        {
            var tx = JsonConvert.DeserializeObject <TransferTransactionInfoDTO>(input);

            var txInfo   = TransactionInfo.Create(tx.Meta.Height, tx.Meta.Index, tx.Meta.Id, tx.Meta.Hash, tx.Meta.MerkleComponentHash);
            var deadline = new Deadline(tx.Transaction.Deadline);
            var mosaics  = tx.Transaction.Mosaics.Select(m => new Mosaic(new MosaicId(BitConverter.ToUInt64(m.MosaicId.FromHex(), 0)), m.Amount)).ToList();

            IMessage message;

            try
            {
                message = PlainMessage.Create(Encoding.UTF8.GetString(tx.Transaction.Message.Payload.FromHex()));
            }
            catch (Exception)
            {
                try
                {
                    message = PlainMessage.Create(tx.Transaction.Message.Payload);
                }
                catch (Exception)
                {
                    message = EmptyMessage.Create();
                }
            }

            return(new TransferTransaction(
                       ExtractNetworkType(tx.Transaction.Version),
                       ExtractTransactionVersion(tx.Transaction.Version),
                       deadline,
                       tx.Transaction.Fee,
                       Address.CreateFromEncoded(tx.Transaction.Recipient),
                       mosaics,
                       message,
                       tx.Transaction.Signature,
                       new PublicAccount(tx.Transaction.Signer, ExtractNetworkType(tx.Transaction.Version)),
                       txInfo
                       ));
        }
示例#19
0
        public void ShouldAddTransactiont()
        {
            //Arrange
            var transactionTableRepository = Substitute.For <ITableRepository <TransactionHistory> >();
            TransactionHistoryService transactionService = new TransactionHistoryService(transactionTableRepository);
            TransactionInfo           transactInfo       = new TransactionInfo
            {
                CustomerOrderId = 1,
                SalerOrderId    = 1,
                TrDateTime      = new DateTime(2019, 08, 21)
            };

            //Act
            transactionService.AddTransactionInfo(transactInfo);
            //Assert
            transactionTableRepository.Received(1).Add(Arg.Is <TransactionHistory>(
                                                           w => w.CustomerOrderID == 1 &&
                                                           w.SalerOrderID == 1 &&
                                                           w.TransactionDateTime == new DateTime(2019, 08, 21)

                                                           ));
        }
示例#20
0
        // Gets the list of transactions by given account id, and page,
        // conv must = false if smart contract transactions requested
        public TransactionsData AccountTransactions(string id, int page, int limit, bool conv = true)
        {
            if (limit < 10 || limit > 25)
            {
                limit = 25;
            }
            if (page <= 0)
            {
                page = 1;
            }

            using (var client = CreateApi())
            {
                // Get the list of transactions from the API
                var offset   = limit * (page - 1);
                var trs      = client.TransactionsGet(Base58Encoding.Decode(id), offset, limit + 1);
                var lastPage = page;

                // Prepare the result
                var result = new TransactionsData
                {
                    Page         = page,
                    Transactions = new List <TransactionInfo>(),
                    HaveNextPage = trs.Transactions.Count > limit,
                    LastPage     = lastPage
                };

                // Fill data and return the result
                var count = Math.Min(limit, trs.Transactions.Count);
                for (var i = 0; i < count; i++)
                {
                    var t     = trs.Transactions[i];
                    var tInfo = new TransactionInfo(i + offset + 1, t.Id, t.Trxn);
                    result.Transactions.Add(tInfo);
                }
                result.NumStr = count > 0 ? $"{offset + 1} - {offset + count} of {offset + count}" : "-";
                return(result);
            }
        }
示例#21
0
        // Gets transaction data from API by given transaction id
        public TransactionInfo TransactionInfo(string id)
        {
            using (var client = CreateApi())
            {
                // Prepare transaction id for request
                var ids  = id.Split('.');
                var trId = new TransactionId()
                {
                    Index    = int.Parse(ids[1]) - 1,
                    PoolHash = ConvUtils.ConvertHashBack(ids[0])
                };

                // Get data from API
                var tr = client.TransactionGet(trId);

                // Prepare the result
                var tInfo = new TransactionInfo(0, null, tr.Transaction.Trxn)
                {
                    Id = id, Found = tr.Found
                };

                // if transaction was not found, return the result
                if (!tr.Found)
                {
                    return(tInfo);
                }

                // Otherwise, request block data and store block time in the result
                if (string.IsNullOrEmpty(tInfo.PoolHash))
                {
                    return(tInfo);
                }
                var pool = client.PoolInfoGet(ConvUtils.ConvertHashBack(tInfo.PoolHash), 0);
                tInfo.Time = ConvUtils.UnixTimeStampToDateTime(pool.Pool.Time);

                // return the result
                return(tInfo);
            }
        }
示例#22
0
        public IActionResult TransferMoney(IFormCollection formCollection)
        {
            int   fromAccountId  = Int32.Parse(formCollection["fromAccount"]);
            int   toAccountId    = Int32.Parse(formCollection["toAccount"]);
            float transferAmount = float.Parse(formCollection["transferAmount"]);

            if (fromAccountId != toAccountId)
            {
                Account fromAccount = AccountInfo(fromAccountId);
                Account toAccount   = AccountInfo(toAccountId);


                if (fromAccount.amount < transferAmount || fromAccount.amount <= 0)
                {
                    return(RedirectToAction("BankAccountOverview"));
                }

                fromAccount.amount -= transferAmount;
                toAccount.amount   += transferAmount;

                TransactionInfo fromAccountInfo = TransactionDetailCreater(
                    fromAccount.account_id, transferAmount, fromAccount.amount, true);
                SContext.Add(fromAccountInfo);
                SContext.SaveChanges();

                TransactionInfo toAccountInfo = TransactionDetailCreater(
                    toAccount.account_id, transferAmount, toAccount.amount, false);
                toAccountInfo.transaction_id = fromAccountInfo.transaction_id;
                SContext.Add(toAccountInfo);

                SContext.Update(fromAccount);
                SContext.Update(toAccount);
                SContext.SaveChanges();

                return(View("/Views/Home/TransferMoneyConfirmation.cshtml", fromAccountInfo));
            }

            return(View("/Views/Home/BankAccountOverview.cshtml"));
        }
示例#23
0
        public void Run(bool testNet = false)
        {
            _logger.Information("------------------------------");
            _logger.Information("Starting Marvin...");
            _logger.Information("Getting current price...");
            var meanPrices = GetMeanPrices();

            _logger.Information($"ICXUSD current price: {meanPrices}");
            var tx = CreateTransaction(meanPrices);

            _logger.Information($"Updating Daedric...");
            var result = UpdateDaedric(tx);

            _logger.Information($"Deadric updated tx hash: {result}");
            ExceptionHelper.TryNoException(() =>
            {
                var getTransactionByHash   = new GetTransactionByHash(_appsetting.Network_Url);
                TransactionInfo postResult = getTransactionByHash.Invoke(result).Result;
                _logger.Information($"Transaction info : {postResult.ToString()}");
            }, _logger);
            _logger.Information("Completed");
        }
        public override Response processCommitTransactionTwoPhase(TransactionInfo info)
        {
            if (TrackTransactions && info != null)
            {
                ConnectionId connectionId = info.ConnectionId;
                if (connectionId != null)
                {
                    ConnectionState cs = null;

                    if (cs != null)
                    {
                        TransactionState transactionState = cs[info.TransactionId];
                        if (transactionState != null)
                        {
                            transactionState.addCommand(info);
                            return(new Tracked(new RemoveTransactionAction(info, this)));
                        }
                    }
                }
            }
            return(null);
        }
        private void ReadTransactionFromMessage(Message message, TransactionFlowOption txFlowOption)
        {
            TransactionInfo transactionInfo = null;

            try
            {
                transactionInfo = this.formatter.ReadTransaction(message);
            }
            catch (TransactionException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Error);
                this.FaultOnMessage(message, System.ServiceModel.SR.GetString("SFxTransactionDeserializationFailed", new object[] { exception.Message }), "TransactionHeaderMalformed");
            }
            if (transactionInfo != null)
            {
                TransactionMessageProperty.Set(transactionInfo, message);
            }
            else if (txFlowOption == TransactionFlowOption.Mandatory)
            {
                this.FaultOnMessage(message, System.ServiceModel.SR.GetString("SFxTransactionFlowRequired"), "TransactionHeaderMissing");
            }
        }
示例#26
0
        public override Response ProcessEndTransaction(TransactionInfo info)
        {
            if (TrackTransactions && info != null)
            {
                ConnectionId connectionId = info.ConnectionId;
                if (connectionId != null)
                {
                    ConnectionState cs = null;

                    if (connectionStates.TryGetValue(connectionId, out cs))
                    {
                        TransactionState transactionState = cs[info.TransactionId];
                        if (transactionState != null)
                        {
                            transactionState.AddCommand(info);
                        }
                    }
                }
                return(TRACKED_RESPONSE_MARKER);
            }
            return(null);
        }
示例#27
0
        public void AddTransaction(TransactionInfo info)
        {
            bool isAdd = true;

            for (int i = 0; i < txItems.Count; i++)
            {
                if (txItems[i]._info.Transaction.Hash == info.Transaction.Hash)
                {
                    isAdd = false;
                    break;
                }
            }

            if (isAdd)
            {
                TxItem item = new TxItem(info);

                item.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(56)))), ((int)(((byte)(66)))));
                item.Location  = new System.Drawing.Point(30, 16 + (txItems.Count) * (70 + 10));
                item.Name      = "txItem" + info.Transaction.Hash.ToString();
                item.Size      = new System.Drawing.Size(500, 70);
                item.TabIndex  = 100;

                this.pan_history.Controls.Add(item);

                txItems.Add(item);

                if (txItems.Count * 80 + 16 > pan_history.Height)
                {
                    vsb_history.Maximum = txItems.Count * 80 + 16 - pan_history.Height + 16;
                    vsb_history.Show();
                }
            }

            if (txItems.Count > 0)
            {
                lbl_no_history.Hide();
            }
        }
        private static MosaicMetadataTransaction ToMetadataTransaction(JObject tx, TransactionInfo txInfo)
        {
            var transaction = tx["transaction"].ToObject <JObject>();
            var version     = transaction["version"];
            //var transactions = transaction["transactions"];
            //var metatransaction = transactions["transaction"];
            //Bug - It seems the dotnetcore does not
            //understand the Integer.
            //The workaround it to double cast the version
            int versionValue;

            try
            {
                versionValue = (int)((uint)version);
            }
            catch (Exception)
            {
                versionValue = (int)version;
            }

            var network           = TransactionMappingUtils.ExtractNetworkType(versionValue);
            var txVersion         = TransactionMappingUtils.ExtractTransactionVersion(versionValue);
            var deadline          = new Deadline(transaction["deadline"].ToObject <UInt64DTO>().ToUInt64());
            var maxFee            = transaction["maxFee"]?.ToObject <UInt64DTO>().ToUInt64();
            var signature         = transaction["signature"].ToObject <string>();
            var signer            = new PublicAccount(transaction["signer"].ToObject <string>(), network);
            var type              = EntityTypeExtension.GetRawValue(transaction["type"].ToObject <int>());
            var scopedMetadataKey = transaction["scopedMetadataKey"].ToObject <UInt64DTO>().ToUInt64();
            var targetKey         = new PublicAccount(transaction["targetKey"].ToObject <string>(), network);
            var targetId          = new MosaicId(transaction["targetMosaicId"].ToObject <UInt64DTO>().ToUInt64());

            var valueSizeDelta = transaction["valueSizeDelta"].ToObject <short>();
            var valueSize      = transaction["valueSize"].ToObject <ushort>();
            var value          = transaction["value"].ToObject <string>();

            var mosaicMetadataTransaction = new MosaicMetadataTransaction(network, txVersion, type, deadline, maxFee, scopedMetadataKey, targetKey, targetId, value, valueSizeDelta, valueSize, signature, signer, txInfo);

            return(mosaicMetadataTransaction);
        }
示例#29
0
        public void Rollback()
        {
            if (!InTransaction)
            {
                throw new StompException("Invalid State: Not Currently in a Transaction");
            }

            BeforeEnd();

            var info = new TransactionInfo
            {
                ConnectionId  = _session.Connection.ConnectionId,
                TransactionId = TransactionId,
                Type          = (Int32)TransactionType.Rollback
            };

            TransactionId = null;
            _session.Connection.SyncRequest(info);

            AfterRollback();
            _synchronizations.Clear();
        }
示例#30
0
        void startTransaction()
        {
            List <Byte> rs485packet = null;
            List <Byte> txPacket    = null;

            if (transactionQ.Count > 0)
            {
                TransactionInfo tInfo = transactionQ.Dequeue();


                rs485packet = rs485Driver.Packetize((byte)tInfo.deviceId, (byte)tInfo.command, tInfo.data);

                if (rs485packet != null)
                {
                    //txPacket = xbeeDriver.getTxPacket(tInfo.deviceId, rs485packet);
                    //byte[] txBuffer = txPacket.ToArray();
                    byte[] txBuffer = rs485packet.ToArray();
                    spDriver.Write(txBuffer, 0, rs485packet.Count);
                    //spDriver.WriteToPort(txBuffer);

                    #region TRACE_CODE
                    String traceString = DateTime.Now.ToString();
                    foreach (Byte b in txBuffer)
                    {
                        traceString += "0x" + b.ToString("x2") + " ";
                    }
                    traceString += Environment.NewLine;

                    _andonTrace.TraceInformation(traceString);
                    foreach (TraceListener l in _andonTrace.Listeners)
                    {
                        l.Flush();
                    }

                    #endregion
                }
            }
            transactionTimer.Start();
        }
        protected void BtnUpdate_Click(object sender, EventArgs e)
        {
            TransactionInfo t1 = new TransactionInfo();

            BusInfo binfo = new BusInfo();

            if (t1.AlreadyBooked(DropDownBusId.SelectedItem.Text) == false)
            {
                binfo.UpdateBus(DropDownBusId.SelectedItem.Text, TxtSource.Text, TxtDestination.Text, Convert.ToDateTime(TxtDate.Text).Date, Convert.ToDateTime(TxtTime.Text), Convert.ToInt32(TxtSeat.Text), Convert.ToInt32(TxtFare.Text), TxtType.Text);
                Response.Redirect("Admin.aspx");
            }
            else
            {
                TxtSource.Text      = "Cannot Update";
                TxtDestination.Text = "";
                TxtDate.Text        = "";
                TxtTime.Text        = "";
                TxtFare.Text        = "";
                TxtSeat.Text        = "";
                TxtType.Text        = "";
            }
        }
        public static async Task <List <string>[]> GetNestedTransactionIds(int tier, List <ITransactionAttributionGrain>[] tiers)
        {
            TransactionInfo ti = TransactionContext.GetTransactionInfo();

            List <string>[] results = new List <string> [tier + 1 + tiers.Length];
            results[tier] = new List <string>(new[] { ti?.Id });

            if (tiers.Length == 0)
            {
                return(results);
            }

            List <ITransactionAttributionGrain> nextTier = tiers.FirstOrDefault();

            List <ITransactionAttributionGrain>[] nextTiers = tiers.Skip(1).ToArray();
            List <string>[][] tiersResults = await Task.WhenAll(nextTier.Select(g => g.GetNestedTransactionIds(tier + 1, nextTiers)));

            foreach (List <string>[] result in tiersResults)
            {
                if (result.Length != results.Length)
                {
                    throw new ApplicationException("Invalid result length");
                }
                for (int i = tier + 1; i < results.Length; i++)
                {
                    if (results[i] != null)
                    {
                        results[i].AddRange(result[i]);
                    }
                    else
                    {
                        results[i] = result[i];
                    }
                }
            }

            return(results);
        }
    public AddressEntryDialogViewModel(Network network, TransactionInfo info)
    {
        _network          = network;
        _info             = info;
        IsQrButtonVisible = WebcamQrReader.IsOsPlatformSupported;

        SetupCancel(enableCancel: true, enableCancelOnEscape: true, enableCancelOnPressed: true);

        this.ValidateProperty(x => x.To, ValidateToField);

        this.WhenAnyValue(x => x.To)
        .Skip(1)
        .Subscribe(ParseToField);

        PasteCommand     = ReactiveCommand.CreateFromTask(async() => await OnPasteAsync());
        AutoPasteCommand = ReactiveCommand.CreateFromTask(async() => await OnAutoPasteAsync());
        QrCommand        = ReactiveCommand.CreateFromTask(async() =>
        {
            ShowQrCameraDialogViewModel dialog = new(_network);
            var result = await NavigateDialogAsync(dialog, NavigationTarget.CompactDialogScreen);
            if (!string.IsNullOrWhiteSpace(result.Result))
            {
                To = result.Result;
            }
        });

        var nextCommandCanExecute =
            this.WhenAnyValue(x => x.To)
            .Select(to =>
        {
            var addressFilled = !string.IsNullOrEmpty(to);
            var hasError      = Validations.Any;

            return(addressFilled && !hasError);
        });

        NextCommand = ReactiveCommand.Create(() => Close(DialogResultKind.Normal, BitcoinAddress.Create(To, _network)), nextCommandCanExecute);
    }
示例#34
0
 public TransactionInfo TransactionInfo(string id)
 {
     using (var client = CreateApi())
     {
         var ids   = id.Split('.');
         var tr    = client.TransactionGet($"{ids[0]}:{int.Parse(ids[1]) - 1}");
         var tInfo = new TransactionInfo(0, id, tr.Transaction)
         {
             Found = tr.Found
         };
         if (!tr.Found)
         {
             return(tInfo);
         }
         if (string.IsNullOrEmpty(tInfo.PoolHash))
         {
             return(tInfo);
         }
         var pool = client.PoolInfoGet(ConvUtils.ConvertHashBackAscii(tInfo.PoolHash), 0);
         tInfo.Age = ConvUtils.UnixTimeStampToDateTime(pool.Pool.Time).ToString("G");
         return(tInfo);
     }
 }
示例#35
0
            public void Search()
            {
                string query = String.Format(@"select
                                    DISTINCT
                                    ct.TRANSACTION_LINK,
                                    ct.TRANSACTION_ID,
                                    ct.TRANSACTION_TIME,
                                    ct.TRANSACTION_TYPE,
                                    ct.TRANSACT_GUID,
                                    ct.SUMM,
                                    ca.NAME,
                                    ctn.DOP_INFO,
                                    cp.L_NAME,
                                    cp.F_NAME,
                                    cp.M_NAME,
                                    cp.FULL_NAME,
                                    ctr.NAME AS REASON,
                                    ctn.NOTES,
                                    ct.CARD_CODE
                                from CARD_TRANSACTIONS ct
                                    INNER JOIN CARD_PEOPLE_ACCOUNTS cpa ON ct.ACCOUNT_ID = cpa.PEOPLE_ACCOUNT_ID
                                    INNER JOIN CARD_ACCOUNT_TYPES ca ON cpa.ACCOUNT_TYPE_ID = ca.ACCOUNT_TYPE_ID
                                    LEFT JOIN CARD_TRANSACTION_NOTES ctn ON ct.TRANSACT_GUID = ctn.TRANSACT_GUID
                                    LEFT JOIN CARD_TRANSFER_REASONS ctr ON ctn.TRANSFER_REASON_ID = ctr.TRANSFER_REASON_ID
                                    LEFT JOIN CARD_PEOPLES cp ON cpa.PEOPLE_ID = cp.PEOPLE_ID
                                {0}
                                ORDER BY ct.TRANSACTION_LINK, ct.TRANSACTION_TIME DESC", searchString);
                string connectionstring = WebConfigurationManager.ConnectionStrings["crmConnectionString"].ToString();
                SqlConnection con = new SqlConnection(connectionstring);
                con.Open();
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.CommandTimeout = 120000;
                SqlDataReader rdr = cmd.ExecuteReader();

                foreach (DbDataRecord record in rdr)
                {
                    TransactionInfo ti = new TransactionInfo();
                    ti.account_name = record["NAME"].ToString();

                    if (record["CARD_CODE"] != DBNull.Value)
                        ti.card_code = Convert.ToInt64(record["CARD_CODE"]);

                    if (record["TRANSACTION_LINK"] != DBNull.Value)
                        ti.transaction_link = Convert.ToInt64(record["TRANSACTION_LINK"]);

                    if (record["DOP_INFO"] != DBNull.Value)
                        ti.dop_info = record["DOP_INFO"].ToString();

                    if (record["FULL_NAME"] != DBNull.Value)
                        ti.full_name = record["FULL_NAME"].ToString();

                    if (record["TRANSACTION_ID"] != DBNull.Value)
                        ti.transaction_id = Convert.ToInt64(record["TRANSACTION_ID"]);

                    if (record["TRANSACTION_TIME"] != DBNull.Value)
                        ti.transaction_time = Convert.ToDateTime(record["TRANSACTION_TIME"]);

                    if (record["TRANSACTION_TYPE"] != DBNull.Value)
                        ti.transaction_type = Convert.ToInt32(record["TRANSACTION_TYPE"]);

                    if (record["SUMM"] != DBNull.Value)
                    {
                        if(ti.transaction_type == 161)
                            ti.bpSpented = Convert.ToDecimal(record["SUMM"]);
                        else
                            if(ti.transaction_type == 162)
                                ti.bpAccrued = Convert.ToDecimal(record["SUMM"]);
                    }

                    ti.TransactionGuid = Guid.Parse(record["TRANSACT_GUID"].ToString());

                    if (record["REASON"] != DBNull.Value)
                        ti.REASON = record["REASON"].ToString();

                    if (record["NOTES"] != DBNull.Value)
                        ti.NOTES = record["NOTES"].ToString();

                    if (ti.transaction_link == null)
                    {
                        TransactionInfo tiSearch = Transactions.FirstOrDefault(p => p.TransactionGuid == ti.TransactionGuid);

                        if (tiSearch == null)
                            Transactions.Add(ti);
                        else
                            if (ti.transaction_type == 161)
                                tiSearch.bpSpented = ti.bpSpented;
                            else
                                if (ti.transaction_type == 162)
                                    tiSearch.bpAccrued = ti.bpAccrued;
                    }
                    else
                    {
                        TransactionInfo tiSearch = Transactions.FirstOrDefault(p => p.transaction_id == ti.transaction_link);

                        if (tiSearch == null)
                        {
                            Transactions.Add(ti);
                            ti.NOTES = "Отмена транзакции " + ti.transaction_link.ToString();
                        }
                        else
                        {
                            tiSearch.transaction_link = ti.transaction_link;
                            tiSearch.NOTES += "\r\n" + "Отмена транзакции " + ti.transaction_link.ToString();
                        }
                    }
                }

                con.Close();
            }
        /// <summary>
        /// Begin a new transaction with the given name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="level">The level.</param>
        /// <exception cref="PersistentLayer.Exceptions.BusinessLayerException">
        /// The transaction name cannot be null or empty;BeginTransaction
        /// or
        /// BeginTransaction
        /// or
        /// Error on beginning a new transaction.;BeginTransaction
        /// </exception>
        public virtual void BeginTransaction(string name, IsolationLevel? level)
        {
            if (name == null || name.Trim().Equals(string.Empty))
                throw new BusinessLayerException("The transaction name cannot be null or empty", "BeginTransaction");

            if (this.Exists(name))
                throw new BusinessLayerException(string.Format("The transaction name ({0}) to add is used by another point.", name), "BeginTransaction");

            int index = transactions.Count;
            ITransactionInfo info = new TransactionInfo(name, index);

            if (this.transactions.Count == 0)
            {
                try
                {
                    ISession session = this.GetCurrentSession();
                    if (level == null)
                        session.BeginTransaction();
                    else
                        session.BeginTransaction(level.Value);
                }
                catch (Exception ex)
                {
                    throw new BusinessLayerException("Error on beginning a new transaction.", "BeginTransaction", ex);
                }
            }
            this.transactions.Push(info);
        }
示例#37
0
        public void handleMessage(Message msg)
        {

            if (msg is MessageMessage)
            {
                MessageMessage omsg = (MessageMessage)msg;
                if (omsg.type == MessageMessage.Type.SOLD_MARKET_SCROLLS)
                {
                    this.needSoldAucs = true;
                    App.Communicator.send(new MarketplaceSoldListViewMessage());
                }
            }

            if (msg is OkMessage)
            {
                OkMessage omsg = (OkMessage)msg;
                if (Helpfunktions.Instance.createAuctionMenu)
                {

                    if (omsg.op == "MarketplaceCreateOffer" && this.sellingCard != null)
                    {
                        Helpfunktions.Instance.cardIDToNumberOwned[this.sellingType]--;
                        Helpfunktions.Instance.cardIDToNumberOwnedTiered[this.sellingType] -= (int)Math.Pow(3, sellingTypeLevel);
                        PlayerStore.Instance.createCardsFilter.filtersChanged = true;
                        PlayerStore.Instance.sellOfferFilter.filtersChanged = true;

                        this.dataOffer = 0;
                        this.sellingCard = null;
                        App.Communicator.send(new MarketplaceOffersViewMessage());
                        //App.Communicator.send(new MarketplaceSoldListViewMessage());
                        App.Communicator.sendRequest(new LibraryViewMessage());
                    }
                    if (omsg.op == "MarketplaceCancelOffer")
                    {
                        Helpfunktions.Instance.cardIDToNumberOwned[this.cancelType]++;
                        Helpfunktions.Instance.cardIDToNumberOwnedTiered[this.cancelType] += (int)Math.Pow(3, cancelTypeLevel);
                        PlayerStore.Instance.createCardsFilter.filtersChanged = true;
                        PlayerStore.Instance.sellOfferFilter.filtersChanged = true;

                        this.dataOffer = 0;
                        App.Communicator.send(new MarketplaceOffersViewMessage());
                        //App.Communicator.send(new MarketplaceSoldListViewMessage());
                        App.Communicator.sendRequest(new LibraryViewMessage());
                    }

                    if (omsg.op == "MarketplaceClaim")
                    {
                        
                        if (transactionBeingClaimed == null) return;
                        if (this.workthreadclaimall)
                        {
                            this.claimeditemstaxes += this.transactionBeingClaimed.fee;
                            this.claimeditemsmoney += this.transactionBeingClaimed.sellPrice;
                            System.Threading.Thread.Sleep(150);
                            this.claimlast();
                            return;
                        }
                        App.AudioScript.PlaySFX("Sounds/hyperduck/UI/ui_coin_tally_end");
                        CardType cardType = CardTypeManager.getInstance().get(this.transactionBeingClaimed.cardType);
                        this.dataOffer = 0;
                        this.needSoldAucs = true;
                        App.Communicator.send(new MarketplaceOffersViewMessage());
                        App.Communicator.send(new MarketplaceSoldListViewMessage());
                        App.Communicator.sendRequest(new LibraryViewMessage());
                        App.Popups.ShowOk(this, "claimgold", "Gold added", string.Concat(new object[]
							{
								"<color=#bbaa88>Tier ",
								(int)(this.transactionBeingClaimed.level + 1),
								" ",
								cardType.name,
								" sold for ",
								this.transactionBeingClaimed.sellPrice,
								" gold!\nEarned <color=#ffd055>",
								this.transactionBeingClaimed.sellPrice - this.transactionBeingClaimed.fee,
								" gold</color> (the fence collects ",
								this.transactionBeingClaimed.fee,
								").</color>"
							}), "Ok");
                        this.transactionBeingClaimed = null;
                    }
                }

                if (Helpfunktions.Instance.playerStoreMenu)
                {
                    if (omsg.op == "MarketplaceMakeDeal")
                    {
                        App.Communicator.sendRequest(new GetStoreItemsMessage());
                        App.Communicator.sendRequest(new LibraryViewMessage());
                        App.Popups.ShowOk(this, "dealmade", "Purchase complete!", clickedItemName + " has been added to your collection.", "Ok");
                        Helpfunktions.Instance.cardIDToNumberOwned[this.clickedItemtypeid]++;
                        Helpfunktions.Instance.cardIDToNumberOwnedTiered[this.clickedItemtypeid]+=(int)Math.Pow(3, clickedItemLevel);
                        PlayerStore.Instance.createCardsFilter.filtersChanged = true;
                        PlayerStore.Instance.sellOfferFilter.filtersChanged = true;
                        clickedItemBuyID = -1;
                    }
                }

            }

            if (msg is FailMessage)
            {
                FailMessage failMessage = (FailMessage)msg;
                if (failMessage.isType(typeof(MarketplaceMakeDealMessage)))
                {
                    App.Popups.ShowOk(this, "dealNOTmade", "Purchase failed", failMessage.info, "Ok");
                    PlayerStore.Instance.createCardsFilter.filtersChanged = true;
                    PlayerStore.Instance.sellOfferFilter.filtersChanged = true;
                    clickedItemBuyID = -1;
                }

                if (failMessage.isType(typeof(MarketplaceCreateOfferMessage)) && this.sellingCard != null)
                {
                    App.Popups.ShowOk(this, "cantcreate", "Create failed", failMessage.info, "Ok");
                    this.sellingCard = null;
                }

                if (failMessage.isType(typeof(MarketplaceClaimMessage)))
                {
                    if (transactionBeingClaimed == null) return;
                    if (this.workthreadclaimall)
                    {
                        System.Threading.Thread.Sleep(150);
                        this.claimlast();
                        return;
                    }
                    this.dataOffer = 0;
                    this.needSoldAucs = true;
                    App.Communicator.send(new MarketplaceOffersViewMessage());
                    App.Communicator.send(new MarketplaceSoldListViewMessage());
                    App.Communicator.sendRequest(new LibraryViewMessage());
                    transactionBeingClaimed = null;
                }
            }

            if (msg is CheckCardDependenciesMessage && sellingCard !=null )
            {
                CheckCardDependenciesMessage checkCardDependenciesMessage = (CheckCardDependenciesMessage)msg;
                if (checkCardDependenciesMessage.dependencies == null || checkCardDependenciesMessage.dependencies.Length == 0)
                {
                    this.GetCreateOfferInfo();
                }
                else
                {
                    App.Popups.ShowOkCancel(this, "deckinvalidationwarning", "Notice", "Selling this scroll will make the following decks illegal:\n\n" + DeckUtil.GetFormattedDeckNames(checkCardDependenciesMessage.GetDeckNames()), "Ok", "Cancel");
                }
            }

            if (msg is MarketplaceCreateOfferInfoMessage && sellingCard != null)
            {
                MarketplaceCreateOfferInfoMessage marketplaceCreateOfferInfoMessage = (MarketplaceCreateOfferInfoMessage)msg;
                App.Popups.ShowSellCard(this, "sellcard", this.sellingCard, marketplaceCreateOfferInfoMessage.lowestPrice, marketplaceCreateOfferInfoMessage.suggestedPrice, marketplaceCreateOfferInfoMessage.copiesForSale, marketplaceCreateOfferInfoMessage.tax);
            }

            if (msg is MarketplaceOffersSearchViewMessage)
            {
                MarketplaceOffersSearchViewMessage marketplaceOffersViewMessage = (MarketplaceOffersSearchViewMessage)msg;
                clickedItemForSales = marketplaceOffersViewMessage.copiesForSale;
                clickedItemLevel = marketplaceOffersViewMessage.offer.card.level;
                clickedItemPrice = marketplaceOffersViewMessage.offer.price;
                clickedItemBuyID = marketplaceOffersViewMessage.offer.id;
                clickedItemName = marketplaceOffersViewMessage.offer.card.getName();
                clickedItemtypeid = marketplaceOffersViewMessage.offer.card.getType();

            }

            if (msg is MarketplaceOffersViewMessage)
            {
                //if (this.dataisreadyOwnOffers) return;

                MarketplaceOffersViewMessage marketplaceOffersViewMessage = (MarketplaceOffersViewMessage)msg;
                MarketplaceOffer[] offers = marketplaceOffersViewMessage.offers;
                this.pstoreOwnAucs.Clear();
                DateTime tme = DateTime.Now;
                tme = tme.AddMilliseconds(1000);
                for (int i = 0; i < offers.Length; i++)
                {
                    MarketplaceOffer marketplaceOffer = offers[i];
                    Auction a = new Auction(App.MyProfile.ProfileInfo.name, tme, Auction.OfferType.SELL, marketplaceOffer.card, "" + marketplaceOffer.id, marketplaceOffer.price);
                    tme = tme.AddMilliseconds(1);
                    //Console.WriteLine("add owm auction: " + a.card.getName() + " " + a.price);
                    this.pstoreOwnAucs.Add(a);
                }

                this.dataOffer++;
                
                if (this.dataOffer >= 2 || !this.needSoldAucs)
                {
                    this.dataisreadyOwnOffers = true;
                }
                if (this.dataOffer >= 2)
                {
                    this.needSoldAucs = false;
                }
            }

            if (msg is MarketplaceSoldListViewMessage)
            {
                //if (this.dataisreadyOwnOffers) return;

                MarketplaceSoldListViewMessage marketplaceOffersViewMessage = (MarketplaceSoldListViewMessage)msg;
                TransactionInfo[] offers = marketplaceOffersViewMessage.sold;
                this.pstoreSOLDAucs.Clear();
                this.soldScrollTransactions.Clear();
                DateTime tme = DateTime.Now;
                
                for (int i = 0; i < offers.Length; i++)
                {
                    TransactionInfo marketplaceOffer = offers[i];
                    if(!marketplaceOffer.claimed) this.soldScrollTransactions.Add(marketplaceOffer.cardId, marketplaceOffer);
                    CardType type = CardTypeManager.getInstance().get(marketplaceOffer.cardType);
                    Card c = new Card(marketplaceOffer.cardId, type, true);
                    string aucmessage="sold " + marketplaceOffer.fee;
                    if (marketplaceOffer.claimed)
                    {
                        aucmessage += " claimed";
                        continue;
                    }
                    Auction a = new Auction(App.MyProfile.ProfileInfo.name, tme, Auction.OfferType.SELL, c, aucmessage, marketplaceOffer.sellPrice, marketplaceOffer.cardId);
                    tme = tme.AddMilliseconds(1);
                    //Console.WriteLine("add owm auction: " + a.card.getName() + " " + a.price);
                    this.pstoreSOLDAucs.Add(a);
                }
                this.dataOffer++;
                if (this.dataOffer >= 2) this.dataisreadyOwnOffers = true;
                this.needSoldAucs = false;
            }

            if (msg is MarketplaceAvailableOffersListViewMessage)
            {
                Prices.Instance.getBlackmarketPrices(msg as MarketplaceAvailableOffersListViewMessage);
                if (this.dataisready) return;

                MarketplaceAvailableOffersListViewMessage marketplaceAvailableOffersListViewMessage = (MarketplaceAvailableOffersListViewMessage)msg;

                MarketplaceTypeAvailability[] available = marketplaceAvailableOffersListViewMessage.available;
                this.pstoreAucs.Clear();
                DateTime tme = DateTime.Now;
                for (int i = 0; i < available.Length; i++)
                {
                    MarketplaceTypeAvailability mta = available[i];
                    CardType type = CardTypeManager.getInstance().get(mta.type);
                    Card card = new Card(1, type, true);
                    card.level = mta.level;
                    Auction a = new Auction("BlackMarket", tme, Auction.OfferType.SELL, card, "", mta.price);
                    tme = tme.AddMilliseconds(-1);
                    //Console.WriteLine("add auction: " + a.card.getName() + " " + a.price);
                    this.pstoreAucs.Add(a);
                }

                this.dataisready = true;
            }
            return;
        }
示例#38
0
        public override TransactionInfo PreAuthorize(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, decimal amount, bool testTransaction)
        {
            ANetRequest request = null;
            ANetResponse response = null;
            TransactionInfo transactionInfo = new TransactionInfo();

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;

            request = new ANetRequest(requestUrl, loginId, transactionKey, customer, card, amount, testTransaction);
            response = request.ProcessAuthOnly();

            transactionInfo.Id = Guid.NewGuid();
            //transactionInfo.CustomerName = System.Web.Security.Membership.GetUser(customer.ID).UserName;
            transactionInfo.SubscriptionId = Guid.Empty;
            transactionInfo.GatewayId = gateway.Id;
            transactionInfo.CreateDate = DateTime.Now;
            //transactionInfo.IsTrial = ??;
            transactionInfo.Type = TransactionType.Standard;
            transactionInfo.Amount = amount;
            transactionInfo.GatewayAmount = gateway.TransactionFee;
            transactionInfo.OrderId = orderId;
            if (response == null)
            {
                transactionInfo.ResponseText = "";
                transactionInfo.Status = TransactionStatus.Error;
            }
            else if (response.Code == ANetResponseCode.Approved)
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Approved;
            }
            else
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Error;
            }
            return transactionInfo;
        }
 /// <summary>
 /// Binds this
 /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>
 /// instance to the thread local storage variable for the current thread and
 /// backs up the existing
 /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>
 /// object for the current thread.
 /// </summary>
 public void BindToThread()
 {
     // Expose current TransactionStatus, preserving any existing TransactionStatus
     // for restoration after this transaction is complete.
     TransactionInfo currentTransactionInfo = LogicalThreadContext.GetData(CURRENT_TRANSACTIONINFO_SLOTNAME) as TransactionInfo;
     _oldTransactionInfo = currentTransactionInfo;
     LogicalThreadContext.SetData(CURRENT_TRANSACTIONINFO_SLOTNAME, this);
 }
        /// <summary>
        /// Handle a exception, closing out the transaction.
        /// </summary>
        /// <remarks>
        /// <p>
        /// We may commit or roll back, depending on our configuration.
        /// </p>
        /// </remarks>
        /// <param name="transactionInfo">
        /// The
        /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>
        /// about the current transaction.
        /// </param>
        /// <param name="exception">The <see cref="System.Exception"/> encountered.</param>
        protected void CompleteTransactionAfterThrowing(
			TransactionInfo transactionInfo, Exception exception )
        {
            if ( transactionInfo != null &&  transactionInfo.HasTransaction )
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Completing transaction for [" + transactionInfo.JoinpointIdentification + "] after exception: " + exception);
                }

                if ( transactionInfo.TransactionAttribute.RollbackOn( exception ))
                {
                    try
                    {
                        _transactionManager.Rollback( transactionInfo.TransactionStatus );
                    }
                    catch (Exception e)
                    {
                        log.Error("Application exception overridden by rollback exception", e);
                        throw;
                    }
                }
                else
                {
                    // We don't roll back on this exception.
                    // Will still roll back if TransactionStatus.RollbackOnly is true.
                    try
                    {
                        _transactionManager.Commit(transactionInfo.TransactionStatus);
                    } catch (Exception e)
                    {
                        log.Error("Application exception overriden by commit exception", e);
                        throw;
                    }

                }
            }
        }
示例#41
0
		internal async Task FinalizeBatchExecution(StatementExecutionBatchResult batchResult, CancellationToken cancellationToken)
		{
			_userTransactionInfo = null;

			var exception = await ResolveExecutionPlanIdentifiersAndTransactionStatus(cancellationToken);
			if (exception != null)
			{
				await SafeResolveTransactionStatus(cancellationToken);
			}

			batchResult.DatabaseOutput = await RetrieveDatabaseOutput(cancellationToken);
		}
示例#42
0
 public override void Refund(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, string refID, TransactionInfo transaction, bool testTransaction)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Creates a new instance of the transaction class and populates it with data from the specified SqlDataReader.
        /// </summary>
        protected virtual TransactionInfo MakeTransactionInfo(SqlDataReader dataReader)
        {
            TransactionInfo transactionInfo = new TransactionInfo();
            transactionInfo.Transactionid = SqlClientUtility.GetInt32(dataReader,DbConstants.TRANSACTION.TRANSACTIONID, 0);
            transactionInfo.Station = SqlClientUtility.GetInt32(dataReader,DbConstants.TRANSACTION.STATION, 0);
            transactionInfo.Time = SqlClientUtility.GetInt32(dataReader,DbConstants.TRANSACTION.TIME, 0);
            transactionInfo.Userid = SqlClientUtility.GetInt32(dataReader,DbConstants.TRANSACTION.USERID, 0);
            transactionInfo.Price = SqlClientUtility.GetString(dataReader,DbConstants.TRANSACTION.PRICE, String.Empty);
            transactionInfo.Number_plate = SqlClientUtility.GetString(dataReader,DbConstants.TRANSACTION.NUMBER_PLATE, String.Empty);
            transactionInfo.Evidence = SqlClientUtility.GetInt32(dataReader,DbConstants.TRANSACTION.EVIDENCE, 0);

            return transactionInfo;
        }
示例#44
0
        public override TransactionInfo ProcessPayment(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, decimal amount, bool testTransaction)
        {
            ProPayRequest request = null;
            ProPayResponse response = null;
            TransactionInfo transactionInfo = new TransactionInfo();

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;

            request = new ProPayRequest(requestUrl, loginId, transactionKey, customer, card, amount, testTransaction);
            response = request.Process();



            transactionInfo.Id = Guid.NewGuid();
            transactionInfo.SubscriptionId = Guid.Empty;
            transactionInfo.GatewayId = gateway.Id;
            transactionInfo.CreateDate = DateTime.Now;
            //transactionInfo.IsTrial = ??;
            transactionInfo.Type = TransactionType.Standard;
            transactionInfo.Amount = amount;
            transactionInfo.GatewayAmount = gateway.TransactionFee;
            transactionInfo.OrderId = orderId;
            if (response == null)
            {
                transactionInfo.ResponseText = "";
                transactionInfo.Status = TransactionStatus.Error;
            }
            else if (response.Code == ProPayResponseCode.Success)
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Approved;
            }
            else
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Error;
            }
            return transactionInfo;
        }
示例#45
0
        private XATransactionId[] TryRecoverBrokerTXIds()
        {
            Tracer.Debug("Checking for Recoverable Transactions on Broker.");

            TransactionInfo info = new TransactionInfo();
            info.ConnectionId = this.session.Connection.ConnectionId;
            info.Type = (int)TransactionType.Recover;

            this.connection.CheckConnected();
            DataArrayResponse response = this.connection.SyncRequest(info) as DataArrayResponse;

            if (response != null && response.Data.Length > 0)
            {
                Tracer.DebugFormat("Broker reports there are {0} recoverable XA Transactions", response.Data.Length);

                List<XATransactionId> recovered = new List<XATransactionId>();

                foreach (DataStructure ds in response.Data)
                {
                    XATransactionId xid = ds as XATransactionId;
                    if (xid != null)
                    {
                        recovered.Add(xid);
                    }
                }

                return recovered.ToArray();
            }

            return new XATransactionId[0];
        }
示例#46
0
        public void ClaimSalesMoney(int cardid)
        {
            if (this.workthreadclaimall == true) return;

            if (this.soldScrollTransactions.ContainsKey(cardid))
            {
                TransactionInfo transactionInfo = this.soldScrollTransactions[cardid];
                this.transactionBeingClaimed = transactionInfo;
                App.Communicator.send(new MarketplaceClaimMessage(transactionInfo.transactionId));
                this.soldScrollTransactions.Remove(cardid);
            }
        }
 /// <summary>
 /// Resets the 
 /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>
 /// for this thread.
 /// </summary>
 /// <remarks>
 /// <note>
 /// Call this in all cases: exceptions or normal return.
 /// </note>
 /// </remarks>
 /// <param name="transactionInfo">
 /// The 
 /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>
 /// about the current transaction. May be null.
 /// </param>
 protected void CleanupTransactionInfo( TransactionInfo transactionInfo )
 {
     if ( transactionInfo != null )
     {
         transactionInfo.RestoreThreadLocalStatus( );
     }
 }
示例#48
0
		private void DisposeUserTransaction()
		{
			_userTransactionInfo = null;

			if (_userTransaction == null)
			{
				return;
			}

			_userTransaction.Dispose();
			_userTransaction = null;
		}
        /// <summary>
        /// Execute after the successful completion of call, but not after an exception was handled.
        /// </summary>
        /// <remarks>
        /// <p>
        /// Do nothing if we didn't create a transaction.
        /// </p>
        /// </remarks>
        /// <param name="transactionInfo">
        /// The
        /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>
        /// about the current transaction.
        /// </param>
        protected void CommitTransactionAfterReturning( TransactionInfo transactionInfo )
        {
            if ( transactionInfo != null && transactionInfo.HasTransaction )
            {
                #region Instrumentation

                if (log.IsDebugEnabled)
                {
                    log.Debug("Completing transaction for [" + transactionInfo.JoinpointIdentification + "]");
                }

                #endregion

                _transactionManager.Commit( transactionInfo.TransactionStatus );
            }
        }
示例#50
0
		private async Task SafeResolveTransactionStatus(CancellationToken cancellationToken)
		{
			if (cancellationToken.IsCancellationRequested)
			{
				return;
			}

			using (var command = _userConnection.CreateCommand())
			{
				command.CommandText = OracleDatabaseCommands.SelectLocalTransactionIdCommandText;

				using (var reader = await command.ExecuteReaderAsynchronous(CommandBehavior.Default, cancellationToken))
				{
					if (!await reader.ReadAsynchronous(cancellationToken))
					{
						return;
					}

					var transactionId = OracleReaderValueConvert.ToString(reader["TRANSACTION_ID"]);

					if (!String.IsNullOrEmpty(transactionId))
					{
						var transactionElements = transactionId.Split('.');
						_userTransactionInfo =
							new TransactionInfo
							{
								UndoSegmentNumber = Convert.ToInt32(transactionElements[0]),
								SlotNumber = Convert.ToInt32(transactionElements[1]),
								SequnceNumber = Convert.ToInt32(transactionElements[2]),
								IsolationLevel = IsolationLevel.Unspecified
							};
					}

					var currentSchema = Convert.ToString(reader["SCHEMANAME"]);
					_databaseModel.SetCurrentSchema(currentSchema);
				}
			}
		}
        /// <summary>
        /// Creates the transaction if necessary.
        /// </summary>
        /// <param name="sourceAttr">The source transaction attribute.</param>
        /// <param name="joinpointIdentification">The joinpoint identification.</param>
        /// <returns>Transaction Info for declarative transaction management.</returns>
        protected TransactionInfo CreateTransactionIfNecessary(ITransactionAttribute sourceAttr, string joinpointIdentification)
        {
            ITransactionAttribute txAttr = sourceAttr;

            // If no name specified, apply method identification as transaction name.
            if (txAttr != null && txAttr.Name == null)
            {
                txAttr = new DelegatingTransactionAttributeWithName(txAttr, joinpointIdentification);
            }

            TransactionInfo transactionInfo = new TransactionInfo(txAttr, joinpointIdentification);
            if ( txAttr != null )
            {
                // We need a transaction for this method
                #region Instrumentation

                if (log.IsDebugEnabled)
                {
                    log.Debug("Getting transaction for " + transactionInfo.JoinpointIdentification);
                }

                #endregion
                // The transaction manager will flag an error if an incompatible tx already exists
                transactionInfo.TransactionStatus = _transactionManager.GetTransaction(txAttr);
            }
            else
            {
                // The TransactionInfo.HasTransaction property will return
                // false. We created it only to preserve the integrity of
                // the ThreadLocal stack maintained in this class.
                if (log.IsDebugEnabled)
                {
                    log.Debug("Skipping transactional joinpoint [" + joinpointIdentification +
                              "] because no transaction manager has been configured");
                }
            }

            // We always bind the TransactionInfo to the thread, even if we didn't create
            // a new transaction here. This guarantees that the TransactionInfo stack
            // will be managed correctly even if no transaction was created by this aspect.
            transactionInfo.BindToThread( );
            return transactionInfo;
        }
示例#52
0
		private async Task<Exception> ResolveExecutionPlanIdentifiersAndTransactionStatus(CancellationToken cancellationToken)
		{
			using (var connection = new OracleConnection(_databaseModel.BackgroundConnectionString))
			{
				using (var command = connection.CreateCommand())
				{
					command.BindByName = true;
					command.CommandText = OracleDatabaseCommands.SelectExecutionPlanIdentifiersCommandText;
					command.AddSimpleParameter("SID", _userSessionIdentifier.Value.SessionId);

					try
					{
						await connection.OpenAsynchronous(cancellationToken);
						connection.ModuleName = $"{_moduleName}/BackgroundConnection".EnsureMaximumLength(64);
						connection.ActionName = "Fetch execution info";

						_userCommandSqlId = null;

						using (var reader = await command.ExecuteReaderAsynchronous(CommandBehavior.Default, cancellationToken))
						{
							if (!await reader.ReadAsynchronous(cancellationToken))
							{
								return null;
							}

							_userCommandSqlId = OracleReaderValueConvert.ToString(reader["SQL_ID"]);
							_userCommandChildNumber = OracleReaderValueConvert.ToInt32(reader["SQL_CHILD_NUMBER"]) ?? 0;

							var undoSegmentNumber = OracleReaderValueConvert.ToInt32(reader["XIDUSN"]);
							if (undoSegmentNumber.HasValue)
							{
								_userTransactionInfo =
									new TransactionInfo
									{
										UndoSegmentNumber = undoSegmentNumber.Value,
										SlotNumber = Convert.ToInt32(reader["XIDSLOT"]),
										SequnceNumber = Convert.ToInt32(reader["XIDSQN"]),
										IsolationLevel = (IsolationLevel)Convert.ToInt32(reader["TRANSACTION_ISOLATION_LEVEL"])
									};
							}

							var currentSchema = Convert.ToString(reader["SCHEMANAME"]);
							_databaseModel.SetCurrentSchema(currentSchema);
						}

						return null;
					}
					catch (OracleException e)
					{
						Trace.WriteLine($"Execution plan identifers and transaction status could not been fetched: {e}");
						return e;
					}
					finally
					{
						await connection.CloseAsynchronous(cancellationToken);
					}
				}
			}
		}
示例#53
0
        public override void Refund(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, string refID, TransactionInfo transaction,
            bool testTransaction)
        {
            ANetRequest request = null;
            ANetResponse response = null;

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;

            request = new ANetRequest(requestUrl, loginId, transactionKey, customer, card, refID, transaction, testTransaction, transaction.Amount);
           
            response = request.ProcessRefund();

            if (response.Code == ANetResponseCode.Approved)
            {
                transaction.Status = TransactionStatus.Refunded;
            }
        }
 /// <summary>
 /// Saves a record to the transaction table.
 /// </summary>
 public virtual void Insert(TransactionInfo transactionInfo)
 {
     try
     {
         new TransactionTFM().Insert(transactionInfo);
     }
     catch (Exception ex)
     {
         //Provider.Log.Error(ex, "TFM.Biz.Implements.Transaction - Insert" + ex.Message);
         throw;
     }
 }
 public TransactionInfoWrapper(TransactionInfo transactionInfo)
 {
     _transactionInfo = transactionInfo;
 }
        public void UpdateTransaction(TransactionInfo transaction)
        {
            try
            {
                CashFlowManagerEntities db = new CashFlowManagerEntities();

                var tran = (from t in db.Transactions where t.Id == transaction.Id select t).SingleOrDefault();

                if (tran != null)
                {
                    tran.Narration = transaction.Narration;
                    tran.ScheduleId = transaction.ScheduleId;
                    tran.Amount = transaction.Amount;
                    tran.StartDate = transaction.StartDate;
                    tran.TransactionTypeId = transaction.TransactionTypeId;

                    db.Entry(tran).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
        public DbResult CreateDb()
        {
            var records = new LogRecord[_chunkRecs.Count][];
            for (int i = 0; i < records.Length; ++i)
            {
                records[i] = new LogRecord[_chunkRecs[i].Length];
            }

            var transactions = new Dictionary<int, TransactionInfo>();
            var streams = new Dictionary<string, StreamInfo>();
            var streamUncommitedVersion = new Dictionary<string, int>();

            for (int i = 0; i < _chunkRecs.Count; ++i)
            {
                for (int j = 0; j < _chunkRecs[i].Length; ++j)
                {
                    var rec = _chunkRecs[i][j];

                    TransactionInfo transInfo;
                    bool transCreate = transactions.TryGetValue(rec.Transaction, out transInfo);
                    if (!transCreate)
                    {
                        if (rec.Type == Rec.RecType.Commit)
                            throw new Exception("Commit for non-existing transaction.");

                        transactions[rec.Transaction] = transInfo = new TransactionInfo(rec.StreamId, rec.Id, rec.Id);

                        streams[rec.StreamId] = new StreamInfo(-1);
                        streamUncommitedVersion[rec.StreamId] = -1;
                    }
                    else
                    {
                        if (rec.Type == Rec.RecType.TransStart)
                            throw new Exception(string.Format("Not expected record type: {0}.", rec.Type));
                    }

                    if (transInfo.StreamId != rec.StreamId)
                    {
                        throw new Exception(string.Format("Wrong stream id for transaction. Transaction StreamId: {0}, record StreamId: {1}.",
                                                          transInfo.StreamId,
                                                          rec.StreamId));
                    }

                    if (rec.Type != Rec.RecType.Commit && transInfo.IsDelete)
                        throw new Exception("Transaction with records after delete record.");

                    if (rec.Type == Rec.RecType.Delete)
                        transInfo.IsDelete = true;
                    
                    transInfo.LastPrepareId = rec.Id;
                }
            }

            for (int i = 0; i < _chunkRecs.Count; ++i)
            {
                var chunk = i == 0 ? _db.Manager.GetChunk(0) : _db.Manager.AddNewChunk();
                _db.Config.WriterCheckpoint.Write(i * (long)_db.Config.ChunkSize);

                for (int j = 0; j < _chunkRecs[i].Length; ++j)
                {
                    var rec = _chunkRecs[i][j];
                    var transInfo = transactions[rec.Transaction];
                    var logPos = _db.Config.WriterCheckpoint.ReadNonFlushed();

                    int streamVersion = streamUncommitedVersion[rec.StreamId];
                    if (streamVersion == -1 && rec.Type != Rec.RecType.TransStart && rec.Type != Rec.RecType.Create)
                        throw new Exception(string.Format("Stream {0} is empty and we are not creating it with stream created.", rec.StreamId));
                    if (streamVersion == EventNumber.DeletedStream && rec.Type != Rec.RecType.Commit)
                        throw new Exception(string.Format("Stream {0} was deleted, but we need to write some more prepares.", rec.StreamId));

                    if (transInfo.FirstPrepareId == rec.Id)
                    {
                        transInfo.TransactionPosition = logPos;
                        transInfo.TransactionEventNumber = streamVersion + 1;
                        transInfo.TransactionOffset = 0;
                    }

                    LogRecord record;

                    var expectedVersion = transInfo.FirstPrepareId == rec.Id ? streamVersion : ExpectedVersion.Any;
                    switch (rec.Type)
                    {
                        case Rec.RecType.Prepare:
                        case Rec.RecType.Create:
                        {
                            int transOffset = transInfo.TransactionOffset;
                            transInfo.TransactionOffset += 1;

                            record = LogRecord.Prepare(logPos, 
                                                       Guid.NewGuid(), 
                                                       rec.Id, 
                                                       transInfo.TransactionPosition,
                                                       transOffset,
                                                       rec.StreamId,
                                                       expectedVersion,
                                                       PrepareFlags.Data
                                                       | (transInfo.FirstPrepareId == rec.Id ? PrepareFlags.TransactionBegin : PrepareFlags.None)
                                                       | (transInfo.LastPrepareId == rec.Id ? PrepareFlags.TransactionEnd : PrepareFlags.None), 
                                                       rec.EventType,
                                                       rec.Id.ToByteArray(),
                                                       null,
                                                       rec.TimeStamp);
                            if (rec.Type == Rec.RecType.Create)
                                transInfo.StreamMetadata = rec.Metadata;

                            streamUncommitedVersion[rec.StreamId] += 1;
                            break;
                        }

                        case Rec.RecType.Delete:
                        {
                            int transOffset = transInfo.TransactionOffset;
                            transInfo.TransactionOffset += 1;

                            record = LogRecord.Prepare(logPos, 
                                                       Guid.NewGuid(), 
                                                       rec.Id, 
                                                       transInfo.TransactionPosition,
                                                       transOffset,
                                                       rec.StreamId,
                                                       expectedVersion,
                                                       PrepareFlags.StreamDelete
                                                       | (transInfo.FirstPrepareId == rec.Id ? PrepareFlags.TransactionBegin : PrepareFlags.None)
                                                       | (transInfo.LastPrepareId == rec.Id ? PrepareFlags.TransactionEnd : PrepareFlags.None), 
                                                       rec.EventType,
                                                       LogRecord.NoData,
                                                       null,
                                                       rec.TimeStamp);
                            streamUncommitedVersion[rec.StreamId] = EventNumber.DeletedStream;
                            break;
                        }

                        case Rec.RecType.TransStart:
                        case Rec.RecType.TransEnd:
                        {
                            record = LogRecord.Prepare(logPos,
                                                       Guid.NewGuid(),
                                                       rec.Id,
                                                       transInfo.TransactionPosition,
                                                       -1,
                                                       rec.StreamId,
                                                       expectedVersion,
                                                       (transInfo.FirstPrepareId == rec.Id ? PrepareFlags.TransactionBegin : PrepareFlags.None)
                                                       | (transInfo.LastPrepareId == rec.Id ? PrepareFlags.TransactionEnd : PrepareFlags.None),
                                                       rec.EventType,
                                                       LogRecord.NoData,
                                                       null,
                                                       rec.TimeStamp);
                            break;
                        }
                        case Rec.RecType.Commit:
                        {
                            record = LogRecord.Commit(logPos, Guid.NewGuid(), transInfo.TransactionPosition, transInfo.TransactionEventNumber);

                            if (transInfo.StreamMetadata.HasValue)
                                streams[rec.StreamId].StreamMetadata = transInfo.StreamMetadata.Value;

                            if (transInfo.IsDelete)
                                streams[rec.StreamId].StreamVersion = EventNumber.DeletedStream;
                            else
                                streams[rec.StreamId].StreamVersion = transInfo.TransactionEventNumber + transInfo.TransactionOffset - 1;
                            break;
                        }
                        default:
                            throw new ArgumentOutOfRangeException();
                    }

                    var writerRes = chunk.TryAppend(record);
                    if (!writerRes.Success)
                        throw new Exception(string.Format("Couldn't write log record: {0}", record));
                    _db.Config.WriterCheckpoint.Write(i * (long)_db.Config.ChunkSize + writerRes.NewPosition);

                    records[i][j] = record;
                }

                if (i < _chunkRecs.Count-1 || (_completeLast && i == _chunkRecs.Count - 1))
                    chunk.Complete();
            }

            return new DbResult(_db, records, streams);
        }
示例#58
0
        private void claimlast()
        {
            int cardid = -1;
            TransactionInfo transactionInfo = null;
            foreach (KeyValuePair<int, TransactionInfo> kvp in this.soldScrollTransactions)
            {
                cardid = kvp.Key;
                transactionInfo = kvp.Value;
            }
            if (cardid != -1)
            {
                this.claimeditems++;
                this.soldScrollTransactions.Remove(cardid);
                this.transactionBeingClaimed = transactionInfo;
                App.Communicator.send(new MarketplaceClaimMessage(transactionInfo.transactionId));
            }
            else
            {
                //finished claiming
                if (this.claimeditems >= 1)
                {
                    this.dataOffer = 0;
                    this.needSoldAucs = true;
                    App.Communicator.send(new MarketplaceOffersViewMessage());
                    App.Communicator.send(new MarketplaceSoldListViewMessage());
                    App.Communicator.sendRequest(new LibraryViewMessage());
                    App.Popups.ShowOk(this, "claimgold", "Gold added", string.Concat(new object[]
							{   
                                "<color=#bbaa88>",
								"Your Scrolls where sold for ",
								this.claimeditemsmoney,
								" gold!\nEarned <color=#ffd055>",
								this.claimeditemsmoney-this.claimeditemstaxes,
								" gold</color> (the fence collects ",
								this.claimeditemstaxes,
								").</color>"
							}), "Ok");
                }

                this.claimeditems = 0;
                this.claimeditemstaxes = 0;
                this.claimeditemsmoney = 0;
                this.transactionBeingClaimed = null;
                this.workthreadclaimall = false;
            }

        }
        /// <summary>
        /// Saves a record to the transaction table.
        /// </summary>
        public virtual void Insert(TransactionInfo transactionInfo)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@transactionid", transactionInfo.Transactionid),
                new SqlParameter("@station", transactionInfo.Station),
                new SqlParameter("@time", transactionInfo.Time),
                new SqlParameter("@userid", transactionInfo.Userid),
                new SqlParameter("@price", transactionInfo.Price),
                new SqlParameter("@number_plate", transactionInfo.Number_plate),
                new SqlParameter("@evidence", transactionInfo.Evidence)
            };

            SqlClientUtility.ExecuteNonQuery(connectionStringName, CommandType.StoredProcedure, "transaction_Insert", parameters);
        }
示例#60
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();
            }
        }