コード例 #1
0
        private static bool CancelDeliveryWithShortSellOrders(DeliveryRequest deliveryRequest)
        {
            List <Transaction> executedTransactions = new List <Transaction>();
            List <Transaction> transactions         = new List <Transaction>();

            Account          account           = TradingSetting.Default.GetAccount(deliveryRequest.AccountId);
            var              instrument        = Settings.Setting.Default.GetInstrument(deliveryRequest.InstrumentId);
            var              tradePolicyDetail = Settings.Setting.Default.GetTradePolicy(account.Setting().TradePolicyId)[instrument.Id, null];
            TransactionError error             = TransactionError.OK;

            foreach (DeliveryRequestOrderRelation relation in deliveryRequest.DeliveryRequestOrderRelations)
            {
                Order openOrder = account.GetOrder(relation.OpenOrderId);
                transactions.Add(account.CreateCloseTranAndOrder(openOrder, relation, deliveryRequest));

                transactions.Add(account.CreateOpenTranAndOrder(openOrder, relation, deliveryRequest));
            }

            foreach (var eachTran in transactions)
            {
                eachTran.ExecuteDirectly(new Engine.ExecuteContext(account.Id, eachTran.Id, Engine.ExecuteStatus.Filled, eachTran.CreateOrderPriceInfo())
                {
                    IsFreeFee = true, IsFreeValidation = true
                });
            }

            return(error == TransactionError.OK);
        }
コード例 #2
0
 public ActionResult RedirectVPOS(string refId)
 {
     try
     {
         if (refId == null)
         {
             TransactionError _tErr = new TransactionError {
                 ErrorMessage = "هیچ شماره پیگیری برای پرداخت از سمت بانک ارسال نشده است!"
             };
             TempData["tErr"] = _tErr;
             return(RedirectToAction("ShowError", "PaymentMellatBank"));
         }
         else
         {
             return(View("~/Plugins/Payments.MellatBank/Views/RedirectVPOS.cshtml", null, refId));
         }
     }
     catch (Exception error)
     {
         TransactionError _tErr = new TransactionError {
             ErrorMessage = error + "متاسفانه خطایی رخ داده است، لطفا مجددا عملیات خود را انجام دهید در صورت تکرار این مشکل را به بخش پشتیبانی اطلاع دهید"
         };
         TempData["tErr"] = _tErr;
         return(RedirectToAction("ShowError", "PaymentMellatBank"));
     }
 }
コード例 #3
0
        private void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                // Signal the main thread to continue.
                connectDone.Set();

                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;

                Socket handler = listener.EndAccept(ar);

                // 加入 Client 清單
                Socket socket = null;
                _clients.TryRemove(handler.LocalEndPoint.ToString(), out socket);
                _clients.TryAdd(handler.LocalEndPoint.ToString(), handler);

                // Create the state object.
                //StateObject state = new StateObject();
                //state.workSocket = handler;
                //handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                //    new AsyncCallback(ReadCallback), state);
                StartReceiving(handler);
            }
            catch (ObjectDisposedException)
            {
                // 順利關閉
            }
            catch (Exception ex)
            {
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #4
0
 public ActionResult Withdrawl(Transaction transaction)
 {
     try
     {
         var balance = _repo.GetBalace(transaction.CheckingAccountId);
         if (balance < transaction.Amount)
         {
             ModelState.AddModelError("Amount", "You have insuficient funds");
         }
         if (ModelState.IsValid)
         {
             if (_repo.AddTransaction(transaction.CheckingAccountId, -transaction.Amount, "Withdrawal"))
             {
                 return(RedirectToAction("Statement", "CheckingAccount", new { checkingAccountId = transaction.CheckingAccountId }));
             }
             var error = new TransactionError
             {
                 Title   = "Transaction Denied",
                 Message = "Could not withdraw"
             };
             return(View("TransactionError", error));
         }
         ModelState.AddModelError("InvalidAccount", "Invalid account.");
         return(View());
     }
     catch (Exception e)
     {
         var error2 = new TransactionError
         {
             Title   = "Transaction Denied",
             Message = e.Message
         };
         return(View("TransactionError", error2));
     }
 }
コード例 #5
0
        internal TransactionError Execute(ExecuteContext context)
        {
            TransactionError error = TransactionError.OK;
            var account            = TradingSetting.Default.GetAccount(context.AccountId);
            var tran = account.GetTran(context.TranId);

            try
            {
                DataSet historyData = this.LoadHistorySettings(tran);
                this.ReplaceOrder(historyData, false, account);
                //account.Execute(e);
                this.ReplaceOrder(historyData, true, account);
                //SettingFacade.Default.SettingManager.RemoveHistorySettings(e.Account.Id);
            }
            catch (TransactionServerException tranException)
            {
                Logger.Error(tranException.ToString());
                error = tranException.ErrorCode;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                error = TransactionError.RuntimeError;
            }
            if (error != TransactionError.OK)
            {
                account.CancelExecute(context, error);
            }
            return(error);
        }
コード例 #6
0
        private void StartReceiving(Socket handler)
        {
            while (IsListening)
            {
                // Set the event to nonsignaled state.
                receiveDone.Reset();

                // Receive the response from the remote device.
                try
                {
                    // Create the state object.
                    StateObject state = new StateObject();
                    state.workSocket = handler;

                    // Begin receiving the data from the remote device.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                         new AsyncCallback(ReceiveCallback), state);
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex.ToString());
                    TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
                }

                receiveDone.WaitOne();
            }
        }
