コード例 #1
0
        internal async Task OnSetupState(CancellationToken ct, Action <IGrainContext, string, TransactionQueue <TState> > setupResourceFactory)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            this.participantId = new ParticipantId(this.config.StateName, this.context.GrainReference, this.config.SupportedRoles);

            var storageFactory = this.context.ActivationServices.GetRequiredService <INamedTransactionalStateStorageFactory>();
            ITransactionalStateStorage <TState> storage = storageFactory.Create <TState>(this.config.StorageName, this.config.StateName);

            // setup transaction processing pipe
            Action deactivate   = () => grainRuntime.DeactivateOnIdle(context);
            var    options      = this.context.ActivationServices.GetRequiredService <IOptions <TransactionalStateOptions> >();
            var    clock        = this.context.ActivationServices.GetRequiredService <IClock>();
            var    timerManager = this.context.ActivationServices.GetRequiredService <ITimerManager>();

            this.queue = new TransactionQueue <TState>(options, this.participantId, deactivate, storage, clock, logger, timerManager, this.activationLifetime);

            setupResourceFactory(this.context, this.config.StateName, queue);

            // recover state
            await this.queue.NotifyOfRestore();
        }
コード例 #2
0
        public void Main()
        {
            //Invoker
            var transactionQueue = new TransactionQueue();

            //Receiver
            var suesAccount = new Account("Sue Smith", 0);

            //Commands
            var suesDeposit    = new Deposit(suesAccount, 100);
            var suesWithdrawal = new Withdraw(suesAccount, 50);

            //Receiver
            var corysAccount = new Account("Cory Melendez", 100);

            //Commands
            var corysDeposit    = new Deposit(corysAccount, 50);
            var corysWithdrawal = new Withdraw(corysAccount, 40);

            //Adding to queue to be executed, first in first out
            transactionQueue.AddTransaction(suesDeposit);
            transactionQueue.AddTransaction(corysDeposit);
            transactionQueue.AddTransaction(suesWithdrawal);
            transactionQueue.AddTransaction(corysWithdrawal);

            transactionQueue.ProcessPendingTransactions();

            Console.WriteLine($"Cory's balance: {corysAccount.Balance}");
            Console.WriteLine($"Sue's balance: {suesAccount.Balance}");
        }
コード例 #3
0
        private async Task OnSetupState(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            var boundExtension = await this.runtime.BindExtension <TransactionParticipantExtension, ITransactionParticipantExtension>(() => new TransactionParticipantExtension());

            boundExtension.Item1.Register(this.config.StateName, this);
            this.thisParticipant = boundExtension.Item2.AsTransactionParticipant(this.config.StateName);

            this.logger = loggerFactory.CreateLogger($"{context.GrainType.Name}.{this.config.StateName}.{this.thisParticipant.ToShortString()}");

            var storageFactory = this.context.ActivationServices.GetRequiredService <INamedTransactionalStateStorageFactory>();
            ITransactionalStateStorage <TState> storage = storageFactory.Create <TState>(this.config.StorageName, this.config.StateName);

            Action deactivate = () => grainRuntime.DeactivateOnIdle(context.GrainInstance);
            var    options    = this.context.ActivationServices.GetRequiredService <IOptions <TransactionalStateOptions> >();
            var    clock      = this.context.ActivationServices.GetRequiredService <IClock>();

            this.queue              = new TransactionQueue <TState>(options, this.thisParticipant, deactivate, storage, this.serializerSettings, clock, logger);
            this.resource           = new TransactionalResource <TState>(this.queue);
            this.transactionManager = new TransactionManager <TState>(this.queue);

            // recover state
            await this.queue.NotifyOfRestore();
        }
コード例 #4
0
        internal async Task OnSetupState(CancellationToken ct, Action <IGrainActivationContext, string, TransactionQueue <TState> > setupResourceFactory)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            this.participantId = new ParticipantId(this.config.StateName, this.context.GrainInstance.GrainReference, ParticipantId.Role.Resource | ParticipantId.Role.Manager);

            this.logger = loggerFactory.CreateLogger($"{context.GrainType.Name}.{this.config.StateName}.{this.context.GrainIdentity.IdentityString}");

            var storageFactory = this.context.ActivationServices.GetRequiredService <INamedTransactionalStateStorageFactory>();
            ITransactionalStateStorage <TState> storage = storageFactory.Create <TState>(this.config.StorageName, this.config.StateName);

            // setup transaction processing pipe
            Action deactivate = () => grainRuntime.DeactivateOnIdle(context.GrainInstance);
            var    options    = this.context.ActivationServices.GetRequiredService <IOptions <TransactionalStateOptions> >();
            var    clock      = this.context.ActivationServices.GetRequiredService <IClock>();

            this.queue = new TransactionQueue <TState>(options, this.participantId, deactivate, storage, this.serializerSettings, clock, logger);

            setupResourceFactory(this.context, this.config.StateName, queue);

            // recover state
            await this.queue.NotifyOfRestore();
        }
コード例 #5
0
 public GetTradeHistoryInfo GetAndSendTradeHistoryInfoData(TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, short OrderType, short IsPop = 0)
 {
     try
     {
         //var OrderHistoryList = _frontTrnRepository.GetTradeHistory(0, "", "", "", 0, 0, Newtransaction.Id);
         GetTradeHistoryInfo model = new GetTradeHistoryInfo();
         model.TrnNo      = NewTradeTransaction.TrnNo;
         model.Type       = (NewTradeTransaction.TrnType == 4) ? "BUY" : "SELL";
         model.Price      = (NewTradeTransaction.BidPrice == 0) ? NewTradeTransaction.AskPrice : (NewTradeTransaction.AskPrice == 0) ? NewTradeTransaction.BidPrice : NewTradeTransaction.BidPrice;
         model.Amount     = (NewTradeTransaction.TrnType == 4) ? NewTradeTransaction.SettledBuyQty : NewTradeTransaction.SettledSellQty;
         model.Total      = model.Type == "BUY" ? ((model.Price * model.Amount) - model.ChargeRs) : ((model.Price * model.Amount));
         model.DateTime   = Convert.ToDateTime(NewTradeTransaction.SettledDate);
         model.Status     = NewTradeTransaction.Status;
         model.StatusText = Enum.GetName(typeof(enTransactionStatus), model.Status);
         model.PairName   = NewTradeTransaction.PairName;
         model.ChargeRs   = Convert.ToDecimal(Newtransaction.ChargeRs);
         model.IsCancel   = NewTradeTransaction.IsCancelled;
         model.OrderType  = Enum.GetName(typeof(enTransactionMarketType), OrderType);
         return(model);
     }
     catch (Exception ex)
     {
         HelperForLog.WriteErrorLog(System.Reflection.MethodBase.GetCurrentMethod().Name, this.GetType().Name, ex);
         //throw ex;
         return(null);
     }
 }
