public async Task <Order> GetAsync(int orderId)
        {
            var order = await _context.Orders.FindAsync(orderId);

            if (order != null)
            {
                await _context.Entry(order)
                .Collection(i => i.OrderItems).LoadAsync();

                await _context.Entry(order)
                .Reference(i => i.Address).LoadAsync();
            }

            return(order);
        }
        public Task <BizResponse> PROCESSSETLLEMENT(BizResponse _Resp, TradeBuyRequest TradeBuyRequestObj, ref List <long> HoldTrnNos, string accessToken = "", short IsCancel = 0)
        {
            short TrackBit = 0;

            try
            {
                TransactionQueueObj      = _TransactionRepository.GetById(TradeBuyRequestObj.TrnNo);
                TradeTransactionQueueObj = _TradeTransactionRepository.GetSingle(item => item.TrnNo == TradeBuyRequestObj.TrnNo);
                TradeBuyerListObj        = _TradeBuyerList.GetSingle(item => item.TrnNo == TradeBuyRequestObj.TrnNo);
                _TradeStopLossObj        = _TradeStopLoss.GetSingle(item => item.TrnNo == TradeBuyRequestObj.TrnNo);

                DebitWalletID   = TradeTransactionQueueObj.OrderWalletID;
                DebitAccountID  = _WalletService.GetAccWalletID(DebitWalletID);
                CreditWalletID  = TradeTransactionQueueObj.DeliveryWalletID;
                CreditAccountID = _WalletService.GetAccWalletID(CreditWalletID);

                if (TradeTransactionQueueObj.IsCancelled == 1 || IsCancel == 1)
                {
                    //Code for settlement
                    CancellationProcess(_Resp, TradeBuyRequestObj, TransactionQueueObj, TradeTransactionQueueObj);
                    return(Task.FromResult(_Resp));
                }
                if (TradeBuyRequestObj.PendingQty == 0)
                {
                    _Resp.ErrorCode  = enErrorCode.Settlement_AlreadySettled;
                    _Resp.ReturnCode = enResponseCodeService.Success;
                    _Resp.ReturnMsg  = "ALready Settled";
                    return(Task.FromResult(_Resp));
                }

                TradeBuyRequestObj.MakeTransactionHold();
                TradeBuyRequestObj.UpdatedDate  = Helpers.UTC_To_IST();
                TradeBuyRequestObj.IsProcessing = 1;
                _TradeBuyRequest.Update(TradeBuyRequestObj);

                TradeBuyerListObj.MakeTransactionHold();
                TradeBuyerListObj.UpdatedDate  = Helpers.UTC_To_IST();
                TradeBuyerListObj.IsProcessing = 1;
                _TradeBuyerList.Update(TradeBuyerListObj);

                IEnumerable <TradeSellerList> MatchSellerListBase;
                //SortedList<TradeSellerList, TradeSellerList>
                //if (TradeTransactionQueueObj.TrnType == Convert.ToInt16(enTrnType.Buy_Trade))//Take price as Highest and find lower
                //{
                //   MatchSellerListBase = _TradeSellerList.FindBy(item => item.Price <= TradeBuyRequestObj.BidPrice && item.IsProcessing == 0
                //                                       && item.BuyServiceID == TradeBuyRequestObj.PaidServiceID &&
                //                                       item.SellServiceID == TradeBuyRequestObj.ServiceID
                //                                       && (item.Status == Convert.ToInt16(enTransactionStatus.Initialize) || item.Status == Convert.ToInt16(enTransactionStatus.Hold))
                //                                       && item.RemainQty > 0);//Pending after partial Qty remain
                //}
                //else //Take price as Highest and find larger
                //{
                //    MatchSellerListBase = _TradeSellerList.FindBy(item => item.Price >= TradeBuyRequestObj.BidPrice && item.IsProcessing == 0
                //                                       && item.BuyServiceID == TradeBuyRequestObj.PaidServiceID &&
                //                                       item.SellServiceID == TradeBuyRequestObj.ServiceID
                //                                       && (item.Status == Convert.ToInt16(enTransactionStatus.Initialize) || item.Status == Convert.ToInt16(enTransactionStatus.Hold))
                //                                       && item.RemainQty > 0);//Pending after partial Qty remain
                //}
                MatchSellerListBase = _TradeSellerList.FindBy(item => item.Price >= TradeBuyRequestObj.BidPrice && item.IsProcessing == 0 &&
                                                              item.BuyServiceID == TradeBuyRequestObj.PaidServiceID &&
                                                              item.SellServiceID == TradeBuyRequestObj.ServiceID &&
                                                              (item.Status == Convert.ToInt16(enTransactionStatus.Initialize) || item.Status == Convert.ToInt16(enTransactionStatus.Hold)) &&
                                                              item.RemainQty > 0);//Pending after partial Qty remain


                //var MatchSellerList = MatchSellerListBase.OrderBy(x => x.Price).OrderBy(x => x.TrnNo);
                var MatchSellerList = MatchSellerListBase.OrderByDescending(x => x.Price).OrderBy(x => x.TrnNo);

                foreach (TradeSellerList SellerList in MatchSellerList)
                {
                    if (SellerList.IsProcessing == 1)
                    {
                        continue;
                    }

                    TrackBit = 1;
                    decimal SettlementQty = 0;
                    List <CreditWalletDrArryTrnID> CreditWalletDrArryTrnIDList = new List <CreditWalletDrArryTrnID>();
                    SellerList.IsProcessing = 1;
                    _TradeSellerList.Update(SellerList);
                    var PoolMst = _TradePoolMaster.GetById(SellerList.PoolID);
                    //====================================Partial SETTLEMENT TO MEMBER
                    if (SellerList.RemainQty < TradeBuyRequestObj.PendingQty)
                    {
                        SettlementQty = SellerList.RemainQty;//Take all Seller's Qty
                        //Topup Order create
                        PoolOrderObj = CreatePoolOrderForSettlement(TradeBuyRequestObj.UserID, SellerList.PoolID, TradeBuyRequestObj.UserID, SellerList.PoolID, TradeBuyRequestObj.TrnNo, SettlementQty, CreditWalletID, CreditAccountID);

                        TradeBuyRequestObj.PendingQty   = TradeBuyRequestObj.PendingQty - SettlementQty;
                        TradeBuyRequestObj.DeliveredQty = TradeBuyRequestObj.DeliveredQty + SettlementQty;
                        TradeBuyerListObj.DeliveredQty  = TradeBuyerListObj.DeliveredQty + SettlementQty;
                        //Here Bid Price of pool always low then user given in Order , base on above Query
                        decimal TakeDisc = 0;
                        if (SellerList.Price < TradeBuyRequestObj.BidPrice)
                        {
                            TakeDisc = (TradeBuyRequestObj.BidPrice - SellerList.Price) * SettlementQty;
                        }
                        InsertTradePoolQueue(TradeBuyRequestObj.UserID, SellerList.TrnNo, SellerList.PoolID, SellerList.RemainQty, SellerList.Price, TradeBuyRequestObj.TrnNo, SettlementQty, TradeBuyRequestObj.BidPrice, TakeDisc, 0, SellerList.Id);

                        SellerList.RemainQty = SellerList.RemainQty - SettlementQty;//this will give result 0
                        SellerList.MakeTransactionSuccess();
                        PoolMst.TotalQty = PoolMst.TotalQty - SettlementQty;
                        PoolOrderObj.MakeTransactionSuccess();
                        PoolOrderObj.DRemarks = "Delivery Success with " + SellerList.Price;
                        TransactionQueueObj.SetTransactionCode(Convert.ToInt64(enErrorCode.Settlement_PartialSettlementDone));
                        TransactionQueueObj.SetTransactionStatusMsg("Partial Settlement Done");
                        decimal SellRelQty = Helpers.DoRoundForTrading(SettlementQty * TradeBuyRequestObj.PaidQty / TradeBuyRequestObj.Qty, 8);

                        TradeTransactionQueueObj.SetTransactionCode(Convert.ToInt64(enErrorCode.Settlement_PartialSettlementDone));
                        TradeTransactionQueueObj.SetTransactionStatusMsg("Partial Settlement Done");
                        TradeTransactionQueueObj.SettledBuyQty  = TradeTransactionQueueObj.SettledBuyQty + SettlementQty;
                        TradeTransactionQueueObj.SettledSellQty = TradeTransactionQueueObj.SettledSellQty + SellRelQty;

                        CreditWalletDrArryTrnIDList.Add(new CreditWalletDrArryTrnID {
                            DrTrnRefNo = SellerList.TrnNo, Amount = SettlementQty
                        });

                        _dbContext.Database.BeginTransaction();

                        _dbContext.Set <TradePoolQueue>().Add(TradePoolQueueObj);
                        _dbContext.Entry(PoolOrderObj).State             = EntityState.Modified;
                        _dbContext.Entry(TradeBuyRequestObj).State       = EntityState.Modified;
                        _dbContext.Entry(SellerList).State               = EntityState.Modified;
                        _dbContext.Entry(PoolMst).State                  = EntityState.Modified;
                        _dbContext.Entry(TradeBuyerListObj).State        = EntityState.Modified;
                        _dbContext.Entry(TransactionQueueObj).State      = EntityState.Modified;
                        _dbContext.Entry(TradeTransactionQueueObj).State = EntityState.Modified;
                        var CreditWalletResult = _WalletService.GetWalletCreditNew(TradeTransactionQueueObj.Delivery_Currency, Helpers.GetTimeStamp(),
                                                                                   enWalletTrnType.Cr_Buy_Trade, SettlementQty, TradeBuyRequestObj.UserID,
                                                                                   CreditAccountID, CreditWalletDrArryTrnIDList.ToArray(), TradeBuyRequestObj.TrnNo, 0,
                                                                                   enWalletTranxOrderType.Credit, enServiceType.Trading, (enTrnType)TransactionQueueObj.TrnType);
                        if (CreditWalletResult.ReturnCode != enResponseCode.Success)
                        {
                            HelperForLog.WriteLogIntoFile("PROCESSSETLLEMENT RollbackTransaction", ControllerName, "Balance credit fail" + CreditWalletResult.ReturnMsg + "##TrnNo:" + TradeBuyRequestObj.TrnNo);
                            _dbContext.Database.RollbackTransaction();

                            _Resp.ErrorCode  = enErrorCode.Settlement_PartialSettlementRollback;
                            _Resp.ReturnCode = enResponseCodeService.Success;
                            _Resp.ReturnMsg  = "Partial Settlement RollBack TrnNo " + TradeBuyRequestObj.TrnNo + " With: TrnNo " + SellerList.TrnNo + "  Reason: " + CreditWalletResult.ReturnMsg;
                        }
                        else
                        {
                            _dbContext.SaveChanges();
                            _dbContext.Database.CommitTransaction();

                            HelperForLog.WriteLogIntoFile("PROCESSSETLLEMENT", ControllerName, "Partial Settlement Done with " + SellerList.TrnNo + "##TrnNo:" + TradeBuyRequestObj.TrnNo);
                            _Resp.ErrorCode  = enErrorCode.Settlement_PartialSettlementDone;
                            _Resp.ReturnCode = enResponseCodeService.Success;
                            _Resp.ReturnMsg  = "Partial Settlement Done of TrnNo " + TradeBuyRequestObj.TrnNo + " Settled: " + TradeBuyRequestObj.DeliveredQty + " Remain:" + TradeBuyRequestObj.PendingQty;
                            //Continuew as record Partially settled
                            try
                            {
                                _ISignalRService.OnStatusPartialSuccess(Convert.ToInt16(enTransactionStatus.Success), TransactionQueueObj, TradeTransactionQueueObj, accessToken, _TradeStopLossObj.ordertype);//komal                                                                                                                                                                                                                //(short Status, TransactionQueue Newtransaction, TradeTransactionQueue NewTradeTransaction, string Token, short OrderType, short IsPartial=0)
                            }
                            catch (Exception ex)
                            {
                                HelperForLog.WriteLogIntoFile("ISignalRService", ControllerName, "Partial Settlement Error " + ex.Message + "##TrnNo:" + TradeBuyRequestObj.TrnNo);
                            }
                        }
                        HoldTrnNos.Add(SellerList.TrnNo);
                    }
                    //====================================FULL SETTLEMENT TO MEMBER
                    else if (SellerList.RemainQty >= TradeBuyRequestObj.PendingQty && TradeBuyRequestObj.PendingQty != 0)
                    {
                        SettlementQty = TradeBuyRequestObj.PendingQty;
                        //Topup Order create
                        PoolOrderObj = CreatePoolOrderForSettlement(TradeBuyRequestObj.UserID, SellerList.PoolID, TradeBuyRequestObj.UserID, SellerList.PoolID, TradeBuyRequestObj.TrnNo, SettlementQty, CreditWalletID, CreditAccountID);


                        //Here Bid Price of pool always low then user given in Order , base on above Query
                        decimal TakeDisc = 0;
                        if (SellerList.Price < TradeBuyRequestObj.BidPrice)
                        {
                            TakeDisc = (TradeBuyRequestObj.BidPrice - SellerList.Price) * SettlementQty;
                        }
                        InsertTradePoolQueue(TradeBuyRequestObj.UserID, SellerList.TrnNo, SellerList.PoolID, SellerList.RemainQty, SellerList.Price, TradeBuyRequestObj.TrnNo, SettlementQty, TradeBuyRequestObj.BidPrice, TakeDisc, 0, SellerList.Id);


                        SellerList.RemainQty = SellerList.RemainQty - SettlementQty;//Update first as updated value in below line
                        SellerList.MakeTransactionHold();
                        PoolMst.TotalQty = PoolMst.TotalQty - SettlementQty;

                        TradeBuyRequestObj.DeliveredQty = TradeBuyRequestObj.DeliveredQty + SettlementQty; //Fully settled Here
                        TradeBuyRequestObj.PendingQty   = TradeBuyRequestObj.PendingQty - SettlementQty;   //this will 0

                        TradeBuyRequestObj.MakeTransactionSuccess();
                        TradeBuyerListObj.MakeTransactionSuccess();
                        TransactionQueueObj.MakeTransactionSuccess();
                        TransactionQueueObj.SetTransactionCode(Convert.ToInt64(enErrorCode.Settlement_FullSettlementDone));
                        TransactionQueueObj.SetTransactionStatusMsg("Full Settlement Done");

                        TradeTransactionQueueObj.MakeTransactionSuccess();
                        TradeTransactionQueueObj.SetTransactionCode(Convert.ToInt64(enErrorCode.Settlement_FullSettlementDone));
                        TradeTransactionQueueObj.SetTransactionStatusMsg("Full Settlement Done");
                        decimal SellRelQty = Helpers.DoRoundForTrading(SettlementQty * TradeBuyRequestObj.PaidQty / TradeBuyRequestObj.Qty, 8);
                        TradeTransactionQueueObj.SettledBuyQty  = TradeTransactionQueueObj.SettledBuyQty + SettlementQty;
                        TradeTransactionQueueObj.SettledSellQty = TradeTransactionQueueObj.SettledSellQty + SellRelQty;

                        TradeBuyerListObj.DeliveredQty = TradeBuyerListObj.DeliveredQty + SettlementQty;

                        PoolOrderObj.MakeTransactionSuccess();
                        PoolOrderObj.DRemarks = "Delivery Success with " + SellerList.Price;

                        CreditWalletDrArryTrnIDList.Add(new CreditWalletDrArryTrnID {
                            DrTrnRefNo = SellerList.TrnNo, Amount = SettlementQty
                        });

                        _dbContext.Database.BeginTransaction();

                        _dbContext.Set <TradePoolQueue>().Add(TradePoolQueueObj);
                        _dbContext.Entry(PoolOrderObj).State             = EntityState.Modified;
                        _dbContext.Entry(TradeBuyRequestObj).State       = EntityState.Modified;
                        _dbContext.Entry(SellerList).State               = EntityState.Modified;
                        _dbContext.Entry(PoolMst).State                  = EntityState.Modified;
                        _dbContext.Entry(TradeBuyerListObj).State        = EntityState.Modified;
                        _dbContext.Entry(TransactionQueueObj).State      = EntityState.Modified;
                        _dbContext.Entry(TradeTransactionQueueObj).State = EntityState.Modified;
                        var CreditWalletResult = _WalletService.GetWalletCreditNew(TradeTransactionQueueObj.Delivery_Currency, Helpers.GetTimeStamp(),
                                                                                   enWalletTrnType.Cr_Buy_Trade, SettlementQty, TradeBuyRequestObj.UserID,
                                                                                   CreditAccountID, CreditWalletDrArryTrnIDList.ToArray(), TradeBuyRequestObj.TrnNo, 1,
                                                                                   enWalletTranxOrderType.Credit, enServiceType.Trading, (enTrnType)TransactionQueueObj.TrnType);
                        if (CreditWalletResult.ReturnCode != enResponseCode.Success)
                        {
                            HelperForLog.WriteLogIntoFile("PROCESSSETLLEMENT RollbackTransaction", ControllerName, "Balance credit fail" + CreditWalletResult.ReturnMsg + "##TrnNo:" + TradeBuyRequestObj.TrnNo);
                            _dbContext.Database.RollbackTransaction();

                            _Resp.ErrorCode  = enErrorCode.Settlement_FullSettlementRollback;
                            _Resp.ReturnCode = enResponseCodeService.Success;
                            _Resp.ReturnMsg  = "Full Settlement Rollback TrnNo:" + TradeBuyRequestObj.TrnNo + " With: TrnNo " + SellerList.TrnNo + "  Reason:" + CreditWalletResult.ReturnMsg;
                        }
                        else
                        {
                            _dbContext.SaveChanges();
                            _dbContext.Database.CommitTransaction();

                            HelperForLog.WriteLogIntoFile("PROCESSSETLLEMENT", ControllerName, "Full Settlement Done with " + SellerList.TrnNo + "##TrnNo:" + TradeBuyRequestObj.TrnNo);

                            _Resp.ErrorCode  = enErrorCode.Settlement_FullSettlementDone;
                            _Resp.ReturnCode = enResponseCodeService.Success;
                            _Resp.ReturnMsg  = "Full Settlement Done of TrnNo " + TradeBuyRequestObj.TrnNo + " Settled: " + TradeBuyRequestObj.DeliveredQty + " Remain:" + TradeBuyRequestObj.PendingQty;
                            try
                            {
                                _ISignalRService.OnStatusSuccess(Convert.ToInt16(enTransactionStatus.Success), TransactionQueueObj, TradeTransactionQueueObj, accessToken, _TradeStopLossObj.ordertype); //komal
                                                                                                                                                                                                         //==============Volume update only after success
                                if (TradeTransactionQueueObj.TrnType == Convert.ToInt16(enTrnType.Buy_Trade))
                                {
                                    _IFrontTrnService.GetPairAdditionalVal(TradeTransactionQueueObj.PairID, TradeTransactionQueueObj.BidPrice, TradeTransactionQueueObj.TrnNo, TradeTransactionQueueObj.BuyQty, TradeTransactionQueueObj.TrnDate);
                                }
                                else
                                {
                                    _IFrontTrnService.GetPairAdditionalVal(TradeTransactionQueueObj.PairID, TradeTransactionQueueObj.AskPrice, TradeTransactionQueueObj.TrnNo, TradeTransactionQueueObj.SellQty, TradeTransactionQueueObj.TrnDate);
                                }

                                EmailSendAsync(TradeBuyRequestObj.UserID.ToString(), Convert.ToInt16(enTransactionStatus.Success), TradeTransactionQueueObj.PairName,
                                               TradeTransactionQueueObj.PairName.Split("_")[1], TradeTransactionQueueObj.TrnDate.ToString(),
                                               TradeTransactionQueueObj.DeliveryTotalQty, TradeTransactionQueueObj.OrderTotalQty, 0);
                            }
                            catch (Exception ex)
                            {
                                HelperForLog.WriteLogIntoFile("ISignalRService", ControllerName, "Full Settlement Error " + ex.Message + "##TrnNo:" + TradeBuyRequestObj.TrnNo);
                            }
                        }

                        HoldTrnNos.Add(SellerList.TrnNo);

                        _dbContext.Entry(SellerList).Reload();

                        SellerList.IsProcessing = 0; //Release Seller List
                        _TradeSellerList.Update(SellerList);
                        break;                       //record settled
                    }
                    //====================take always latest object from DB
                    //==========as if txn not commit so dbnot change and object value changes , so take object value from DB
                    _dbContext.Entry(TradeBuyRequestObj).Reload();
                    _dbContext.Entry(TransactionQueueObj).Reload();
                    _dbContext.Entry(TradeTransactionQueueObj).Reload();
                    _dbContext.Entry(TradeBuyerListObj).Reload();
                    _dbContext.Entry(SellerList).Reload();

                    SellerList.IsProcessing = 0;//Release Seller List
                    _TradeSellerList.Update(SellerList);
                }
                TradeBuyRequestObj.IsProcessing = 0;//Release Buy Order
                _TradeBuyRequest.Update(TradeBuyRequestObj);

                TradeBuyerListObj.IsProcessing = 0;
                _TradeBuyerList.Update(TradeBuyerListObj);
                if (TrackBit == 0)//No any record Process
                {
                    _Resp.ErrorCode  = enErrorCode.Settlement_NoSettlementRecordFound;
                    _Resp.ReturnCode = enResponseCodeService.Success;
                    _Resp.ReturnMsg  = "No Any Match Record Found";
                }
            }
            catch (Exception ex)
            {
                HelperForLog.WriteErrorLog("PROCESSSETLLEMENT:##TrnNo " + TradeBuyRequestObj.TrnNo, ControllerName, ex);
                _Resp.ReturnCode = enResponseCodeService.Fail;
                _Resp.ReturnMsg  = ex.Message;
                _Resp.ErrorCode  = enErrorCode.Settlement_SettlementInternalError;
            }
            return(Task.FromResult(_Resp));
        }