コード例 #7
0
        private bool Book(MappedTran tran)
        {
            TransactionError error = this.booker.Invoke(tran);

            if (error == TransactionError.OK || error == TransactionError.TransactionAlreadyExists ||
                error == TransactionError.OpenOrderNotExists || error == TransactionError.InvalidOrderRelation ||
                error == TransactionError.ExceedOpenLotBalance)
            {
                if (error != TransactionError.OK)
                {
                    AppDebug.LogEvent("StateServer", string.Format("Book failed, error = {0} \n {1}", error, tran.ToXmlString()), System.Diagnostics.EventLogEntryType.Warning);
                }

                try
                {
                    string fileName = Path.Combine(this.cachePath, string.Format("{0}.tan", tran.Sequence));
                    File.Delete(fileName);
                }
                catch (Exception ex)
                {
                    AppDebug.LogEvent("StateServer", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
                }

                return(true);
            }
            else
            {
                AppDebug.LogEvent("StateServer", string.Format("Book failed, error = {0} \n {1}", error, tran.ToXmlString()), System.Diagnostics.EventLogEntryType.Warning);
                return(false);
            }
        }
コード例 #8
0
        private void ExecuteOrder(Order marketOrder)
        {
            Guid   tranId = marketOrder.Owner.Id;
            string buyPrice = null, sellPrice = null;

            if (marketOrder.IsBuy)
            {
                buyPrice = (string)marketOrder.BestPrice;
            }
            else
            {
                sellPrice = (string)marketOrder.BestPrice;
            }

            if (marketOrder.Owner.Type == TransactionType.Pair)
            {
                Order otherMarketOrder = marketOrder.Owner.FirstOrder == marketOrder ? marketOrder.Owner.SecondOrder : marketOrder.Owner.FirstOrder;
                if (otherMarketOrder.IsBuy)
                {
                    buyPrice = (string)otherMarketOrder.BestPrice;
                }
                else
                {
                    sellPrice = (string)otherMarketOrder.BestPrice;
                }
            }
            TransactionError error = marketOrder.Account.Execute(tranId, buyPrice, sellPrice, null, marketOrder.Id);

            Logger.InfoFormat("ExecuteMarketOrder tran id = {0}; result = {1}", tranId, error);
        }
コード例 #9
0
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                // Signal that the connection has been made.
                connectDone.Set();

                //Console.WriteLine("Socket connected to {0}",
                //    client.RemoteEndPoint.ToString());
                TriggerConnectionStatus(true);
            }
            catch (Exception ex)
            {
                // Signal that the connection has been made.
                connectDone.Set();

                //Console.WriteLine(ex.ToString());
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #10
0
        public static ICollection <XElement> GetPlaceResultForMobile(Mobile.Server.Transaction transaction, Token token)
        {
            ICollection <XElement> elements = new List <XElement>();

            if (token != null && token.AppType == AppType.Mobile)
            {
                Token            placeToken = new Token(token.UserID, token.UserType, AppType.TradingConsole);
                string           tranCode;
                TransactionError error = Application.Default.TradingConsoleServer.Place(placeToken, Application.Default.StateServer, transaction.ToXmlNode(), out tranCode);
                if (error == TransactionError.Action_ShouldAutoFill)
                {
                    error = TransactionError.OK;
                }

                foreach (Mobile.Server.Order order in transaction.Orders)
                {
                    XElement orderErrorElement = new XElement("Order");
                    orderErrorElement.SetAttributeValue("Id", order.Id);
                    orderErrorElement.SetAttributeValue("ErrorCode", error.ToString());
                    elements.Add(orderErrorElement);
                }

                Mobile.Manager.UpdateWorkingOrder(token, transaction.Id, error);
                return(elements);
            }
            return(null);
        }
コード例 #11
0
 public PlaceEventArgs(Guid accountId, Guid tranId, PlaceStatus status, TransactionError error, string errorDetail)
 {
     this.AccountId     = accountId;
     this.TransactionId = tranId;
     this.Status        = status;
     this.Error         = error;
     this.ErrorDetail   = string.Format("ErrorCode = {0}, detail = {1}", error, errorDetail);
 }
コード例 #12
0
        public RedirectResult CreatePurchase([FromForm(Name = "recurly-token")] string tokenId, [FromForm(Name = "account-code")] string accountCode, [FromForm(Name = "first-name")] string firstName, [FromForm(Name = "last-name")] string lastName)
        {
            // If our form specifies an account code, we can use that; otherwise,
            // create an account code with a uniq id
            accountCode = accountCode ?? Guid.NewGuid().ToString();

            var purchaseReq = new PurchaseCreate()
            {
                Currency = "USD",
                Account  = new AccountPurchase()
                {
                    Code        = accountCode,
                    FirstName   = firstName,
                    LastName    = lastName,
                    BillingInfo = new BillingInfoCreate()
                    {
                        TokenId = tokenId
                    }
                },
                Subscriptions = new List <SubscriptionPurchase>()
                {
                    new SubscriptionPurchase()
                    {
                        PlanCode = "basic"
                    }
                }
            };

            try
            {
                InvoiceCollection collection = _client.CreatePurchase(purchaseReq);
                _logger.LogInformation($"Created ChargeInvoice with Number: {collection.ChargeInvoice.Number}");
            }
            catch (Recurly.Errors.Transaction e)
            {
                /**
                 * Note: This is not an example of extensive error handling,
                 * it is scoped to handling the 3DSecure error for simplicity.
                 * Please ensure you have proper error handling before going to production.
                 */
                TransactionError transactionError = e.Error.TransactionError;

                if (transactionError != null && transactionError.Code == "three_d_secure_action_required")
                {
                    string actionTokenId = transactionError.ThreeDSecureActionTokenId;
                    return(Redirect($"/3d-secure/authenticate.html#token_id={tokenId}&action_token_id={actionTokenId}&account_code={accountCode}"));
                }

                return(HandleError(e));
            }
            catch (Recurly.Errors.ApiError e)
            {
                return(HandleError(e));
            }

            return(Redirect(SuccessURL));
        }
コード例 #13
0
        public ActionResult ShowError(TransactionError tErrParam)
        {
            TransactionError tErr = (TransactionError)TempData["tErr"];

            if (tErr == null)
            {
                tErr = tErrParam;
            }
            return(View(ViewNames.ShowError, tErr));
        }
コード例 #14
0
ファイル: ExecuteService.cs プロジェクト: dreamsql/Outter
        private TransactionError InnerExecute(OrderExecuteEventArgs e)
        {
            TransactionError error = TransactionError.OK;

            try
            {
                var account = TradingSetting.Default.GetAccount(e.AccountId);
                var tran    = account.GetTran(e.TranId);
                if (e.TranId == null)
                {
                    return(TransactionError.TransactionNotExists);
                }
                if (e.ExecutingLot != null)
                {
                    this.PartialExecute(e.ExecutingLot.Value, tran);
                }

                if (!tran.CanExecute)
                {
                    if (tran.IsExecuted)
                    {
                        return(TransactionError.OK);
                    }
                    else
                    {
                        return(TransactionError.TransactionCannotBeExecuted);
                    }
                }
                _executeStrategy.Execute(e);
                //if (!SettingFacade.Default.SettingManager.SystemParameter.NeedsFillCheck(e.Transaction.OrderType))
                //{
                //    Trace.WriteLine("ready to book");
                //    error = this.Book(e);
                //}
                //else
                //{
                //    Trace.WriteLine("executeStrategy.Execute");
                //    _executeStrategy.Execute(e);
                //}
            }
            catch (TransactionException tranEx)
            {
                error = tranEx.ErrorCode;
                Logger.Warn(tranEx.Message);
                Trace.WriteLine(tranEx.Message);
            }
            catch (Exception ex)
            {
                error = TransactionError.RuntimeError;
                Logger.Error(ex);
                Trace.WriteLine(ex.ToString());
            }
            return(error);
        }
コード例 #15
0
        private TransactionError AcceptOrDeclineTransfer(Guid userId, Guid transferID, TransferAction action)
        {
            Guid             accountId, currencyId;
            decimal          amount;
            TransactionError error = TransferManager.AcceptTransfer(userId, transferID, action, out accountId, out currencyId, out amount);
            var account            = GetAccount(accountId);

            account.AddDeposit(currencyId, amount, true);
            account.SaveAndBroadcastChanges();
            Broadcaster.Default.Add(BroadcastBLL.CommandFactory.CreateUpdateBalanceCommand(accountId, currencyId, amount, ModifyType.Add));
            return(error);
        }
コード例 #16
0
        private Guid?GetAccountId(Guid orderId, out TransactionError errorCode)
        {
            Guid result;

            errorCode = TransactionError.OK;
            if (!Protocal.Commands.TransactionMapping.Default.GetAccountIdByOrder(orderId, out result))
            {
                errorCode = TransactionError.OpenOrderNotExists;
                return(null);
            }
            return(result);
        }
コード例 #17
0
ファイル: iExchangeEngine.cs プロジェクト: dreamsql/Outter
        public override TransactionError Cancel(Transaction tran, CancelReason reason)
        {
            TransactionError error = TransactionError.OK;

            if (!tran.CancelService.CanCancel)
            {
                return(TransactionError.TransactionCannotBeCanceled);
            }
            Logger.InfoFormat("begin in engine cancel tran={0}", tran);
            _cancelBlock.Post(Tuple.Create(tran, reason));
            return(error);
        }
コード例 #18
0
ファイル: Blockchain.cs プロジェクト: virtualeconomy/cs-v-sdk
        public ITransaction GetUnconfirmedTransactionById(string txId)
        {
            string url  = string.Format("{0}/transactions/unconfirmed/info/{1}", NodeUrl, txId);
            string json = HttpHelper.Get(url);

            try
            {
                return(TransactionParser.Parse(json));
            }
            catch (Exception)
            {
                throw TransactionError.FromJson(json);
            }
        }
コード例 #19
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state  = (StateObject)ar.AsyncState;
                Socket      client = state.workSocket;

                // 斷線時, 也會觸發此事件
                if (client.Connected == false)
                {
                    receiveDone.Set();
                    //MessageReceived?.Invoke(this, new SocketMessageEventArgs("Disconnected"));
                    return;
                }

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read
                    // more data.
                    response = state.sb.ToString();
                    if (response.IndexOf("<EOF>") > -1)
                    {
                        // Signal that all bytes have been received.
                        receiveDone.Set();

                        //// All the data has been read from the
                        //// client. Display it on the console.
                        MessageReceived?.Invoke(this, new SocketMessageEventArgs(response));
                    }
                    else
                    {
                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                            new AsyncCallback(ReceiveCallback), state);
                    }
                }
            }
            catch (Exception ex)
            {
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #20
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                string content = string.Empty;

                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state   = (StateObject)ar.AsyncState;
                Socket      handler = state.workSocket;

                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read
                    // more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<EOF>") > -1)
                    {
                        // Signal that all bytes have been received.
                        receiveDone.Set();

                        //// All the data has been read from the
                        //// client. Display it on the console.
                        //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                        //    content.Length, content);
                        //// Echo the data back to the client.
                        //Send(handler, content);
                        //Send(handler, "received");
                        MessageReceived?.Invoke(this, new SocketMessageEventArgs(content));
                    }
                    else
                    {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                             new AsyncCallback(ReceiveCallback), state);
                    }
                }
            }
            catch (Exception ex)
            {
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #21
0
ファイル: Booker.cs プロジェクト: dreamsql/Outter
        internal static bool Book(this Account account, Token token, Protocal.TransactionBookData tranData)
        {
            bool useCurrentSetting;

            Settings.Instrument instrument = Settings.Setting.Default.GetInstrument(tranData.InstrumentId);
            TransactionError    error      = account.BookForPhysicalTran(tranData, out useCurrentSetting);

            if (error != TransactionError.OK)
            {
                throw new TransactionServerException(error);
            }
            if (!useCurrentSetting)
            {
                ResetManager.Default.LoadHistorySetting(tranData.TradeDay, "Book");
            }

            var settingAccount = Settings.Setting.Default.GetAccount(account.Id, tranData.TradeDay);

            if (settingAccount == null || tranData.ExecuteTime < settingAccount.BeginTime)
            {
                throw new TransactionServerException(TransactionError.AccountIsNotTrading);
            }

            if (token.AppType == AppType.PhysicalTerminal && instrument.Category == InstrumentCategory.Physical)
            {
                if (!tranData.TryFillExecutePrice(instrument, account))
                {
                    Logger.Error("TransactionServer.Book Can't get live price to book \r\n");
                    throw new TransactionServerException(TransactionError.InvalidPrice);
                }
            }
            Transaction tran = Periphery.TransactionBLL.TransactionFacade.CreateBookTran(instrument.Category, account, tranData);

            TransactionPlacer.Default.Verify(account, tran, false, tranData.AppType, PlaceContext.Empty);
            if (tranData.CheckMargin && !account.HasEnoughMoneyToPlace(tran))
            {
                throw new TransactionServerException(TransactionError.MarginIsNotEnough);
            }
            if (account.ExecuteBookTran(tran, tranData))
            {
                if (tran.IsPhysical)
                {
                    UpdatePhysicalRequestStatus(tran);
                }
                return(true);
            }
            return(false);
        }
コード例 #22
0
 internal long PlaceBatchOrders(List <TransactionData> trans)
 {
     return(this.CallByRead(() =>
     {
         Stopwatch stopwatch = new Stopwatch();
         stopwatch.Start();
         Parallel.ForEach(trans, tran =>
         {
             var account = this.GetAccount(tran.AccountId);
             string tranCode = string.Empty;
             TransactionError error = account.Place(tran, out tranCode);
         });
         stopwatch.Stop();
         return stopwatch.ElapsedTicks;
     }, () => 0));
 }
コード例 #23
0
ファイル: KtMmfEventBus.cs プロジェクト: DevTainan/KTCommon
 public KtMmfEventBus()
 {
     _timer           = new KtTimer(double.Epsilon, ReceiveData);
     _timer.Starting += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(true));
     };
     _timer.Stopped += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(false));
     };
     _timer.Error += (object sender, ExceptionEventArgs e) =>
     {
         TransactionError?.Invoke(this, e);
     };
 }