コード例 #6
0
        public string CreateTransaction(TransactionQueue NewtransactionReq)
        {
            var Newtransaction = new TransactionQueue()
            {
                TrnDate      = DateTime.UtcNow,
                TrnMode      = NewtransactionReq.TrnMode,
                TrnType      = NewtransactionReq.TrnType,
                MemberID     = NewtransactionReq.MemberID,
                MemberMobile = NewtransactionReq.MemberMobile,
                SMSText      = NewtransactionReq.SMSText,
                SMSCode      = NewtransactionReq.SMSCode,
                Amount       = NewtransactionReq.Amount,
                SMSPwd       = NewtransactionReq.SMSPwd,
                ServiceID    = NewtransactionReq.ServiceID,
                SerProID     = NewtransactionReq.SerProID,
                ProductID    = NewtransactionReq.ProductID,
                RoutID       = NewtransactionReq.RoutID,
                Status       = NewtransactionReq.Status,
                StatusCode   = NewtransactionReq.StatusCode,
                StatusMsg    = NewtransactionReq.StatusMsg,
                VerifyDone   = 0,
                TrnRefNo     = NewtransactionReq.TrnRefNo,
                ChargePer    = NewtransactionReq.ChargePer,
                ChargeRs     = NewtransactionReq.ChargeRs,
                ChargeType   = NewtransactionReq.ChargeType,
            };

            _TransactionRepository.Add(Newtransaction);
            return("Success");
        }
コード例 #7
0
            public override void Run()
            {
                try
                {
                    TransactionQueue queue = new TransactionQueue(BatchSize, (tx, last) =>
                    {
                        // Apply
                        StorageEngine.apply(tx, TransactionApplicationMode.EXTERNAL);

                        // And verify that all nodes are in the index
                        VerifyIndex(tx);
                        Base += BatchSize;
                    });
                    for ( ; !End.get(); I++)
                    {
                        queue.Queue(CreateNodeAndProperty(I));
                    }
                    queue.Empty();
                }
                catch (Exception e)
                {
                    throw new Exception(e);
                }
                finally
                {
                    CommandCreationContext.close();
                }
            }
コード例 #8
0
 public BizResponse CreateTransaction(NewTransactionRequestCls NewtransactionReq)
 {
     _Resp = new BizResponse();
     try
     {
         var Newtransaction = new TransactionQueue()
         {
             TrnMode            = NewtransactionReq.TrnMode,
             TrnType            = Convert.ToInt16(NewtransactionReq.TrnType),
             MemberID           = NewtransactionReq.MemberID,
             MemberMobile       = NewtransactionReq.MemberMobile,
             TransactionAccount = NewtransactionReq.TransactionAccount,
             SMSCode            = NewtransactionReq.SMSCode,
             Amount             = NewtransactionReq.Amount,
             Status             = 0,
             StatusCode         = 0,
             StatusMsg          = "Initialise",
             TrnRefNo           = NewtransactionReq.TrnRefNo,
             AdditionalInfo     = NewtransactionReq.AdditionalInfo
         };
         _TransactionRepository.Add(Newtransaction);
         return(new BizResponse {
             ReturnMsg = "Success", ReturnCode = enResponseCodeService.Success
         });
     }
     catch (Exception ex)
     {
         _log.LogError(ex, "exception,\nMethodName:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\nClassname=" + this.GetType().Name, LogLevel.Error);
         return(new BizResponse {
             ReturnMsg = ex.Message, ReturnCode = enResponseCodeService.InternalError
         });
     }
 }
コード例 #9
0
        private async Task OnSetupState(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            this.participantId = new ParticipantId(this.config.ServiceName, this.context.GrainInstance.GrainReference, ParticipantId.Role.PriorityManager);

            this.logger = loggerFactory.CreateLogger($"{context.GrainType.Name}.{this.config.ServiceName}.{this.context.GrainIdentity.IdentityString}");

            var storageFactory = this.context.ActivationServices.GetRequiredService <INamedTransactionalStateStorageFactory>();
            ITransactionalStateStorage <OperationState> storage = storageFactory.Create <OperationState>(this.config.StorageName, this.config.ServiceName);

            // setup transaction processing pipe
            Action   deactivate = () => grainRuntime.DeactivateOnIdle(context.GrainInstance);
            var      options    = this.context.ActivationServices.GetRequiredService <IOptions <TransactionalStateOptions> >();
            var      clock      = this.context.ActivationServices.GetRequiredService <IClock>();
            TService service    = this.context.ActivationServices.GetRequiredServiceByName <TService>(this.config.ServiceName);

            this.queue = new TocTransactionQueue <TService>(service, options, this.participantId, deactivate, storage, this.serializerSettings, clock, logger);

            // Add transaction manager factory to the grain context
            this.context.RegisterResourceFactory <ITransactionManager>(this.config.ServiceName, () => new TransactionManager <OperationState>(this.queue));

            // recover state
            await this.queue.NotifyOfRestore();
        }
コード例 #10
0
 internal BatchingResponseHandler(int maxBatchSize, TransactionQueue.Applier applier, TransactionObligationFulfiller obligationFulfiller, ResponseUnpacker_TxHandler txHandler, VersionContextSupplier versionContextSupplier, Log log)
 {
     this._obligationFulfiller    = obligationFulfiller;
     this._txHandler              = txHandler;
     this._versionContextSupplier = versionContextSupplier;
     this._queue = new TransactionQueue(maxBatchSize, applier);
     this._log   = log;
 }
コード例 #11
0
        internal void SetupResourceFactory(IGrainContext context, string stateName, TransactionQueue <TState> queue)
        {
            // Add resources factory to the grain context
            context.RegisterResourceFactory <ITransactionalResource>(stateName, () => new FaultInjectionTransactionalResource <TState>(this.faultInjector, FaultInjectionControl, new TransactionalResource <TState>(queue), context, logger, grainRuntime));

            // Add tm factory to the grain context
            context.RegisterResourceFactory <ITransactionManager>(stateName, () => new FaultInjectionTransactionManager <TState>(this.faultInjector, FaultInjectionControl, new TransactionManager <TState>(queue), context, logger, grainRuntime));
        }
コード例 #12
0
        public void ProcessBatch(object tsacs)
        {
            TransactionQueue queue = (TransactionQueue)tsacs;

            foreach (Transaction item in queue)
            {
                ProcessTransaction(item);
            }
        }
コード例 #13
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        //{
        //    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        //    conn.Open();
        //    string insertQuery = "insert into [Table] ([name],[account],[amount]) values (@name1,@account1,@amount1)";
        //    SqlCommand com = new SqlCommand(insertQuery, conn);
        //    com.Parameters.AddWithValue("@name1", TextBox3.Text);
        //    com.Parameters.AddWithValue("@account1", TextBox1.Text);
        //    com.Parameters.AddWithValue("@amount1", TextBox2.Text);
        //    com.ExecuteNonQuery();
        //    Response.Redirect("manage.aspx");
        //    Response.Write("Transfer Successfull");
        //    conn.Close();
        //}

        //catch (Exception ex)
        //{
        //    Response.Write("Error:"+ex.ToString());
        //}
        if (FileUpload1.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/") + filename);
                STATUS.Text = "Upload status: File uploaded!";
                if (Session["AdminFlag"] != null)
                {
                    VIEW_STATUS.Visible = Visible;
                    VIEW_STATUS.Text    = "View All Transactions";
                }
                else
                {
                    VIEW_STATUS.Visible = Visible;
                }
                System.Diagnostics.Debug.WriteLine("Transfer Operation");
                System.Diagnostics.Debug.WriteLine("UserName:"******"New"].ToString());
                System.Diagnostics.Debug.WriteLine("User GUID:" + Session["SESSIONID"].ToString());
                System.Diagnostics.Debug.WriteLine("Session ID:" + HttpContext.Current.Session.SessionID);

                string             file  = Server.MapPath("~/ ") + filename;
                TParser            parse = new TParser(file);
                TransactionBuilder build = new TransactionBuilder();
                int BatchId = parse.Parse(build);
                TransactionQueue   queue   = build.SetBatch(BatchId);
                TransactionService service = new TransactionService();
                service.Start(queue);
            }
            catch (Exception ex)
            {
                STATUS.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }
    }
コード例 #14
0
 public void OnStatusSuccess(short Status, TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, string Token, short OrderType)
 {
     try
     {
         GetTradeHistoryInfo historyInfo  = new GetTradeHistoryInfo();
         GetBuySellBook      BuySellmodel = new GetBuySellBook();
         //update Recent Order
         //pop OpenOrder
         //add tradehistory
         //add orderhistory
         //pop buyer/seller book;
         //HelperForLog.WriteLogIntoFile("OnStatusSuccess", ControllerName, "Call ---- TransactionQueue :" + JsonConvert.SerializeObject(Newtransaction) + " TradeTransactionQueue :" + JsonConvert.SerializeObject(NewTradeTransaction));
         if (string.IsNullOrEmpty(Token))
         {
             Token = GetTokenByUserID(NewTradeTransaction.MemberID.ToString());
         }
         if (!string.IsNullOrEmpty(Token))
         {
             BuySellmodel.Amount      = 0;
             BuySellmodel.OrderId     = new Guid();
             BuySellmodel.RecordCount = 0;
             if (NewTradeTransaction.TrnType == 4)//Buy
             {
                 BuySellmodel.Price = NewTradeTransaction.BidPrice;
                 BuyerBook(BuySellmodel, NewTradeTransaction.PairName);
                 HelperForLog.WriteLogIntoFile("OnStatusSuccess", ControllerName, "BuyerBook call TRNNO:" + Newtransaction.Id);
             }
             else//Sell
             {
                 BuySellmodel.Price = NewTradeTransaction.AskPrice;
                 SellerBook(BuySellmodel, NewTradeTransaction.PairName);
                 HelperForLog.WriteLogIntoFile("OnStatusSuccess", ControllerName, "SellerBook call TRNNO:" + Newtransaction.Id);
             }
             GetAndSendRecentOrderData(Newtransaction, NewTradeTransaction, Token, OrderType);  //Update Recent
             HelperForLog.WriteLogIntoFile("OnStatusSuccess", ControllerName, " Aftre Recent Order Socket call TRNNO:" + Newtransaction.Id);
             GetAndSendOpenOrderData(Newtransaction, NewTradeTransaction, Token, OrderType, 1); //update OpenOrder
             HelperForLog.WriteLogIntoFile("OnStatusSuccess", ControllerName, " Aftre Open Order Socket call TRNNO:" + Newtransaction.Id);
             historyInfo = GetAndSendTradeHistoryInfoData(Newtransaction, NewTradeTransaction, OrderType);
             OrderHistory(historyInfo, historyInfo.PairName); //Order
             HelperForLog.WriteLogIntoFile("OnStatusSuccess", ControllerName, " Aftre Order History Socket call  : TRNNO:" + Newtransaction.Id);
             TradeHistory(historyInfo, Token);                //TradeHistory
             HelperForLog.WriteLogIntoFile("OnStatusSuccess", ControllerName, " Aftre Trade History Socket call  : TRNNO:" + Newtransaction.Id);
             var msg = EnResponseMessage.SignalRTrnSuccessfullySettled;
             msg = msg.Replace("#Price#", historyInfo.Price.ToString());
             msg = msg.Replace("#Qty#", historyInfo.Amount.ToString());
             msg = msg.Replace("#Total#", historyInfo.Total.ToString());
             ActivityNotification(msg, Token);
         }
     }
     catch (Exception ex)
     {
         HelperForLog.WriteErrorLog(System.Reflection.MethodBase.GetCurrentMethod().Name, this.GetType().Name, ex);
         //throw ex;
     }
 }