コード例 #24
0
ファイル: KTAppEventBus.cs プロジェクト: DevTainan/KTCommon
 private KTAppEventBus()
 {
     _queue           = new ConcurrentQueue <EventBusMessageEventArgs>();
     _timer           = new KtTimer(50, ProcessQueue);
     _timer.Starting += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(true));
     };
     _timer.Stopped += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(false));
     };
     _timer.Error += (object sender, ExceptionEventArgs e) =>
     {
         TransactionError?.Invoke(this, e);
     };
 }
コード例 #25
0
        public void AddNewError()
        {
            var error = new TransactionError()
            {
                Date        = DateTime.Parse("2018-08-11"),
                Description = "Some new transaction error"
            };

            repository.Add(error);
            var expected = collectionInit.ToList();

            expected.Add(error);

            var actual = repository.GetAll().ToList();

            Assert.That(expected, Is.EquivalentTo(actual).Using(new TransactionErrorComparer()));
        }
コード例 #26
0
        public ActionResult Transfer(TransferViewModel transfer)
        {
            try
            {
                var balance = _repo.GetBalace(transfer.CheckingAccountId);
                if (balance < transfer.Amount)
                {
                    ModelState.AddModelError("Amount", "You have insufficient funds!");
                }


                // check for a valid destination account

                if (!_repo.AccountExists(transfer.DestinationCheckingAccountId))
                {
                    ModelState.AddModelError("DestinationCheckingAccountId", "Invalid destination account number.");
                }

                // add debit/credit transactions and update account balances
                if (ModelState.IsValid)
                {
                    if (_repo.Transfer(transfer.CheckingAccountId, transfer.DestinationCheckingAccountId, transfer.Amount,
                                       transfer.Message))
                    {
                        return(PartialView("_TransferSuccess", transfer));
                    }
                    var error = new TransactionError
                    {
                        Title   = "Transaction Denied",
                        Message = "Could not transfer successfuly"
                    };
                    return(View("TransactionError", error));
                }
                return(PartialView("_TransferForm"));
            }
            catch (Exception e)
            {
                var error2 = new TransactionError
                {
                    Title   = "Transaction Denied",
                    Message = e.Message
                };
                return(View("TransactionError", error2));
            }
        }