コード例 #15
0
        //When the lock is released, the first transaction in queue will try to acquire the lock again
        internal void RefreshQueue()
        {
            if (TransactionQueue.Count == 0)
            {
                return;
            }
            Tuple <Transaction, LockType> first = TransactionQueue.Dequeue();

            first.Item1.Paused = false;
            Acquire(first.Item1, first.Item2);
        }
コード例 #16
0
        static void Main(string[] args)
        {
            string             file  = @"C:\Users\Priyank Kapadia\BankInformation\Batch\batch.txt";
            TParser            parse = new TParser(file);
            TransactionBuilder build = new TransactionBuilder();
            int BatchId = parse.Parse(build);
            TransactionQueue   queue   = build.SetBatch(BatchId);
            TransactionService service = new TransactionService();

            service.Start(queue);
        }
コード例 #17
0
 public override void Start()
 {
     _stopped = false;
     RefreshFromNewStore();
     _txQueue = new TransactionQueue(_maxBatchSize, (first, last) =>
     {
         _commitProcess.commit(first, NULL, EXTERNAL);
         _pageCursorTracerSupplier.get().reportEvents();                 // Report paging metrics for the commit
         long lastAppliedRaftLogIndex             = LogIndexTxHeaderEncoding.decodeLogIndexFromTxHeader(last.transactionRepresentation().additionalHeader());
         _commandIndexTracker.AppliedCommandIndex = lastAppliedRaftLogIndex;
     });
 }