コード例 #27
0
 public static XElement Place(Session session, XmlNode tran)
 {
     try
     {
         string tranCode = string.Empty;
         Token  token    = SessionManager.Default.GetToken(session);
         foreach (XmlNode child in tran.ChildNodes)
         {
             if (child.Name == "Order")
             {
                 if (child.Attributes["Extension"] != null &&
                     child.Attributes["Extension"].Value.StartsWith("IfDone"))
                 {
                     string      oldValue = child.Attributes["Extension"].Value;
                     XmlDocument document = new XmlDocument();
                     XmlElement  element  = document.CreateElement("IfDone");
                     string[]    items    = oldValue.Split(new char[] { ' ' });
                     foreach (string item in items)
                     {
                         if (item != "IfDone")
                         {
                             string[] keyValue = item.Split(new char[] { '=' });
                             if (keyValue[0] == "LimitPrice" || keyValue[0] == "StopPrice")
                             {
                                 element.SetAttribute(keyValue[0], keyValue[1]);
                             }
                         }
                     }
                     child.Attributes["Extension"].Value = element.OuterXml;
                 }
             }
         }
         TransactionError error = Application.Default.TradingConsoleServer.Place(token, Application.Default.StateServer, tran, out tranCode);
         var dict = new Dictionary <string, string>()
         {
             { "transactionError", error.ToString() }, { "tranCode", tranCode }
         };
         return(XmlResultHelper.NewResult(dict));
     }
     catch (System.Exception exception)
     {
         AppDebug.LogEvent("TradingConsole.Place:", exception.ToString(), System.Diagnostics.EventLogEntryType.Error);
         return(XmlResultHelper.NewErrorResult());
     }
 }