コード例 #18
0
        public void OnStatusCancel(short Status, TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, string Token, short OrderType)
        {
            try
            {
                GetTradeHistoryInfo historyInfo = new GetTradeHistoryInfo();

                //pop from OpenOrder
                //update Recent order
                //add Trade history
                //HelperForLog.WriteLogIntoFile("OnStatusCancel", ControllerName, " TransactionQueue :" + JsonConvert.SerializeObject(Newtransaction) + " TradeTransactionQueue :" + JsonConvert.SerializeObject(NewTradeTransaction));
                if (string.IsNullOrEmpty(Token))
                {
                    Token = GetTokenByUserID(NewTradeTransaction.MemberID.ToString());
                }
                if (!string.IsNullOrEmpty(Token))
                {
                    GetAndSendOpenOrderData(Newtransaction, NewTradeTransaction, Token, OrderType, 1); //with amount 0, remove from OpenOrder
                    HelperForLog.WriteLogIntoFile("OnStatusCancel", ControllerName, " Aftre Open Order Socket call : TRNNO:" + Newtransaction.Id);
                    GetAndSendRecentOrderData(Newtransaction, NewTradeTransaction, Token, OrderType);  //Update Recent
                    HelperForLog.WriteLogIntoFile("OnStatusCancel", ControllerName, " Aftre Recent Order Socket call : TRNNO:" + Newtransaction.Id);
                    historyInfo = GetAndSendTradeHistoryInfoData(Newtransaction, NewTradeTransaction, OrderType);
                    TradeHistory(historyInfo, Token);//TradeHistory
                    HelperForLog.WriteLogIntoFile("OnStatusCancel", ControllerName, " Aftre Trade History Socket call : TRNNO:" + Newtransaction.Id);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An unexpected exception occured,\nMethodName:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\nClassname=" + this.GetType().Name, LogLevel.Error);
                //throw ex;
            }
            //public void OnWalletBalChangeByUserID(WalletMasterResponse Data, string WalletTypeName, long UserID)
            //{
            //    try
            //    {
            //        //string str = "clientId=cleanarchitecture&grant_type=password&[email protected]&password=P@ssw0rd!&scope=openid profile email offline_access client_id roles phone";
            //        //str = str.Replace("=","\":\"");
            //        //str = str.Replace("&", "\",\"");
            //        //str = "{\"" + str + "\"}";
            //        //var obj = JsonConvert.DeserializeObject(str);
            //        //var jsonData= JsonConvert.SerializeObject(obj);
            //        var Redis = new RadisServices<ConnetedClientToken>(this._fact);
            //        string AccessToken = Redis.GetHashData("Tokens:" + UserID.ToString(), "Token");
            //        Token = AccessToken;
            //        BuyerSideWalletBal(Data, WalletTypeName, Token);
            //        SellerSideWalletBal(Data, WalletTypeName, Token);
            //    }
            //    catch (Exception ex)
            //    {
            //        HelperForLog.WriteErrorLog(System.Reflection.MethodBase.GetCurrentMethod().Name, this.GetType().Name, ex);
            //        //throw ex;
            //    }
        }
コード例 #19
0
 public virtual void InstallCommitProcess(TransactionCommitProcess commitProcess, long lastCommittedIndex)
 {
     lock (this)
     {
         this._lastCommittedIndex = lastCommittedIndex;
         _commandIndexTracker.AppliedCommandIndex = lastCommittedIndex;
         _log.info(format("Updated lastCommittedIndex to %d", lastCommittedIndex));
         this._queue = new TransactionQueue(_maxBatchSize, (first, last) =>
         {
             commitProcess.Commit(first, CommitEvent.NULL, TransactionApplicationMode.EXTERNAL);
             _pageCursorTracerSupplier.get().reportEvents();                     // Report paging metrics for the commit
         });
     }
 }
コード例 #20
0
 public void OnStatusPartialSuccess(short Status, TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, string Token, short OrderType)
 {
     try
     {
         GetBuySellBook BuySellmodel = new GetBuySellBook();
         //update Buyer/seller book
         //HelperForLog.WriteLogIntoFile("OnStatusPartialSuccess", ControllerName, " TransactionQueue :" + JsonConvert.SerializeObject(Newtransaction) + " TradeTransactionQueue :" + JsonConvert.SerializeObject(NewTradeTransaction));
         if (string.IsNullOrEmpty(Token))
         {
             Token = GetTokenByUserID(NewTradeTransaction.MemberID.ToString());
         }
         if (!string.IsNullOrEmpty(Token))
         {
             List <GetBuySellBook> list = new List <GetBuySellBook>();
             if (NewTradeTransaction.TrnType == 4)//Buy
             {
                 list = _frontTrnRepository.GetBuyerBook(NewTradeTransaction.PairID, NewTradeTransaction.BidPrice);
                 foreach (var model in list)
                 {
                     BuySellmodel = model;
                     break;
                 }
                 if (BuySellmodel.OrderId.ToString() != "00000000-0000-0000-0000-000000000000")
                 {
                     BuyerBook(BuySellmodel, NewTradeTransaction.PairName);
                     HelperForLog.WriteLogIntoFile("OnStatusPartialSuccess", ControllerName, "BuyerBook call TRNNO:" + Newtransaction.Id);
                 }
             }
             else//Sell
             {
                 list = _frontTrnRepository.GetSellerBook(NewTradeTransaction.PairID, NewTradeTransaction.AskPrice);
                 foreach (var model in list)
                 {
                     BuySellmodel = model;
                     break;
                 }
                 if (BuySellmodel.OrderId.ToString() != "00000000-0000-0000-0000-000000000000")
                 {
                     SellerBook(BuySellmodel, NewTradeTransaction.PairName);
                     HelperForLog.WriteLogIntoFile("OnStatusPartialSuccess", ControllerName, "SellerBook call TRNNO:" + Newtransaction.Id);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "An unexpected exception occured,\nMethodName:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\nClassname=" + this.GetType().Name, LogLevel.Error);
         //throw ex;
     }
 }
コード例 #21
0
        internal static void Participate(ITransactionParticipant participant)
        {
            if (!IsActive)
            {
                return;
            }

            TransactionQueue queue = ContextHandler.GetTransactionQueue();

            if (queue == null)
            {
                queue = new TransactionQueue();
                ContextHandler.SetTransactionQueue(queue);
            }
            queue.Add(participant);
        }
コード例 #22
0
 public void Start(TransactionQueue tsacs)
 {
     WaitCallback callBack;
     System.Diagnostics.Debug.WriteLine("Setting minimum threads for pool");
     System.Threading.ThreadPool.SetMinThreads(10, 10);
     TransactionQueue splitchunk = new TransactionQueue();
     callBack = new WaitCallback(ProcessBatch);
     for (int i = 0; i < tsacs.Queue.Count; i++)
     {
         splitchunk.Add(tsacs.Queue[i]);
         if(i % 49 == 0 && i != 0)
         {
             System.Threading.ThreadPool.QueueUserWorkItem(ProcessBatch,(object)splitchunk);
             splitchunk = null;
             splitchunk = new TransactionQueue();
         }
     }
 }
コード例 #23
0
        public void Start(TransactionQueue tsacs)
        {
            WaitCallback callBack;

            System.Diagnostics.Debug.WriteLine("Setting minimum threads for pool");
            System.Threading.ThreadPool.SetMinThreads(10, 10);
            TransactionQueue splitchunk = new TransactionQueue();

            callBack = new WaitCallback(ProcessBatch);
            for (int i = 0; i < tsacs.Queue.Count; i++)
            {
                splitchunk.Add(tsacs.Queue[i]);
                if (i % 49 == 0 && i != 0)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(ProcessBatch, (object)splitchunk);
                    splitchunk = null;
                    splitchunk = new TransactionQueue();
                }
            }
        }
コード例 #24
0
 public static void Main()
 {
     var op1 = new Operation1();
     var t   = TransactionQueue.First(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(op1)
               .Then(new Operation2());
     var r = t.Execute(0);
 }
コード例 #25
0
 public void GetAndSendOpenOrderData(TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, string Token, short OrderType, short IsPop = 0)
 {
     try
     {
         ActiveOrderInfo OpenOrderModel = new ActiveOrderInfo();
         OpenOrderModel.Id                = Newtransaction.Id;
         OpenOrderModel.TrnDate           = Newtransaction.TrnDate;
         OpenOrderModel.Type              = (NewTradeTransaction.TrnType == 4) ? "BUY" : "SELL";
         OpenOrderModel.Order_Currency    = NewTradeTransaction.Order_Currency;
         OpenOrderModel.Delivery_Currency = NewTradeTransaction.Delivery_Currency;
         if (IsPop == 1)
         {
             OpenOrderModel.Amount = 0;
         }
         else
         {
             OpenOrderModel.Amount = (NewTradeTransaction.BuyQty == 0) ? NewTradeTransaction.SellQty : (NewTradeTransaction.SellQty == 0) ? NewTradeTransaction.BuyQty : NewTradeTransaction.BuyQty;
         }
         OpenOrderModel.Price       = (NewTradeTransaction.BidPrice == 0) ? NewTradeTransaction.AskPrice : (NewTradeTransaction.AskPrice == 0) ? NewTradeTransaction.BidPrice : NewTradeTransaction.BidPrice;
         OpenOrderModel.IsCancelled = NewTradeTransaction.IsCancelled;
         OpenOrderModel.OrderType   = Enum.GetName(typeof(enTransactionMarketType), OrderType);
         OpenOrderModel.PairId      = NewTradeTransaction.PairID;
         OpenOrderModel.PairName    = NewTradeTransaction.PairName;
         OpenOrder(OpenOrderModel, Token);
         HelperForLog.WriteLogIntoFile("GetAndSendOpenOrderData", ControllerName, " After OpenOrder call TRNNO:" + Newtransaction.Id);
         if (IsPop != 1)//send notification
         {
             var msg = EnResponseMessage.SignalRTrnSuccessfullyCreated;
             msg = msg.Replace("#Price#", OpenOrderModel.Price.ToString());
             msg = msg.Replace("#Qty#", OpenOrderModel.Amount.ToString());
             ActivityNotification(msg, Token);
         }
     }
     catch (Exception ex)
     {
         HelperForLog.WriteErrorLog(System.Reflection.MethodBase.GetCurrentMethod().Name, this.GetType().Name, ex);
         //throw ex;
     }
 }
コード例 #26
0
 public void GetAndSendRecentOrderData(TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, string Token, short OrderType, short IsPop = 0)
 {
     try
     {
         RecentOrderInfo model = new RecentOrderInfo();
         model.TrnNo     = NewTradeTransaction.TrnNo;
         model.Type      = (NewTradeTransaction.TrnType == 4) ? "BUY" : "SELL";
         model.Price     = (NewTradeTransaction.BidPrice == 0) ? NewTradeTransaction.AskPrice : (NewTradeTransaction.AskPrice == 0) ? NewTradeTransaction.BidPrice : NewTradeTransaction.BidPrice;
         model.Qty       = (NewTradeTransaction.BuyQty == 0) ? NewTradeTransaction.SellQty : (NewTradeTransaction.SellQty == 0) ? NewTradeTransaction.BuyQty : NewTradeTransaction.BuyQty;
         model.DateTime  = Newtransaction.TrnDate;
         model.Status    = NewTradeTransaction.StatusMsg;
         model.PairId    = NewTradeTransaction.PairID;
         model.PairName  = NewTradeTransaction.PairName;
         model.OrderType = Enum.GetName(typeof(enTransactionMarketType), OrderType);
         RecentOrder(model, Token);
         HelperForLog.WriteLogIntoFile("GetAndSendRecentOrderData", ControllerName, "After Socket call RecentOrder TRNNO:" + Newtransaction.Id);
     }
     catch (Exception ex)
     {
         HelperForLog.WriteErrorLog(System.Reflection.MethodBase.GetCurrentMethod().Name, this.GetType().Name, ex);
         //throw ex;
     }
 }
コード例 #27
0
 public void Start(TransactionQueue tsacs)
 {
     WaitCallback callBack;
     System.Diagnostics.Debug.WriteLine("Setting minimum threads for pool");
     System.Threading.ThreadPool.SetMinThreads(10, 10);
     TransactionQueue splitchunk = new TransactionQueue();
     callBack = new WaitCallback(ProcessBatch);
     MasterAccount = tsacs.Queue[0].AccountFrom;
     for (int i = 1; i <= tsacs.Queue.Count; i++)
     {
         splitchunk.Add(tsacs.Queue[i - 1]);
         if(i % 500 == 0 ||  i == tsacs.Queue.Count)
         {
             splitchunk.BatchID = tsacs.BatchID;
             System.Threading.ThreadPool.QueueUserWorkItem(callBack,(object)splitchunk);
             splitchunk = null;
             splitchunk = new TransactionQueue();
         }
     }
 }
コード例 #28
0
        public BizResponse CancellationProcess(BizResponse _Resp, TradeBuyRequest TradeBuyRequestObj, TransactionQueue TransactionQueueObj, TradeTransactionQueue TradeTransactionQueueObj)
        {
            decimal DeliverQty = 0;

            try
            {
                //finding the return sell quantity of cancallation order depending on pendingqty of tradebuyquantity
                //ALSO DIND THE SELL BID PRICE
                DeliverQty = Helpers.DoRoundForTrading(TransactionQueueObj.Amount * TradeBuyRequestObj.PendingQty / TradeBuyRequestObj.Qty, 8);//@TotalSellQty

                if (DeliverQty == 0 || DeliverQty < 0 || DeliverQty > TransactionQueueObj.Amount)
                {
                    _Resp.ErrorCode  = enErrorCode.CancelOrder_InvalidDeliveryamount;
                    _Resp.ReturnCode = enResponseCodeService.Fail;
                    _Resp.ReturnMsg  = "Invalid Delivery amount";
                    return(_Resp);
                }
                var PoolMst = _TradePoolMaster.GetSingle(e => e.Status == 1 && e.OnProcessing > 0 && e.TotalQty > DeliverQty && e.Id == TradeBuyRequestObj.SellStockID);
                if (PoolMst == null)
                {
                    _Resp.ErrorCode  = enErrorCode.CancelOrder_StockNotAvilable;
                    _Resp.ReturnCode = enResponseCodeService.Fail;
                    _Resp.ReturnMsg  = "Stock Not Avilable";
                    return(_Resp);
                }

                CancellQueueEntry(tradeCancelQueue, TradeBuyRequestObj.TrnNo, TransactionQueueObj.ServiceID, TradeBuyRequestObj.PendingQty, DeliverQty, 0, 0, TradeBuyRequestObj.UserID);
                PoolOrderObj                = CreatePoolOrderForSettlement(TradeBuyRequestObj.UserID, TradeBuyRequestObj.SellStockID, TradeBuyRequestObj.UserID, TradeBuyRequestObj.SellStockID, TradeBuyRequestObj.TrnNo, DeliverQty, CreditWalletID, CreditAccountID);
                tradeCancelQueue.OrderID    = PoolOrderObj.Id;
                tradeCancelQueue.Status     = 1;
                TradeBuyRequestObj.IsCancel = 1;
                TradeTransactionQueueObj.SetTransactionStatusMsg("Cancellation Initiated");
                TradeTransactionQueueObj.IsCancelled = 1;
                _TradeTransactionRepository.Update(TradeTransactionQueueObj);

                _dbContext.Database.BeginTransaction();

                _dbContext.Set <TradeCancelQueue>().Add(tradeCancelQueue);
                _dbContext.Set <PoolOrder>().Add(PoolOrderObj);
                _dbContext.Entry(PoolOrderObj).State             = EntityState.Modified;
                _dbContext.Entry(TradeBuyRequestObj).State       = EntityState.Modified;
                _dbContext.Entry(TradeTransactionQueueObj).State = EntityState.Modified;
                _dbContext.SaveChanges();
                _dbContext.Database.CommitTransaction();

                if (PoolMst.TotalQty >= DeliverQty)
                {
                    PoolOrderObj.DeliveryAmt = DeliverQty;
                    PoolOrderObj.Status      = 1;
                    PoolOrderObj.DRemarks    = "Cancel order Delivery Success";
                    //PoolOrderObj.DMemberID = TradeBuyRequestObj.UserID; DeliveryGivenBy=@MemberID
                    _PoolOrder.Update(PoolOrderObj);

                    PoolMst.TotalQty    = PoolMst.TotalQty - DeliverQty;
                    PoolMst.UpdatedDate = DateTime.UtcNow;
                    PoolMst.UpdatedBy   = TradeBuyRequestObj.UserID;
                    _TradePoolMaster.Update(PoolMst);

                    TradeBuyRequestObj.Status = 1;
                    _TradeBuyRequest.Update(TradeBuyRequestObj);
                    if (TradeBuyRequestObj.DeliveredQty > 0)
                    {
                        TradeTransactionQueueObj.Status      = 1;
                        TradeTransactionQueueObj.StatusMsg   = "Success with partial cancellation";
                        TradeTransactionQueueObj.SettledDate = DateTime.UtcNow;
                        _TradeTransactionRepository.Update(TradeTransactionQueueObj);

                        TransactionQueueObj.Status    = 1;
                        TransactionQueueObj.StatusMsg = "Success with partial cancellation";
                        _TransactionRepository.Update(TransactionQueueObj);

                        TradeBuyRequestObj.Status      = 1;
                        TradeBuyRequestObj.UpdatedDate = DateTime.UtcNow;
                        _TradeBuyRequest.Update(TradeBuyRequestObj);
                    }
                    else
                    {
                        TradeTransactionQueueObj.Status      = 2;
                        TradeTransactionQueueObj.StatusMsg   = "Full Order Cancellation";
                        TradeTransactionQueueObj.SettledDate = DateTime.UtcNow;
                        _TradeTransactionRepository.Update(TradeTransactionQueueObj);

                        TransactionQueueObj.Status = 2;
                        _TransactionRepository.Update(TransactionQueueObj);

                        TradeBuyRequestObj.Status      = 2;
                        TradeBuyRequestObj.UpdatedDate = DateTime.UtcNow;
                        _TradeBuyRequest.Update(TradeBuyRequestObj);
                    }

                    tradeCancelQueue.Status      = 1;
                    tradeCancelQueue.SettledDate = DateTime.UtcNow;
                    tradeCancelQueue.UpdatedDate = DateTime.UtcNow;
                    tradeCancelQueue.StatusMsg   = "Cancellation Successful.";
                    //TCQ object update pending
                    //Update Wallet
                    //EXEC sp_InsertTransactionAccount
                    //EXEC sp_InsertLedger
                }

                _Resp.ErrorCode  = enErrorCode.CancelOrder_InsertSuccess;
                _Resp.ReturnCode = enResponseCodeService.Success;
                _Resp.ReturnMsg  = "Cancel Order Insert Success";
                return(_Resp);
            }
            catch (Exception ex)
            {
                HelperForLog.WriteErrorLog("CancellationProcess:##TrnNo " + TradeBuyRequestObj.TrnNo, ControllerName, ex);
                _dbContext.Database.RollbackTransaction();
            }
            return(_Resp);
        }
コード例 #29
0
        private static void SetupResourceFactory(IGrainContext context, string stateName, TransactionQueue <TState> queue)
        {
            // Add resources factory to the grain context
            context.RegisterResourceFactory <ITransactionalResource>(stateName, () => new TransactionalResource <TState>(queue));

            // Add tm factory to the grain context
            context.RegisterResourceFactory <ITransactionManager>(stateName, () => new TransactionManager <TState>(queue));
        }
コード例 #30
0
        public void OnStatusHold(short Status, TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, string Token, short OrderType)
        {
            try
            {
                GetTradeHistoryInfo historyInfo  = new GetTradeHistoryInfo();
                GetBuySellBook      BuySellmodel = new GetBuySellBook();
                //add buyer/seller book
                //add OpenOrder
                //add recent order
                // HelperForLog.WriteLogIntoFile("OnStatusHold", ControllerName, " TransactionQueue :" );
                if (string.IsNullOrEmpty(Token))
                {
                    Token = GetTokenByUserID(NewTradeTransaction.MemberID.ToString());
                }
                List <GetBuySellBook> list = new List <GetBuySellBook>();
                if (!string.IsNullOrEmpty(Token))
                {
                    if (NewTradeTransaction.TrnType == 4)//Buy
                    {
                        list = _frontTrnRepository.GetBuyerBook(NewTradeTransaction.PairID, NewTradeTransaction.BidPrice);
                        foreach (var model in list)
                        {
                            BuySellmodel = model;
                            break;
                        }
                        if (BuySellmodel.OrderId.ToString() != "00000000-0000-0000-0000-000000000000")
                        {
                            BuyerBook(BuySellmodel, NewTradeTransaction.PairName);
                            HelperForLog.WriteLogIntoFile("OnStatusHold", ControllerName, "BuyerBook call TRNNO:" + Newtransaction.Id + " Pair :" + NewTradeTransaction.PairName);
                        }
                    }
                    else//Sell
                    {
                        list = _frontTrnRepository.GetSellerBook(NewTradeTransaction.PairID, NewTradeTransaction.AskPrice);
                        foreach (var model in list)
                        {
                            BuySellmodel = model;
                            break;
                        }
                        if (BuySellmodel.OrderId.ToString() != "00000000-0000-0000-0000-000000000000")
                        {
                            SellerBook(BuySellmodel, NewTradeTransaction.PairName);
                            HelperForLog.WriteLogIntoFile("OnStatusHold", ControllerName, "SellerBook call TRNNO:" + Newtransaction.Id + " Pair :" + NewTradeTransaction.PairName);
                        }
                    }
                    //var msg = EnResponseMessage.SignalRTrnSuccessfullyCreated;
                    //msg = msg.Replace("#Price#", historyInfo.Price.ToString());
                    //msg = msg.Replace("#Qty#", historyInfo.Amount.ToString());
                    //ActivityNotification(msg, Token);

                    GetAndSendOpenOrderData(Newtransaction, NewTradeTransaction, Token, OrderType);
                    HelperForLog.WriteLogIntoFile("OnStatusHold", ControllerName, " Aftre Open Order Socket call  TRNNO:" + Newtransaction.Id);
                    GetAndSendRecentOrderData(Newtransaction, NewTradeTransaction, Token, OrderType);
                    HelperForLog.WriteLogIntoFile("OnStatusHold", ControllerName, " Aftre Recent Order Socket call  TRNNO:" + Newtransaction.Id);
                }
            }
            catch (Exception ex)
            {
                HelperForLog.WriteErrorLog(System.Reflection.MethodBase.GetCurrentMethod().Name, this.GetType().Name, ex);
                ////throw ex;
            }
        }
コード例 #31
0
        public ThirdPartyAPIRequest MakeWebRequest(long routeID, long thirdpartyID, long serproDetailID, TransactionQueue TQ = null)
        {
            try
            {
                RouteConfiguration         routeConfiguration;
                ThirdPartyAPIConfiguration thirdPartyAPIConfiguration;
                //ProviderConfiguration providerConfiguration;
                //ServiceProviderDetail ServiceProviderDetail;
                ServiceProConfiguration     ServiceProConfiguration;
                ThirdPartyAPIRequest        thirdPartyAPIRequest = new ThirdPartyAPIRequest();
                Dictionary <string, string> keyValuePairs        = new Dictionary <string, string>();
                WebHeaderCollection         keyValuePairsHeader  = new WebHeaderCollection();


                thirdPartyAPIConfiguration = _thirdPartyCommonRepository.GetById(thirdpartyID);
                var SerProconfigID = _serviceProviderDetail.GetSingle(item => item.Id == serproDetailID).ServiceProConfigID;
                ServiceProConfiguration = _ServiceProConfiguration.GetSingle(item => item.Id == SerProconfigID);
                routeConfiguration      = _routeRepository.GetById(routeID);


                thirdPartyAPIRequest.RequestURL  = thirdPartyAPIConfiguration.APISendURL;
                thirdPartyAPIRequest.RequestBody = thirdPartyAPIConfiguration.APIRequestBody;

                if (thirdPartyAPIConfiguration == null || routeConfiguration == null)
                {
                    return(thirdPartyAPIRequest);
                }

                keyValuePairs.Add("#OPERATORCODE#", routeConfiguration.OpCode);
                //keyValuePairs.Add("#WALLETID#", routeConfiguration.ProviderWalletID);
                keyValuePairs.Add("#ORGADDRESS#", routeConfiguration.ProviderWalletID);// Org Wallet Address/ID

                if (!string.IsNullOrEmpty(thirdPartyAPIConfiguration.TimeStamp))
                {
                    keyValuePairs.Add("#TIMESTAMP#", Helpers.UTC_To_IST().ToString(thirdPartyAPIConfiguration.TimeStamp));
                }

                if (TQ != null)//Rita 25-10-2018 incase of transation
                {
                    keyValuePairs.Add("#SMSCODE#", TQ.SMSCode);
                    keyValuePairs.Add("#TRANSACTIONID#", TQ.Id.ToString());
                    keyValuePairs.Add("#AMOUNT#", TQ.Amount.ToString());
                    keyValuePairs.Add("#USERADDRESS#", TQ.TransactionAccount);
                    keyValuePairs.Add("#CONVERTEDAMT#", (routeConfiguration.ConvertAmount * TQ.Amount).ToString());
                }
                else//In case of Wallet Operation
                {
                }

                //Rushabh 11-10-2018 For Authorization Header
                if (thirdPartyAPIConfiguration.AuthHeader != string.Empty)
                {
                    foreach (string mainItem in thirdPartyAPIConfiguration.AuthHeader.Split("###"))
                    {
                        string[] item = mainItem.Split(":");
                        //thirdPartyAPIRequest.RequestURL = thirdPartyAPIRequest.RequestURL.Replace(item[0], item[1]);
                        //thirdPartyAPIRequest.RequestBody = thirdPartyAPIRequest.RequestBody.Replace(item[0], item[1]);
                        string authInfo = ServiceProConfiguration.UserName + ":" + ServiceProConfiguration.Password;
                        item[1] = item[1].Replace("#BASIC#", Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)));
                        if (item[0] == "Sign") // ntrivedi for withdaraw
                        {
                            string hashSignHeader = hashMACsha512(thirdPartyAPIRequest.RequestURL, item[1]);
                            //AddToLog("Transaction Req hashSignHeader=" & hashSignHeader, "ThirdPartyAPI", trnObj)
                            //  myReq.Headers.Add(HeaderKeyValuePairArray(0), hashSignHeader)
                            keyValuePairsHeader.Add(item[0], hashSignHeader);
                        }
                        else
                        {
                            keyValuePairsHeader.Add(item[0], item[1]);
                        }
                    }
                }

                foreach (KeyValuePair <string, string> item in keyValuePairs)
                {
                    thirdPartyAPIRequest.RequestURL = thirdPartyAPIRequest.RequestURL.Replace(item.Key, item.Value);
                    if (thirdPartyAPIRequest.RequestBody != null)
                    {
                        thirdPartyAPIRequest.RequestBody = thirdPartyAPIRequest.RequestBody.Replace(item.Key, item.Value);
                    }
                }
                //Rita 25-10-2018 added in common dynamic header part
                //if(thirdPartyAPIConfiguration.AuthHeader == "RPC")
                //{
                //    string authInfo = ServiceProConfiguration.UserName + ":" + ServiceProConfiguration.Password;
                //    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                //    authInfo = "Basic " + authInfo;
                //    keyValuePairsHeader.Add("Authorization", authInfo);
                //}
                thirdPartyAPIRequest.keyValuePairsHeader = keyValuePairsHeader;

                thirdPartyAPIRequest.DelayAddress = routeConfiguration.IsDelayAddress;
                thirdPartyAPIRequest.walletID     = routeConfiguration.ProviderWalletID;
                return(thirdPartyAPIRequest);
            }
            catch (Exception ex)
            {
                HelperForLog.WriteErrorLog("GetWebRequest", "MakeWebRequest", ex);
                throw ex;
            }
        }
コード例 #32
0
 internal static void SetTransactionQueue(TransactionQueue queue)
 {
     SetObject(TransactionQueueIdent, queue);
 }