コード例 #28
0
 public ActionResult Deposit(Transaction transaction)
 {
     transaction.Message = "Deposit";
     if (ModelState.IsValid)
     {
         if (_repo.DepositAmount(transaction))
         {
             return(RedirectToAction("Index", "Home"));
         }
         var error = new TransactionError
         {
             Title   = "Transaction Denied",
             Message = "Could not deposit the amount"
         };
         return(View("TransactionError", error));
     }
     return(View());
 }
コード例 #29
0
ファイル: TransferManager.cs プロジェクト: dreamsql/Outter
        internal static TransactionError ApplyTransfer(Guid userID, Account sourceAccount, Guid sourceCurrencyID,
                                                       decimal sourceAmount, Guid targetAccountID, Guid targetCurrencyID, decimal targetAmount,
                                                       decimal rate, DateTime expireDate)
        {
            TransactionError result = TransactionError.OK;

            try
            {
                result = sourceAccount.HasEnoughMoneyToTransfer(ExternalSettings.Default.DBConnectionString, sourceCurrencyID, sourceAmount);
                if (result != TransactionError.OK)
                {
                    return(result);
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                TransactionServerException transactionException = exception as TransactionServerException;
                return(transactionException == null ? TransactionError.RuntimeError : transactionException.ErrorCode);
            }
            finally
            {
            }

            Guid transferId;

            if (!TransferHelper.ApplyTransferToDB(ExternalSettings.Default.DBConnectionString, userID, sourceAccount.Id, sourceCurrencyID, sourceAmount,
                                                  targetAccountID, targetCurrencyID, targetAmount, rate, expireDate, out transferId))
            {
                Logger.Error("Save apply to DB failed");
                result = TransactionError.DbOperationFailed;
            }

            if (result == TransactionError.OK)
            {
                sourceAccount.AddDeposit(sourceCurrencyID, sourceAmount, true);
                Broadcaster.Default.Add(BroadcastBLL.CommandFactory.CreateUpdateBalanceCommand(sourceAccount.Id, sourceCurrencyID, sourceAmount, Protocal.ModifyType.Add));
                Guid remitterId = sourceAccount.Customer.Id;
                Guid payeeId    = TradingSetting.Default.GetAccount(targetAccountID).Customer.Id;
                Broadcaster.Default.Add(BroadcastBLL.CommandFactory.CreateTradingTransferCommand(transferId, remitterId, payeeId, TransferAction.Apply));
            }

            return(result);
        }
コード例 #30
0
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                //handler.Shutdown(SocketShutdown.Both);
                //handler.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }