public ResultViewControl(tableViewModel tvm, bool getResultByTreeView)
        {

            InitializeComponent();
            if (tvm != null)
            {
                MainGirdViewControl mainGridView = new MainGirdViewControl(tvm, getResultByTreeView);
                result = mainGridView.result;
                _tableName = tvm._table.name;
                tvm1 = tvm;

                if (this.StackPanelResultViewControl.Children.Count == 0)
                {
                    this.StackPanelResultViewControl.Children.Add(mainGridView);
                    this.ResultTab.IsSelected = true;             
                    this.CustomQueryAccordion.SelectionMode = AccordionSelectionMode.ZeroOrMore;
                    int mainGridWidth = (((FastDB.ResultViewModel)(mainGridView.MainDataGrid.DataContext)).EndColumn * 160);
                    {
                        mainGridView.MainDataGrid.Width = mainGridWidth;
                    }
                    mainGridView.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                }
                this.DataContext = result;
            }
        }
        public CrossTabulationViewControl(tableViewModel tvm, bool getResultByTreeView)
        {
            InitializeComponent();
            _tableName = tvm._table.name;
            result = new ResultViewModel(tvm, getResultByTreeView);
            if (result != null)
            {

                this.DataContext = result;
            }

        }
        private void OnResultAdded(Result result)
        {
            ResultViewModel resultViewModel = new ResultViewModel(result);
            result.Save();

            // TODO: Only supports one experiment
            ResultsViewModel resultsViewModel = (ResultsViewModel)Project[0].Children[0].Children.Where(item => item is ResultsViewModel).FirstOrDefault();

            if (resultsViewModel != null)
            {
                resultsViewModel.Children.Add(resultViewModel);
            }
        }
        public MainGirdViewControl(tableViewModel tvm, bool getResultByTreeView)
        {
            InitializeComponent();

            _tableName = tvm._table.name;
            result = new ResultViewModel(tvm, getResultByTreeView);

            //this.DataContext = result;
            //int rowCount = this.MainDataGrid.Items.Count;

            //ResultViewModel result = (ResultViewModel)this.DataContext;
            if (result != null)
            {

                this.DataContext = result;

                // manualy adding grid column this is just a test
                //Microsoft.Windows.Controls.DataGridTextColumn dataGridTextColumn   = new Microsoft.Windows.Controls.DataGridTextColumn();
                //dataGridTextColumn.Header = "Gajendra";
                //this.MainDataGrid.Columns.Add(dataGridTextColumn);

                ShowControl();

                //CurrenPage = CurrenPage + 1;
                //this.lblPageNumber.Content = "Page " + CurrenPage.ToString() + " Of " + rowToatlPage.ToString();


                rowToatlPage = getnumberOfPages(result.TotalIRows, result.rowPageSize);
                columnToatlPage = getnumberOfPages(result.TotalColumns, result.columnPageSize);

                if (rowToatlPage > 0)
                {
                    RowCurrenPage = 1;
                    getPageInfo(RowCurrenPage, result.rowPageSize, result.TotalIRows, out startRow, out EndCurrentPageRow);
                    this.lblRowNumber.Content = "Row " + startRow.ToString() + " - " + EndCurrentPageRow.ToString() + " Of " + result.TotalIRows.ToString();
                    this.lblPageNumber.Content = "Page " + RowCurrenPage.ToString() + " Of " + rowToatlPage.ToString();
                }
                if (columnToatlPage > 0 && result.TotalIRows != 0)
                {
                    ColCurrenPage = 1;
                    getPageInfo(ColCurrenPage, result.columnPageSize, result.TotalColumns, out startColumn, out EndCurrentPageColumn);
                    this.lblColumnNumber.Content = "Col " + startColumn.ToString() + " - " + EndCurrentPageColumn.ToString() + " Of " + result.TotalColumns.ToString();
                }

            }
        }
        public CrossTabulationViewControl(SQLBuilder.SelectQueryBuilder QuerryBuilder, string CurrentDatabaseName)
        {
            InitializeComponent();
            result = new ResultViewModel(QuerryBuilder, CurrentDatabaseName);
            if (result != null)
            {

                this.DataContext = result;
                if (result.QueryBulder != null)
                {
                    if (result.QueryBulder.SelectedTables.Count != 0)
                    {
                        _tableName = result.QueryBulder.SelectedTables[0].Name;
                    }
                }
            }
            PopulateCrossTabulationViewControl(QuerryBuilder);
        }
 public ResultViewControl(SQLBuilder.SelectQueryBuilder QuerryBuilder, string CurrentDatabaseName)
 {
     InitializeComponent();
     if (QuerryBuilder.CrossTabClause != null)
     {
         if (QuerryBuilder.CrossTabClause.Col == null)
         {
             if (this.StackPanelResultViewControl.Children.Count == 0)
             {
                 MainGirdViewControl mainGridView = new MainGirdViewControl(QuerryBuilder, CurrentDatabaseName);
                 result = mainGridView.result;
                 this.StackPanelResultViewControl.Children.Add(mainGridView);
                 this.ResultTab.IsSelected = true;
                 this.CustomQueryAccordion.SelectionMode = AccordionSelectionMode.ZeroOrMore;
                 int mainGridWidth = (((FastDB.ResultViewModel)(mainGridView.MainDataGrid.DataContext)).EndColumn * 160);
                 {
                     mainGridView.MainDataGrid.Width = mainGridWidth;
                 }
                 mainGridView.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;    //zahed
             }
         }
         else
         {
             if (this.StackPanelResultViewControl.Children.Count == 1)
             {
                 if ((MainGirdViewControl)this.StackPanelResultViewControl.Children[0] != null)
                 {
                     this.StackPanelResultViewControl.Children.RemoveAt(0);
                 }
             }
             CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(QuerryBuilder, CurrentDatabaseName);
             result = crossTabViewControl.result;
             this.ResultTab.IsSelected = true;
             this.CustomQueryAccordion.SelectionMode = AccordionSelectionMode.ZeroOrMore;
             this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
         }
     }
     this.DataContext = result;
 }
Beispiel #7
0
        public ActionResult Put(int id, ResultViewModel resultVM)
        {
            bool updated = _resultsService.Update(id, resultVM);

            return(updated ? (ActionResult)Ok() : BadRequest());
        }
Beispiel #8
0
        public ActionResult AvailableResults(int?tabId = null)
        {
            int[] availableTabIds = _tabService.GetAllTabIds();

            if (availableTabIds == null || availableTabIds.Length == 0)
            {
                return(View(model: null));
            }

            int    targetTabId = tabId ?? availableTabIds[0];
            Result resultByTab;

            try
            {
                resultByTab = _scheduleResultService.GetResult(targetTabId);
            }
            catch
            {
                return(View(model: null));
            }

            var resultViewModel = new ResultViewModel
            {
                Id                = resultByTab.Id,
                Chain             = resultByTab.Chain,
                AlgorithSummaries = resultByTab.AlgorithSummaries,
                PlotData          = resultByTab.PlotData,
                TabIds            = availableTabIds,
                CurrentTab        = targetTabId
            };

            return(View(resultViewModel));

            //var fakeResult = new ResultViewModel
            //{
            //    Id = 1,
            //    TabIds = new[] { 1, 2, 3 },
            //    Chain = new decimal[,] { { 1.2m, 5 }, { 2.2m, 4 }, { 3.2m, 8 }, { 4.2m, 8 }, { 5.2m, 5 }, { 6.2m, 5 }, { 6.2m, 5 }, { 6.2m, 5 }, { 6.2m, 5 } },
            //    AlgorithSummary = new AlgorithSummary[]
            //    {
            //         new AlgorithSummary
            //         {
            //            Type = AlgorithmType.A1,
            //            Cstar = 4,
            //            Cmax = 17
            //         },
            //         new AlgorithSummary
            //         {
            //            Type = AlgorithmType.A2,
            //            Cstar = 7,
            //            Cmax = 97
            //         },
            //         new AlgorithSummary
            //         {
            //            Type = AlgorithmType.A3,
            //            Cstar = 6,
            //            Cmax = 777
            //         },
            //         new AlgorithSummary
            //         {
            //            Type = AlgorithmType.A4,
            //            Cstar = 66,
            //            Cmax = 76
            //         },
            //    },
            //    PlotData = new Dictionary<AlgorithmType, Plot>
            //        {
            //            { AlgorithmType.A1, new Plot
            //                {
            //                       { 6, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 19.1m,
            //                                Duration = 4,
            //                                End = 7.7m
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 20.1m,
            //                                Duration = 5,
            //                                End = 15.7m
            //                            }
            //                        }
            //                    },
            //                    { 5, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 19.1m,
            //                                Duration = 3,
            //                                End = 4
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 20.1m,
            //                                Duration = 2,
            //                                End = 9
            //                            }
            //                        }
            //                    }
            //                }
            //            },
            //            { AlgorithmType.A2,  new Plot
            //                {
            //                       { 1, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 2.1m,
            //                                Duration = 2,
            //                                End = 3
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 1.1m,
            //                                Duration = 13,
            //                                End = 18
            //                            }
            //                        }
            //                    },
            //                    { 2, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 5.1m,
            //                                Duration = 2,
            //                                End = 2
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 6.1m,
            //                                Duration = 4,
            //                                End = 9
            //                            }
            //                        }
            //                    }
            //                }
            //            },{ AlgorithmType.A3,  new Plot
            //                {
            //                       { 3, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 3.1m,
            //                                Duration = 4,
            //                                End = 8
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 6.1m,
            //                                Duration = 7,
            //                                End = 18.5m
            //                            }
            //                        }
            //                    },
            //                    { 4, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 5.1m,
            //                                Duration = 2,
            //                                End = 2.3m
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 6.1m,
            //                                Duration = 4,
            //                                End = 9.7m
            //                            }
            //                        }
            //                    },
            //                    { 20, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 5.1m,
            //                                Duration = 2,
            //                                End = 2.3m
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 6.1m,
            //                                Duration = 4,
            //                                End = 9.7m
            //                            }
            //                        }
            //                    },
            //                    { 21, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 5.1m,
            //                                Duration = 2,
            //                                End = 2.3m
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 6.1m,
            //                                Duration = 4,
            //                                End = 9.7m
            //                            }
            //                        }
            //                    }
            //                }
            //            },{ AlgorithmType.A4,  new Plot
            //                {
            //                       { 8, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork =15.1m,
            //                                Duration = 9,
            //                                End = 9
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 16.1m,
            //                                Duration = 4,
            //                                End = 15
            //                            }
            //                        }
            //                    },
            //                    { 9, new PlotRowPerDevice[]
            //                        {
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 12.1m,
            //                                Duration = 1,
            //                                End = 3
            //                            },
            //                            new PlotRowPerDevice
            //                            {
            //                                PalletWork = 13.1m,
            //                                Duration = 3,
            //                                End = 6
            //                            }
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //};

            //return View(fakeResult);
        }
 public void Name()
 {
     ResultViewModel viewModel = new ResultViewModel(new Result("name", null));
     Assert.AreEqual("name", viewModel.Name);
 }
Beispiel #10
0
        public Result()
        {
            InitializeComponent();

            BindingContext = new ResultViewModel();
        }
 public ResultView()
 {
     InitializeComponent();
     DataContext = new ResultViewModel();
 }
Beispiel #12
0
        public virtual ActionResult Results()
        {
            var model = new List <ResultViewModel>();

            var answers = _service.GetAnswers();
            var allAvalivableAnswers = _service.GetAvalivableAnswers();
            var questions            = _service.GetQuestions();
            var users = _service.GetUsers();

            var answersCount = users.Count();

            if (answersCount == 0)
            {
                return(RedirectToAction(MVC.Home.Index()));
            }

            foreach (var question in questions)
            {
                var item = new ResultViewModel();
                item.Question       = question.Text;
                item.QuestionNumber = question.Number;

                foreach (var avalivableAnswer in allAvalivableAnswers.Where(x => x.QuestionId == question.QuestionId))
                {
                    item.AnswersResults.Add(new AnswerResultViewModel()
                    {
                        AvalivableAnswerId   = avalivableAnswer.AvalivableAnswerId,
                        AvalivableAnswerText = avalivableAnswer.Text,
                        Quantity             = 0,
                        Percentage           = 0
                    });
                }

                foreach (var answer in answers.Where(x => x.QuestionId == question.QuestionId))
                {
                    var index = item.AnswersResults.FindIndex(x => x.AvalivableAnswerId == answer.AvalivableAnswerId);
                    if (index >= 0)
                    {
                        item.AnswersResults[index].Quantity++;
                    }
                }

                var itemAnswersCount = item.AnswersResults.Sum(x => x.Quantity);
                foreach (var answerItem in item.AnswersResults)
                {
                    if (itemAnswersCount == 0)
                    {
                        answerItem.Percentage = 0;
                    }
                    else
                    {
                        var percentage = (decimal)answerItem.Quantity / (decimal)itemAnswersCount;
                        answerItem.Percentage = Math.Round(percentage, 2, MidpointRounding.AwayFromZero);
                    }
                }

                model.Add(item);
            }

            return(View(model));
        }
Beispiel #13
0
        public ActionResult Result(DateTime?resultDate)
        {
            ResultViewModel viewModel = ResultViewModel.Create(_tResultRepository, resultDate);

            return(View(viewModel));
        }
Beispiel #14
0
        public ResultViewModel FnUpdateCurrentAssignedTo(ApprovalSpotterDetails model, string UserName)
        {
            string userMail = "";

            glog.Debug("FnUpdateCurrentAssignedTo: Entry");
            var result = new ResultViewModel();

            using (var db = new MainDbContext())
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        if (FnGetApprovingOfficerAvailbility(model.AssignedTo))
                        {
                            userMail = db.Sys_Users.FirstOrDefault(x => x.Name == UserName).Email;

                            var approvalProcessDtl = db.Approval_ProcessDetail.Where(w => w.ApprovalProcessID == model.ApprovalProcessDetailID).FirstOrDefault();
                            approvalProcessDtl.AssignedTo     = model.AssignedTo;
                            approvalProcessDtl.ReassignDate   = DateTime.Now;
                            approvalProcessDtl.ReassignBy     = userMail;
                            approvalProcessDtl.ReassignReason = model.ReassignReason;

                            db.Approval_ProcessDetail.Add(approvalProcessDtl);
                            db.Entry(approvalProcessDtl).State = System.Data.Entity.EntityState.Modified;
                            var Id = db.SaveChanges();
                            if (Id > 0)
                            {
                                transaction.Commit();
                                string EmpEmailId  = GetEmailByEmpCode(model.AssignedTo);
                                var    isEmailSend = SendReassignEmailNotificationAPI(model, EmpEmailId, UserName, userMail, model.AssignedTo);
                                result.Status  = 1;
                                result.Message = String.Format("Approval reassign to {0}", GetApprovingOfficerNameByCode(model.AssignedTo));
                            }
                            else
                            {
                                transaction.Rollback();
                                result.Status  = 0;
                                result.Message = "An error occurred while reassign task!";
                            }
                        }
                        else
                        {
                            result.Status  = 2;
                            result.Message = "Selected approving officer is currently unavailable. Please select another approving officer.Thanks";
                        }
                    }
                    catch (Exception ex)
                    {
                        glog.Error("FnUpdateCurrentAssignedTo Exception: " + ex.Message + ex.InnerException);
                        result.Status  = 0;
                        result.Message = "Please contact MIS, error: " + ex.Message;
                        transaction.Rollback();
                    }
                    finally
                    {
                        transaction.Dispose();
                    }
                    glog.Debug("FnUpdateCurrentAssignedTo: Exit");
                    return(result);
                }
            }
        }
Beispiel #15
0
        public ActionResult ViewScore(ResultViewModel resultViewModel)
        {
            IEnumerable <ResultViewModel> resultViewModels = testService.CalculateScore(resultViewModel);

            return(View(resultViewModels));
        }
Beispiel #16
0
        public ResultViewModel FnApproveRejectEvent(ApprovalSpotterDetails model, string UserName)
        {
            string userMail = "";
            int    maxTier = 0, currentTier = 0;

            glog.Debug("InsertSpotterData: Entry");
            var result = new ResultViewModel();

            using (var db = new MainDbContext())
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        userMail = db.Sys_Users.FirstOrDefault(x => x.Name == UserName).Email;
                        bool IsSave = false;

                        if (!string.IsNullOrEmpty(model.RejectReason))
                        {
                            var RejectedAmount = model.OutstandingFee.Select(s => s.SpotterAmt).Sum();
                            var ApprovedAmount = model.SpotterSummary.Amount - RejectedAmount;
                            if (FnUpdateCurrentApproval(db, model.IsAllCheck, model.ApprovalProcessID, model.RejectReason, userMail))
                            {
                                if (FnUpdateSpotterMaster(db, model.IsAllCheck, model.SpotterSummary.SpotterRefNumber, ApprovedAmount, model.RejectReason, userMail))
                                {
                                    if (FnUpdateSpotterDetail(db, model.OutstandingFee, model.ApprovalProcessDetailID, model.RejectReason, userMail))
                                    {
                                        if (FnUpdateContractSpotter(db, model.OutstandingFee, model.ApprovalProcessDetailID, model.RejectReason, userMail))
                                        {
                                            IsSave = true;
                                        }
                                        else
                                        {
                                            IsSave = false;
                                        }
                                    }
                                    else
                                    {
                                        IsSave = false;
                                    }
                                }
                                else
                                {
                                    IsSave = false;
                                }
                            }
                            else
                            {
                                IsSave = false;
                            }
                        }
                        else
                        {
                            maxTier     = db.Sys_Approval.Where(w => w.ApprovalHeaderID == model.ApprovalHeaderID).Select(s => s.Tier).FirstOrDefault();
                            currentTier = db.Approval_ProcessDetail.Where(w => w.ApprovalProcessID == model.ApprovalProcessID).Select(s => s.Tier).Max();
                            var ApprovedAmount = model.OutstandingFee.Select(s => s.SpotterAmt).Sum();
                            if (currentTier == maxTier)
                            {
                                if (FnUpdateCurrentApproval(db, model.IsAllCheck, model.ApprovalProcessID, model.RejectReason, userMail))
                                {
                                    if (FnUpdateSpotterMaster(db, model.IsAllCheck, model.SpotterSummary.SpotterRefNumber, ApprovedAmount, model.RejectReason, userMail))
                                    {
                                        if (FnUpdateSpotterDetail(db, model.OutstandingFee, model.ApprovalProcessDetailID, model.RejectReason, userMail))
                                        {
                                            if (FnUpdateContractSpotter(db, model.OutstandingFee, model.ApprovalProcessDetailID, model.RejectReason, userMail))
                                            {
                                                IsSave = true;
                                            }
                                            else
                                            {
                                                IsSave = false;
                                            }
                                        }
                                        else
                                        {
                                            IsSave = false;
                                        }
                                    }
                                    else
                                    {
                                        IsSave = false;
                                    }
                                }
                                else
                                {
                                    IsSave = false;
                                }
                            }
                            else
                            {
                                var             sysApproval          = db.Sys_Approval.Where(w => w.ApprovalHeaderID == model.ApprovalHeaderID).FirstOrDefault();
                                ApprovalProcess approvalProcessModel = new ApprovalProcess()
                                {
                                    ApprovalDetailID = model.ApprovalProcessID,
                                    CurrentTier      = currentTier,
                                    ApprovalHeaderID = model.ApprovalHeaderID,
                                    ModuleID         = sysApproval.ModuleID,
                                    ApprovalName     = sysApproval.ApprovalName,
                                    RefNo            = model.SpotterSummary.SpotterRefNumber,
                                    UserName         = userMail
                                };
                                result = FnStartNewProcessTier(approvalProcessModel);
                                if (result.Status == 1)
                                {
                                    IsSave = true;
                                }
                                else
                                {
                                    IsSave = false;
                                }
                            }
                        }

                        if (IsSave)
                        {
                            transaction.Commit();
                            string EmpEmailId   = string.Empty;
                            var    employeeCode = "";
                            if (currentTier == maxTier)
                            {
                                employeeCode = db.Sys_Users.FirstOrDefault(x => x.Name == UserName).EmployeeCode;
                                EmpEmailId   = GetEmailByEmpCode(employeeCode);
                            }
                            else
                            {
                                employeeCode = db.Approval_ProcessDetail.FirstOrDefault(x => x.ApprovalProcessID == model.ApprovalProcessID).AssignedTo;
                                EmpEmailId   = GetEmailByEmpCode(employeeCode);
                            }
                            var isEmailSend = SendEmailNotificationAPI(model, EmpEmailId, UserName, userMail, currentTier, maxTier, employeeCode);
                            result.Status = 1;
                            if (string.IsNullOrEmpty(model.RejectReason))
                            {
                                result.Message = "Data has been approved!";
                            }
                            else
                            {
                                result.Message = "Data has been rejected!";
                            }
                        }
                        else
                        {
                            transaction.Rollback();
                            result.Status  = 0;
                            result.Message = "An error occurred when updating approval process";
                        }
                    }
                    catch (Exception ex)
                    {
                        glog.Error("FnApproveRejectEvent Exception: " + ex.Message + ex.InnerException);
                        result.Status  = 0;
                        result.Message = "Please contact MIS, error: " + ex.Message;
                        transaction.Rollback();
                    }
                    finally
                    {
                        transaction.Dispose();
                    }
                    glog.Debug("FnApproveRejectEvent: Exit");
                    return(result);
                }
            }
        }
Beispiel #17
0
 public IActionResult Failed(ResultViewModel <Dictionary <string, object> > result)
 {
     return(View(nameof(Failed), result.Message));
 }
Beispiel #18
0
 public IActionResult Succes(ResultViewModel <Dictionary <string, object> > result)
 {
     return(View(nameof(Succes), result));
 }
        //
        // GET: /Result/
        public ActionResult Index(ResultMessage?message, string userName)
        {
            var model = new ResultViewModel();

            switch (message)
            {
            case ResultMessage.RegisterStepTwo:
                model.Title = "הוראות הרשמה";
                model.Text  = "להשלמת הרישום, נא כנס לדוא\"ל שלך להמשך הרשמה.";
                model.Type  = ResultType.info;
                break;

            case ResultMessage.ConfirmationSuccess:
                model.Title = "ההרשמה הושלמה";
                model.Text  = "השלמת את תהליך הרישום.";
                model.Type  = ResultType.success;
                break;

            case ResultMessage.ConfirmationFailure:
                model.Title = "שגיאה בהרשמה";
                model.Text  = "הייתה שגיאה באישור הדוא\"ל שלך, אנא נסה שוב.";
                model.Type  = ResultType.danger;
                break;

            case ResultMessage.ResetPasswordEmail:
                model.Title = "בקשת שחזור סיסמא נשלחה לכתובת הדוא\"ל " + userName;
                model.Text  = "אם אינך רואה הודעה זו בתיבת הדואר הנכנס שלך בתוך 15 דקות, חפש אותה בתיקיית דואר זבל שלך. אם אתה מוצא אותו שם, נא סמן אותה כ-לא זבל. ";
                model.Type  = ResultType.info;
                break;

            case ResultMessage.ResetPasswordCompleted:
                model.Title = "שחזור סיסמא הושלם";
                model.Text  = "אתה יכול להתחבר לאתר עם הסיסמא החדשה";
                model.Type  = ResultType.success;
                break;

            case ResultMessage.ResetPasswordTokenError:
                model.Title = "הלינק שהשתמשת לא נכון.";
                model.Text  = "אנא כנס ל-  <a href=\"/Account/ResetPassword\"> לאפס את הסיסמה של הדף </ a> כדי לשלוח עוד אחד, או פנה למחלקת תמיכת href=\"/Home/Contact\"> </ a>.";
                model.Type  = ResultType.danger;
                break;

            case ResultMessage.Error:
                model.Title = "שגיאה!";
                model.Text  = "אופס...משהו השתבש";
                model.Type  = ResultType.danger;
                break;

            case ResultMessage.FeedbackSend:
                model.Title = "תודה רבה!";
                model.Text  = "המשוב נשלח.";
                model.Type  = ResultType.success;
                break;

            default:
                model.Title = "הי!";
                model.Text  = "לאט לאט...";
                model.Type  = ResultType.danger;
                break;
            }
            return(View(model));
        }
Beispiel #20
0
        private void ResultViewControl_OnLoaded(object sender, RoutedEventArgs e)
        {
            var resultViewModel = new ResultViewModel();

            ResultViewControl.DataContext = resultViewModel;
        }
        public ResultPage(HttpResponseMessage response)
        {
            InitializeComponent();

            BindingContext = new ResultViewModel(response);
        }
Beispiel #22
0
        public ResultViewModel <UserTrackEditViewModel> Enroll(int TrackID)
        {
            ResultViewModel <UserTrackEditViewModel> result = new ResultViewModel <UserTrackEditViewModel>();

            try
            {
                string Token = Request.Headers.Authorization?
                               .Parameter;
                Dictionary <string, string>
                    cliams = SecurityHelper.Validate(Token);
                int UserID = int.Parse(cliams.First(i => i.Key == "ID").Value);

                if (userTrackService.GetUserTracksCount(UserID) > 2)
                {
                    result.Successed = false;
                    result.Message   = "You exceeded the maximum number of uncomplete tracks ";
                }

                else if (!userTrackService.CheckToEnroll(UserID, TrackID))
                {
                    result.Successed = false;
                    result.Message   = "You Already Enrolled in this Track";
                }

                else

                {
                    UserTrackEditViewModel userTrack = userTrackService.Add(new UserTrackEditViewModel()
                    {
                        ID          = 0,
                        TrackID     = TrackID,
                        UserID      = UserID,
                        Date        = DateTime.Now,
                        FinshDate   = DateTime.Now.AddMonths(1),
                        IsApproveed = false
                    });
                    result.Message   = "Enrollment Request Sent successfully";
                    result.Successed = true;
                    result.Data      = userTrack;

                    var track = trackService.GetByID(TrackID);
                    var user  = userService.GetByID(UserID);

                    var returnedData = new
                    {
                        TrackName = track.Name,
                        Date      = DateTime.Now,
                        UserName  = user.Name,
                        UserID    = user.ID
                    };
                    Hub.Clients.All.GetEnrolledTrack(returnedData);
                }
            }
            catch (Exception e)
            {
                result.Successed = false;
                result.Message   = "Error";
            }

            return(result);
        }
Beispiel #23
0
        public ActionResult Result(ResultViewModel viewModel, FormCollection formCollection)
        {
            _tResultRepository.DbContext.BeginTransaction();
            TResult result = _tResultRepository.GetResultByDate(viewModel.ResultDate.Value);

            if (result != null)
            {
                _tResultRepository.Delete(result);
            }

            result = new TResult();
            result.SetAssignedIdTo(Guid.NewGuid().ToString());
            result.ResultDate  = viewModel.ResultDate;
            result.CreatedDate = DateTime.Now;
            result.CreatedBy   = User.Identity.Name;
            result.DataStatus  = EnumDataStatus.New.ToString();
            result.ResultDets.Clear();
            _tResultRepository.Save(result);

            //get prize for D2 and D3 games
            char[] prizeD1 = viewModel.prizeD4_1.ToCharArray();
            string prizeD2 = viewModel.prizeD4_1.Substring(2, 2);
            string prizeD3 = viewModel.prizeD4_1.Substring(1, 3);

            //save details
            string strprizeD1 = string.Empty, formatWing = string.Empty;

            for (int i = 0; i < prizeD1.Length; i++)
            {
                strprizeD1 = prizeD1[i].ToString();
                //calculate D1
                SaveResultDet(result, EnumGame.D1, i + 1, strprizeD1);

                //calculate wing
                switch (i)
                {
                case 0:
                    formatWing = "{0}xxx";
                    break;

                case 1:
                    formatWing = "x{0}xx";
                    break;

                case 2:
                    formatWing = "xx{0}x";
                    break;

                case 3:
                    formatWing = "xxx{0}";
                    break;
                }
                SaveResultDet(result, EnumGame.WING, i + 1, string.Format(formatWing, strprizeD1));
            }

            //calculate prize for paket
            char[]         indexPrizePaket = ("0123").ToCharArray();
            IList <string> indexResultPaket = indexPrizePaket.AllPermutationsNotDistinct().Where(x => x.Length == 2).ToList();

            char[] prizePaket;
            for (int i = 0; i < indexResultPaket.Count; i++)
            {
                prizePaket = indexResultPaket[i].ToCharArray();
                SaveResultDet(result, EnumGame.PAKET, i + 1, string.Format("{0}/{1}", prizeD1[int.Parse(prizePaket[0].ToString())], prizeD1[int.Parse(prizePaket[1].ToString())]));
            }

            //calculate prize for MK
            char[] prizeMK;
            for (int i = 0; i < indexResultPaket.Count; i++)
            {
                prizeMK = indexResultPaket[i].ToCharArray();
                SaveResultDet(result, EnumGame.MK, i + 1, string.Format("{0}/{1}", prizeD1[int.Parse(prizeMK[0].ToString())], prizeD1[int.Parse(prizeMK[1].ToString())]));
            }

            //calculate prize for DTB
            string prizeD = viewModel.prizeD4_1.Substring(0, 2);
            string prizeT = viewModel.prizeD4_1.Substring(1, 2);
            string prizeB = viewModel.prizeD4_1.Substring(2, 2);

            SaveResultDet(result, EnumGame.D, 1, prizeD);
            SaveResultDet(result, EnumGame.T, 1, prizeT);
            SaveResultDet(result, EnumGame.B, 1, prizeB);

            //calculate prize for BK besar dan kecil
            SaveResultDet(result, EnumGame.BK_B, 101, viewModel.prizeD4_1);
            SaveResultDet(result, EnumGame.BK_B, 201, viewModel.prizeD4_2);
            SaveResultDet(result, EnumGame.BK_B, 301, viewModel.prizeD4_3);
            SaveResultDet(result, EnumGame.BK_K, 101, viewModel.prizeD4_1);
            SaveResultDet(result, EnumGame.BK_K, 201, viewModel.prizeD4_2);
            SaveResultDet(result, EnumGame.BK_K, 301, viewModel.prizeD4_3);

            SaveResultDet(result, EnumGame.D2, 1, prizeD2);
            SaveResultDet(result, EnumGame.D3, 1, prizeD3);
            SaveResultDet(result, EnumGame.D4TH, 1, viewModel.prizeD4_1);
            SaveResultDet(result, EnumGame.D4, 101, viewModel.prizeD4_1);
            SaveResultDet(result, EnumGame.D4, 201, viewModel.prizeD4_2);
            SaveResultDet(result, EnumGame.D4, 301, viewModel.prizeD4_3);
            SaveResultDet(result, EnumGame.D4, 401, viewModel.prizeD4_4_1);
            SaveResultDet(result, EnumGame.D4, 402, viewModel.prizeD4_4_2);
            SaveResultDet(result, EnumGame.D4, 403, viewModel.prizeD4_4_3);
            SaveResultDet(result, EnumGame.D4, 404, viewModel.prizeD4_4_4);
            SaveResultDet(result, EnumGame.D4, 405, viewModel.prizeD4_4_5);
            SaveResultDet(result, EnumGame.D4, 406, viewModel.prizeD4_4_6);
            SaveResultDet(result, EnumGame.D4, 407, viewModel.prizeD4_4_7);
            SaveResultDet(result, EnumGame.D4, 408, viewModel.prizeD4_4_8);
            SaveResultDet(result, EnumGame.D4, 409, viewModel.prizeD4_4_9);
            SaveResultDet(result, EnumGame.D4, 410, viewModel.prizeD4_4_10);

            SaveResultDet(result, EnumGame.D4, 501, viewModel.prizeD4_5_1);
            SaveResultDet(result, EnumGame.D4, 502, viewModel.prizeD4_5_2);
            SaveResultDet(result, EnumGame.D4, 503, viewModel.prizeD4_5_3);
            SaveResultDet(result, EnumGame.D4, 504, viewModel.prizeD4_5_4);
            SaveResultDet(result, EnumGame.D4, 505, viewModel.prizeD4_5_5);
            SaveResultDet(result, EnumGame.D4, 506, viewModel.prizeD4_5_6);
            SaveResultDet(result, EnumGame.D4, 507, viewModel.prizeD4_5_7);
            SaveResultDet(result, EnumGame.D4, 508, viewModel.prizeD4_5_8);
            SaveResultDet(result, EnumGame.D4, 509, viewModel.prizeD4_5_9);
            SaveResultDet(result, EnumGame.D4, 510, viewModel.prizeD4_5_10);

            bool   Success = true;
            string Message = string.Empty;

            try
            {
                _tResultRepository.DbContext.CommitTransaction();
                TempData[EnumCommonViewData.SaveState.ToString()] = EnumSaveState.Success;
                Success = true;
                Message = "Nomor keluar berhasil disimpan.";
            }
            catch (Exception ex)
            {
                _tResultRepository.DbContext.RollbackTransaction();
                TempData[EnumCommonViewData.SaveState.ToString()] = EnumSaveState.Failed;
                Success = false;
                Message = ex.GetBaseException().Message;
            }

            var e = new
            {
                Success,
                Message
            };

            return(Json(e, JsonRequestBehavior.AllowGet));
        }
Beispiel #24
0
        public IActionResult Result(ResultViewModel resultViewModel)

        {
            if (ModelState.IsValid)
            {
                if ((resultViewModel.Bmonth == 1 & resultViewModel.Bday >= 21) || (resultViewModel.Bmonth == 2 & resultViewModel.Bday < 20))
                {
                    resultViewModel.Sign         = "Aquarius";
                    resultViewModel.Englishtrans = "The Water-Bearer";
                    resultViewModel.Imageplace   = "/images/Aquarius.png";
                    resultViewModel.Desc         = "Aquarius seem a bit of an odd-person out. They tend to quietly go about accomplishing their goals, often in unconventional ways. They are both eccentric and humane. They can tend towards laziness if they lose their sense of motivation.";
                    resultViewModel.Dates        = "January 20- February 18";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 2 & resultViewModel.Bday >= 20) || (resultViewModel.Bmonth == 3 & resultViewModel.Bday < 21))
                {
                    resultViewModel.Sign         = "Pisces";
                    resultViewModel.Englishtrans = "The Fish";
                    resultViewModel.Imageplace   = "/images/Pisces.png";
                    resultViewModel.Desc         = "Pisces are dreamers and mystics. They are often quiet, so it is hard to tell, but they have vivid internal lives. They are honest, compassionate and trustworthy. They can also be gullible and easily taken advantage of. Their determination helps them to succeed when it comes to goals.";
                    resultViewModel.Dates        = "February 19- March 20";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 3 & resultViewModel.Bday >= 21) || (resultViewModel.Bmonth == 4 & resultViewModel.Bday < 21))
                {
                    resultViewModel.Sign         = "Aries";
                    resultViewModel.Englishtrans = "The Ram";
                    resultViewModel.Imageplace   = "/images/Aries.png";
                    resultViewModel.Desc         = "Aries tend to love challenges. They are full of energy and zeal. They are both curious and driven, love to compete, and have a strong sense of justice. Aries are natural leaders.";
                    resultViewModel.Dates        = "March 21- April 19";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 4 & resultViewModel.Bday >= 21) || (resultViewModel.Bmonth == 5 & resultViewModel.Bday < 22))
                {
                    resultViewModel.Sign         = "Taurus";
                    resultViewModel.Englishtrans = "The Bull";
                    resultViewModel.Imageplace   = "/images/Taurus.png";
                    resultViewModel.Desc         = "Taurus are reliable, dedicated, committed people. They value security and stability. They bring order to the world. They can also be somewhat stubborn, disliking change.";
                    resultViewModel.Dates        = "April 20- May 20";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 5 & resultViewModel.Bday >= 22) || (resultViewModel.Bmonth == 6 & resultViewModel.Bday < 22))
                {
                    resultViewModel.Sign         = "Gemini";
                    resultViewModel.Englishtrans = "The Twins";
                    resultViewModel.Imageplace   = "/images/Gemini.png";
                    resultViewModel.Desc         = "Gemini love to socialize and to spend time with people. They like to communicate ideas and to share feelings. They enjoy what some might call idle chatter. Their love of small talk may make them seem nervous to some.";
                    resultViewModel.Dates        = "May 21- June 20";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 6 & resultViewModel.Bday >= 22) || (resultViewModel.Bmonth == 7 & resultViewModel.Bday < 23))
                {
                    resultViewModel.Sign         = "Cancer";
                    resultViewModel.Englishtrans = "The Crab";
                    resultViewModel.Imageplace   = "/images/Cancer.png";
                    resultViewModel.Desc         = "Cancers need to be needed, they need to feel loved. They have a strong sense of home and safety. They area also good at creating home-like environments for others.";
                    resultViewModel.Dates        = "June 21- July 22";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 7 & resultViewModel.Bday >= 23) || (resultViewModel.Bmonth == 8 & resultViewModel.Bday < 23))
                {
                    resultViewModel.Sign         = "Leo";
                    resultViewModel.Englishtrans = "The Lion";
                    resultViewModel.Imageplace   = "/images/Leo.png";
                    resultViewModel.Desc         = "Leos have a regal bearing. They bring light and love to others. Their friends and followers adore them. They are used to being the center of attention. They are often happy and pleasing to be around.";
                    resultViewModel.Dates        = "July 23- August 22";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 8 & resultViewModel.Bday >= 23) || (resultViewModel.Bmonth == 9 & resultViewModel.Bday < 24))
                {
                    resultViewModel.Sign         = "Virgo";
                    resultViewModel.Englishtrans = "The Maiden";
                    resultViewModel.Imageplace   = "/images/Virgo.png";
                    resultViewModel.Desc         = "Virgo are capable, organized, and analytical. They are curious people and good storytellers. They have gifts for research, memory and intuition. They are great collaborators, in spite of their tendency to occasionally seem critical.";
                    resultViewModel.Dates        = "August 23- September 22";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 9 & resultViewModel.Bday >= 24) || (resultViewModel.Bmonth == 10 & resultViewModel.Bday < 24))
                {
                    resultViewModel.Sign         = "Libra";
                    resultViewModel.Englishtrans = "The Scales";
                    resultViewModel.Imageplace   = "/images/Libra.png";
                    resultViewModel.Desc         = "A Libra desires justice, and is satisfied only when the scales are balanced. Sometimes they will go to extremes to pursue this goal, which can be unsafe. They are great defenders of the innocent and downtrodden. They love a good debate, in spite of having an introverted side.";
                    resultViewModel.Dates        = "September 23- October 22";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 10 & resultViewModel.Bday >= 24) || (resultViewModel.Bmonth == 11 & resultViewModel.Bday < 23))
                {
                    resultViewModel.Sign         = "Scorpio";
                    resultViewModel.Englishtrans = "The Scorpion";
                    resultViewModel.Imageplace   = "/images/Scorpio.png";
                    resultViewModel.Desc         = "Scorpio are bold, intense and often misunderstood. They have great abilties to complete massive projects, and are quite impassioned beneath their cool exteriors. They can surmount almost any obstacle with their unshakable focus. Sometimes they are mistrusted due to seeming secretive during calculations.";
                    resultViewModel.Dates        = "October 23- November 21";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 11 & resultViewModel.Bday >= 23) || (resultViewModel.Bmonth == 12 & resultViewModel.Bday < 21))
                {
                    resultViewModel.Sign         = "Saggitarius";
                    resultViewModel.Englishtrans = "The Archer";
                    resultViewModel.Imageplace   = "/images/Saggitarius.png";
                    resultViewModel.Desc         = "Saggitarius are wandering philosophers. They can have great focus, but also tend to move about, gathering thoughts and information. They can tend to go in too many directions for their own good. They are often hasty, lacking patience, and make good, if not committed, friends.";
                    resultViewModel.Dates        = "November 22- December 21";

                    return(View(resultViewModel));
                }


                if ((resultViewModel.Bmonth == 12 & resultViewModel.Bday >= 21) || (resultViewModel.Bmonth == 1 & resultViewModel.Bday < 21))
                {
                    resultViewModel.Sign         = "Capricorn";
                    resultViewModel.Englishtrans = "The Sea-Goat";
                    resultViewModel.Imageplace   = "/images/Capricorn.png";
                    resultViewModel.Desc         = "Capricorn enjoy applying their intellect to problems. They like stability. They have a sharp intuition, though they may seem secretive at times. They are responsible people, but can have trouble sharing their burdens with others, being inexpert at communicating.";
                    resultViewModel.Dates        = "December 22- January 19";

                    return(View(resultViewModel));
                }



                return(Redirect("/Home/Error"));
            }


            return(Redirect("/Home/Error"));
        }
        public ActionResult Index(FormCollection form)
        {
            ViewBag.Message = "Results page.";
            //Variables assigned values based on user values entered in the form (# of people, Budget, and Cuisine Type)
            Request dataRequest = new Request();

            dataRequest.numPeople   = int.Parse(form["numPeople"]);
            dataRequest.Budget      = int.Parse(form["Budget"]);
            dataRequest.CuisineType = form["foodDropdown"];
            dataRequest.Category    = form["categoryDropdown"];
            dataRequest.Zipcode     = form["Zipcode"];


            //'price' variable is assigned to 1,2,3, 4, or 5 . This value is created by methods in the QueryHelper class
            string price = QueryHelper.RestaurantPrice(dataRequest.Budget, dataRequest.numPeople);

            //New FactualDriver object being created using the variable names previously assigned to keys
            Factual Factual = new Factual(OATHKEY, OATHSECRET);
            string  data    = null;

            try
            {
                data = Factual.Fetch("restaurants",
                                     new Query()
                                     .Field("price")
                                     .Equal(price)
                                     .Field("cuisine")
                                     .Equal(dataRequest.CuisineType.ToLower())
                                     .Field("postcode")
                                     .Equal(dataRequest.Zipcode)
                                     .Offset(0)
                                     .Limit(20));
            }
            catch
            {
                data = "{Error: 'Please try again'}";
            }

            var jData = JObject.Parse(data);                         //'data' is being Parsed from string to JObject type

            List <Restaurant> restaurants = new List <Restaurant>(); //Initializing a new list of resaurants

            //Each item in 'restaurants' list is initialized as a new 'restaurant'

            if (jData["Error"] == null)
            {
                foreach (var gcVar in jData["response"]["data"].ToList())
                {
                    Restaurant restaurant = new Restaurant();
                    dynamic    restVar    = JObject.Parse(gcVar.ToString());
                    //'restVar' is created and holds the properties of a Resaurant object (these properties are from the Restaurant class: name, address, etc...)

                    //'timeString' variable assigned value based on day of the week
                    //Used for finding hours of operation for restaurants for the current day of the week

                    string timeString = System.DateTime.Now.DayOfWeek.ToString().ToLower();

                    if (restVar["hours"] != null)
                    {
                        var hours = restVar["hours"][timeString];
                        if (hours != null)
                        {
                            restaurant.Hours = hours.ToString();
                        }
                    }
                    //The new Restaurant object named 'restaurant' has its properties assigned values. These values are taken from the 'restVar' variable
                    restaurant.Name       = restVar.name;
                    restaurant.PriceRange = (PriceRange)restVar.price;
                    //'PriceRange' is an enum found in the Restaurant class
                    restaurant.Address = restVar.address;
                    restaurant.ZipCode = restVar.postcode;
                    restaurant.Website = restVar.website;

                    restaurant.CuisineTypes = new List <string>();
                    //Many restaurants serve multiple cuisine types so a list is created to display these types
                    foreach (var cuisineVar in restVar.cuisine)
                    {
                        restaurant.CuisineTypes.Add(cuisineVar.ToString());
                        //The foreach loop iterates through the multiple types and adds them to the 'restaurant.CuisineTypes' list
                    }

                    restaurant.Description = new List <string>();
                    //Just like the CuisineTypes list foreach loop, but for restaurant description
                    foreach (var desVar in restVar.category_labels)
                    {
                        restaurant.Description.Add(desVar.ToString());
                    }

                    restaurant.Id = restaurants.Count;
                    restaurants.Add(restaurant);
                    //Now the 'restaurant' is added to the list named 'restaurants' and the foreach loop repeats this process
                }
            }

            string activityCategory = form["categoryDropdown"];
            string zipcode          = form["Zipcode"];
            string qString          = TMQueryString(zipcode, activityCategory, "10");

            List <Activity> activities   = new List <Activity>();
            List <Activity> tempActivity = ActivitiesRequest(qString);


            foreach (Activity activity in tempActivity)
            {
                if (activity.PricePerPerson != null)
                {
                    if (decimal.Parse(activity.PricePerPerson) <= (((decimal)dataRequest.Budget / 2) / (decimal)dataRequest.numPeople))
                    {
                        activities.Add(activity);
                    }
                }
                else
                {
                    activities.Add(activity);
                }
            }

            if (zipcode.Substring(0, 3) == "495")
            {
                using (DBActivity db = new DBActivity())
                {
                    foreach (var activity in db.Activities)
                    {
                        if (activity.DaysOpen != null && !string.IsNullOrWhiteSpace(activity.PricePerPerson))
                        {
                            if (double.Parse(activity.PricePerPerson) <=
                                (dataRequest.Budget * .5 / dataRequest.numPeople))
                            {
                                Activity newActivity = new Activity();

                                newActivity.Category       = activity.Category;
                                newActivity.City           = activity.City;
                                newActivity.DaysOpen       = activity.DaysOpen;
                                newActivity.Id             = activity.Id;
                                newActivity.Link           = activity.Link;
                                newActivity.PhoneNumber    = activity.PhoneNumber;
                                newActivity.PricePerPerson = activity.PricePerPerson;
                                newActivity.State          = activity.State;
                                newActivity.StreetAddress  = activity.StreetAddress;
                                newActivity.TimesOpen      = activity.TimesOpen;
                                newActivity.Venue          = activity.Venue;
                                newActivity.Zip            = activity.Zip;

                                decimal activityBudget = (((decimal)dataRequest.Budget / 2) / (decimal)dataRequest.numPeople);
                                if (decimal.Parse(newActivity.PricePerPerson) <= activityBudget)
                                {
                                    activities.Add(newActivity);
                                }
                            }
                        }
                    }
                }
            }


            ResultViewModel result = new ResultViewModel();

            result.Restuarants = restaurants;
            result.SetRandomRestaurant();

            result.Activities = activities;
            result.SetRandomActivity();


            return(View("ResultTemp", result));
        }
        public async Task <IActionResult> PostToken([FromBody] UserViewModel usrvm)
        {
            if (usrvm == null)
            {
                return(new StatusCodeResult(500));
            }
            else
            {
                var resultModel = new ResultViewModel();
                try
                {
                    var user = await this.UserManager.FindByNameAsync(usrvm.UserName) ??
                               await this.UserManager.FindByEmailAsync(usrvm.UserName);

                    var isExist = user != null;
                    if (isExist)
                    {
                        resultModel.IsSuccess = false; resultModel.Message = "已存在此账号";
                    }
                    else
                    {
                        var CreateDate = DateTime.Now;
                        user = new ApplicationUser()
                        {
                            UserName         = usrvm.UserName,
                            PasswordHash     = usrvm.UserPwd,
                            CreateDate       = CreateDate,
                            LastModifiedDate = CreateDate,
                            EmailConfirmed   = false,
                            LockoutEnabled   = false,
                        };

                        var result = await this.UserManager.CreateAsync(user, usrvm.UserPwd);

                        while (true)
                        {
                            if (result.Succeeded)
                            {
                                result = await this.UserManager.AddToRoleAsync(user, "Registered");

                                if (result.Succeeded)
                                {
                                    var    jwt       = _tokenHelper.CreateJWTToken(user.Id);
                                    string tokenJson = JsonConvert.SerializeObject(jwt);
                                    resultModel.IsSuccess = true;
                                    resultModel.Token     = tokenJson;
                                    break;
                                }
                            }
                            resultModel.IsSuccess = false;
                            resultModel.Message   = result.Errors.FirstOrDefault().Description;
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    resultModel.IsSuccess = false;
                    resultModel.Message   = e.Message;
                }
                return(this.Json(resultModel, DefaultJsonSettings));
            }
        }
Beispiel #27
0
 public Result Convert(ResultViewModel viewModel)
 {
     return(_mapper.Map <Result>(viewModel));
 }
Beispiel #28
0
 public ResultsView(ResultViewModel aVM)
 {
     InitializeComponent();
     DataContext = aVM;
 }
 public IActionResult Put(ResultViewModel m)
 {
     throw new NotImplementedException();
 }
        public void CheckQueryNeededToBeSaved(CloseableTabItem tabItem, String caller)
        {
            /*****************To Save Modified Query***********/

            string directoryPath = this.result.directoryPath;

            MainWindow mainWindow = (MainWindow)GetTopLevelControl(this.ShortCutsToolBar);
            mainWindow.ValidateAllTabCntrls(this);
            SelectQueryBuilder queryBuilder = mainWindow.LoadSelectQueryBuilderNew(this);

            MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
            this.result = mainGridView1.result;
            if (directoryPath != null)
            {
                this.result.isModified = true;
                this.result.isNew = false;
                this.result.directoryPath = directoryPath;
            }
            else
            {
                this.result.isModified = true;
                this.result.isNew = true;
            }

            /********************************************/

            ResultViewModel rv = (ResultViewModel)this.result;   

            if (this.Content != null)
            {
                if (rv.isModified)
                {
                    if (rv.isNew == false)
                    {
                        switch (caller)
                        {
                            case "Save":

                                string FileName = rv.directoryPath + tabItem.Header.ToString() + ".xml";
                                if (FileName != System.String.Empty)
                                {
                                    XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                    StreamWriter swriter = new StreamWriter(FileName);
                                    SerializerObj.Serialize(swriter, rv.QueryBulder);

                                    swriter.Flush();
                                    swriter.Close();
                                    tabItem.Header = tabItem.Header.ToString();
                                    //we saved the query change isModified to false
                                    rv.isModified = false;
                                    tabItem.labelStar.Content = "";
                                    MessageBox.Show("query saved successfully");
                                }
                                break;

                            case "SaveAs":

                                MainWindow mw = new MainWindow();
                                string FileName1 = mw.OpenSaveDialog(tabItem.Name);

                                if (FileName1 != System.String.Empty)
                                {
                                    XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                    StreamWriter swriter = new StreamWriter(FileName1);
                                    SerializerObj.Serialize(swriter, rv.QueryBulder);

                                    swriter.Flush();
                                    swriter.Close();
                                    string[] splitedArray = FileName1.Split('\\');
                                    string tabItemHeader = splitedArray[splitedArray.Length - 1].Remove((splitedArray[splitedArray.Length - 1]).Length - 4, 4);
                                    tabItem.Header = tabItemHeader;
                                    //we saved the query change isModified to false
                                    rv.isModified = false;
                                    tabItem.labelStar.Content = "";
                                    MessageBox.Show("query saved successfully");
                                }
                                break;

                            case "SaveXML":

                                FileName = ConfigurationManager.AppSettings["DerivedTablesPath"].ToString() + flName + ".xml";
                                if (File.Exists(FileName))
                                {
                                    MessageBox.Show("File already exists....");
                                }
                                else
                                {
                                    if (FileName != System.String.Empty)
                                    {
                                        XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                        StreamWriter swriter = new StreamWriter(FileName);
                                        SerializerObj.Serialize(swriter, rv.QueryBulder);

                                        swriter.Flush();
                                        swriter.Close();
                                        tabItem.Header = tabItem.Header.ToString();

                                        rv.isModified = false;
                                        tabItem.labelStar.Content = "";
                                        MessageBox.Show("query saved successfully");

                                        connectionString = ConfigurationManager.AppSettings["DefaultDBConn"];
                                        CurrentDatabaseName = ConfigurationManager.AppSettings["DefaultDatabase"];

                                        connectionString = connectionString + "Database=" + CurrentDatabaseName + ";";
                                        DependencyObject parent = this.GetTopLevelControl(this);

                                        try
                                        {
                                            List<MySQLData.Schema> schemas = MySQLData.DataAccess.ADODataBridge.getSchemaTree(connectionString, CurrentDatabaseName, ConfigurationManager.AppSettings["DerivedTablesPath"]);//DataAccess.GetDatabases();
                                            MainViewModel viewModel = new MainViewModel(schemas);

                                            if (parent != null)
                                            {
                                                MainWindow m = (MainWindow)parent;
                                                m.MainTreeView.DataContext = viewModel;
                                                listOfTable = new List<MySQLData.Table>();
                                                foreach (MySQLData.Schema schema in schemas)
                                                {
                                                    listOfTable.AddRange(schema.tables);
                                                }
                                                if (listOfTable != null)
                                                {

                                                }
                                            }

                                        }
                                        catch (MySql.Data.MySqlClient.MySqlException ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        if (parent != null)
                                        {
                                            MainWindow m = (MainWindow)parent;
                                            var collView = CollectionViewSource.GetDefaultView(m.tabControlCustomQuery.Items);
                                            collView.CurrentChanging += this.OnTabItemSelecting;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                    else
                    {
                        switch (caller)
                        {
                            case "Save":
                                if (rv.TotalIRows != 0)
                                {
                                    SaveNewQuery(tabItem, rv.QueryBulder);
                                }
                                break;

                            case "SaveAs":

                                if (rv.TotalIRows != 0)
                                {
                                    //save save as the query
                                    MainWindow mw = new MainWindow();
                                    string FileName = mw.OpenSaveDialog(tabItem.Name);

                                    if (FileName != System.String.Empty)
                                    {
                                        XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                        StreamWriter swriter = new StreamWriter(FileName);
                                        SerializerObj.Serialize(swriter, rv.QueryBulder);

                                        swriter.Flush();
                                        swriter.Close();
                                        string[] splitedArray = FileName.Split('\\');
                                        string tabItemHeader = splitedArray[splitedArray.Length - 1].Remove((splitedArray[splitedArray.Length - 1]).Length - 4, 4);
                                        tabItem.Header = tabItemHeader;
                                        //we saved the query change isModified to false
                                        rv.isModified = false;
                                        tabItem.labelStar.Content = "";
                                        MessageBox.Show("query saved successfully");
                                    }
                                }
                                break;

                            case "SaveXML":
                                string FileNameXML = ConfigurationManager.AppSettings["DerivedTablesPath"].ToString() + flName + ".xml";
                                if (File.Exists(FileNameXML))
                                {
                                    MessageBox.Show("File already exists....");
                                }
                                else
                                {
                                    if (FileNameXML != System.String.Empty)
                                    {
                                        XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                        StreamWriter swriter = new StreamWriter(FileNameXML);
                                        SerializerObj.Serialize(swriter, rv.QueryBulder);

                                        swriter.Flush();
                                        swriter.Close();
                                        tabItem.Header = tabItem.Header.ToString();

                                        rv.isModified = false;
                                        tabItem.labelStar.Content = "";
                                        MessageBox.Show("query saved successfully");


                                        connectionString = ConfigurationManager.AppSettings["DefaultDBConn"];
                                        CurrentDatabaseName = ConfigurationManager.AppSettings["DefaultDatabase"];

                                        connectionString = connectionString + "Database=" + CurrentDatabaseName + ";";
                                        DependencyObject parent = this.GetTopLevelControl(this);

                                        try
                                        {
                                            List<MySQLData.Schema> schemas = MySQLData.DataAccess.ADODataBridge.getSchemaTree(connectionString, CurrentDatabaseName, ConfigurationManager.AppSettings["DerivedTablesPath"]);
                                            MainViewModel viewModel = new MainViewModel(schemas);

                                            if (parent != null)
                                            {
                                                MainWindow m = (MainWindow)parent;
                                                m.MainTreeView.DataContext = viewModel;
                                                listOfTable = new List<MySQLData.Table>();
                                                foreach (MySQLData.Schema schema in schemas)
                                                {
                                                    listOfTable.AddRange(schema.tables);
                                                }
                                                if (listOfTable != null)
                                                {
                                                    
                                                }
                                            }

                                        }
                                        catch (MySql.Data.MySqlClient.MySqlException ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        if (parent != null)
                                        {
                                            MainWindow m = (MainWindow)parent;
                                            var collView = CollectionViewSource.GetDefaultView(m.tabControlCustomQuery.Items);
                                            collView.CurrentChanging += this.OnTabItemSelecting;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }
                else
                {
                    switch (caller)
                    {
                        case "Save":
                            break;
                        case "SaveAs":
                            break;
                        case "SaveXML":
                            break;
                        case "CloseTab":
                            TabControl tabControl = tabItem.Parent as TabControl;
                            if (tabControl != null)
                                tabControl.Items.Remove(tabItem);
                            break;
                    }
                }
            }
            else
            {
                if (caller == "CloseTab")
                {
                    TabControl tabControl = tabItem.Parent as TabControl;
                    if (tabControl != null)
                        tabControl.Items.Remove(tabItem);
                }
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="vm"></param>
 public ResultWindow(ResultViewModel vm)
 {
     DataContext = vm;
     InitializeComponent();
 }
        //
        // GET: /Result/

        public ActionResult Index(string keyword)
        {
            // If keyword is null or empty then system will redirect to home page
            if (keyword == null || keyword.Trim().Equals(""))
            {
                return(RedirectToAction("Index", "Home"));
            }

            // Instance model layer
            ResultModel resultModel = new ResultModel();

            // Instance view model for result
            ResultViewModel resultViewModel = new ResultViewModel();

            // Get entry by keyword
            WordIndex entry = resultModel.GetEntryByKeyword(keyword);

            // Property of search history
            bool isExistData = true;

            // Check has entry
            if (entry != null)
            {
                //set view model
                resultViewModel.Entry = entry;

                // List result
                if (entry.Synsets.Where(x => x.Category == "n").Count() > 0)
                {
                    ViewBag.Noun = entry.Synsets.Where(x => x.Category == "n");
                }
                if (entry.Synsets.Where(x => x.Category == "v").Count() > 0)
                {
                    ViewBag.Verb = entry.Synsets.Where(x => x.Category == "v");
                }

                //add history
                isExistData = true;
            }
            else
            {
                isExistData = false;
            }

            //add history
            SearchHistoryModel searchHistoryModel = new SearchHistoryModel();

            searchHistoryModel.AddSearchHistory(keyword, isExistData);

            //add user history
            if (Request.IsAuthenticated)
            {
                UserHistoryModel userHistoryModel = new UserHistoryModel();
                userHistoryModel.AddUserHistory(keyword);
            }


            //---------------------------------------
            // Store 5 recent keywords
            if (Session["Recent"] == null)
            {
                Session["Recent"] = new List <string>();
            }

            int countRecent = ((List <string>)Session["Recent"]).Count;


            if (((List <string>)Session["Recent"]).Contains(keyword))
            {
                ((List <string>)Session["Recent"]).Remove(keyword);
            }
            else if (countRecent >= 5)
            {
                ((List <string>)Session["Recent"]).RemoveAt(0);
            }
            ((List <string>)Session["Recent"]).Add(keyword);

            //((List<string>)Session["Recent"]).Reverse();
            //string[] arraySuggest = new string[((List<string>)Session["Recent"]).Count];
            //((List<string>)Session["Recent"]).CopyTo(arraySuggest);
            //ViewBag.Recent = arraySuggest;
            //((List<string>)Session["Recent"]).Reverse();
            //---------------------------------------

            //ViewBag.Title
            ViewBag.Title = "Kết quả tra cứu cho '" + keyword + "'";

            // add suggest terms
            EntriesModel entryModel = new EntriesModel();

            resultViewModel.SuggestTerm = entryModel.SuggestTerm(keyword);

            // get questions
            QAModel qaModel = new QAModel();

            resultViewModel.Questions = qaModel.GetQuestionPaged(1, 10);

            return(View(resultViewModel));
        }
        private void RunQueryBtn_Click(object sender, RoutedEventArgs e)
        {
            MainWindow mainWindow = (MainWindow)GetTopLevelControl(this.ShortCutsToolBar);
            isAllTabValidated = mainWindow.ValidateAllTabCntrls(this);

            SelectQueryBuilder queryBuilder = mainWindow.LoadSelectQueryBuilderNew(this);
            string queryString;
            if (queryBuilder != null)
            {
                queryString = queryBuilder.BuildQuery();
            }
            XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
            StringWriter writer = new StringWriter();
            SerializerObj.Serialize(writer, queryBuilder);
            DateTime startTime = DateTime.Now;
            TabItem rvctabItem = RVCTAbControl.SelectedItem as TabItem;
            if (XmlSQLTabTxt.Text != null && rvctabItem.Name == "XmlSQLTab")
            {
                try
                {
                    connectionString = ConfigurationManager.AppSettings["DefaultDBConn"];
                    CurrentDatabaseName = ConfigurationManager.AppSettings["DefaultDatabase"];

                    connectionString = connectionString + "Database=" + CurrentDatabaseName + ";";
                    DataTable dataTable = new DataTable();
                    string sqldata = "";
                    dataTable = (MySQLData.DataAccess.ADODataBridge.getData(connectionString, XmlSQLTabTxt.Text));
                    DataView dataView = new DataView(dataTable);
                    ResultViewModel rvm = new ResultViewModel(dataView);
                    MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName, sqldata);

                    CloseableTabItem tabItem = (CloseableTabItem)this.ResultTab;

                    rvm.isModified = true;
                    rvm.isNew = true;

                    mainGridView1.DataContext = rvm;
                    tabItem.Content = mainGridView1;
                    mainGridView1.MainDataGrid.Width = dataTable.Columns.Count * 160;
                    mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

                    this.DataContext = rvm;
                    this.ResultTab.IsSelected = true;
                    lblXmlSQLTabErrorMessage.Visibility = System.Windows.Visibility.Hidden;

                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    if (isErrorLoggingOn)
                    {
                        lblXmlSQLTabErrorMessage.Visibility = System.Windows.Visibility.Visible;
                        lblXmlSQLTabErrorMessage.Height = 20;
                        lblXmlSQLTabErrorMessage.Content = ex.Message;
                        LogError.Log_Err("btnRunQuery_Click", ex);
                    }
                }
                catch (Exception ex)
                {
                    if (isErrorLoggingOn)
                    {
                        LogError.Log_Err("btnRunQuery_Click", ex);
                    }
                }
                Mouse.OverrideCursor = null;
            }
            else if (isAllTabValidated)
            {
                if (mainWindow.queryString != String.Empty)
                {
                    if (queryBuilder != null)
                    {
                        CloseableTabItem tabItem = (CloseableTabItem)this.ResultTab;

                        if (tabItem.Content == null)
                        {
                            Mouse.OverrideCursor = Cursors.Wait;
                            try
                            {
                                if (queryBuilder.CrossTabClause != null)
                                {
                                    if (queryBuilder.CrossTabClause.Col == null)
                                    {
                                        MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                        result = mainGridView1.result;

                                        result.isModified = true;
                                        result.isNew = true;

                                        mainGridView1.DataContext = result;
                                        tabItem.Content = mainGridView1;

                                        mainGridView1.MainDataGrid.Width = result.EndColumn * 160;
                                        mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

                                        this.DataContext = result;
                                        this.ResultTab.IsSelected = true;
                                    }
                                    else
                                    {
                                        if (this.StackPanelResultViewControl.Children.Count == 1)
                                        {
                                            if ((MainGirdViewControl)this.StackPanelResultViewControl.Children[0] != null)
                                            {
                                                this.StackPanelResultViewControl.Children.RemoveAt(0);
                                            }
                                        }
                                        CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                        result = crossTabViewControl.result;
                                        this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
                                    }
                                }
                            }
                            catch (MySql.Data.MySqlClient.MySqlException ex)
                            {
                                if (isErrorLoggingOn)
                                {
                                    LogError.Log_Err("btnRunQuery_Click", ex);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (isErrorLoggingOn)
                                {
                                    LogError.Log_Err("btnRunQuery_Click", ex);
                                }
                            }
                            Mouse.OverrideCursor = null;
                        }
                        else
                        {

                            ResultViewModel rv = (ResultViewModel)this.result;
                            if (rv.isNew)
                            {
                                // we still let user run the query, query still new and modified= true
                                Mouse.OverrideCursor = Cursors.Wait;
                                try
                                {
                                    if (queryBuilder.CrossTabClause != null)
                                    {
                                        if (queryBuilder.CrossTabClause.Col == null)
                                        {
                                            if (queryBuilder.GroupByColumns.Count == 0 && queryBuilder.SelectedColumns.Count == 0)
                                            {
                                                foreach (SQLBuilder.Clauses.Column col in this.SelectTabCntrl.lstToSelecteColFrom.Items)
                                                {
                                                    queryBuilder.SelectColumn(col);
                                                }
                                            }
                                            MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = mainGridView1.result;

                                            result.isModified = true;
                                            result.isNew = true;

                                            mainGridView1.DataContext = result;
                                            tabItem.Content = mainGridView1;

                                            mainGridView1.MainDataGrid.Width = result.EndColumn * 160;
                                            mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                                            CloseableTabItem ti = (CloseableTabItem)mainWindow.tabControl1.SelectedItem;
                                            ti.labelStar.Content = "*";
                                            this.DataContext = result;
                                            this.ResultTab.IsSelected = true;
                                        }
                                        else
                                        {
                                            if (this.StackPanelResultViewControl.Children.Count == 1)
                                            {
                                                if (this.StackPanelResultViewControl.Children[0] != null)
                                                {
                                                    this.StackPanelResultViewControl.Children.RemoveAt(0);
                                                }
                                            }
                                            CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = crossTabViewControl.result;
                                            this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
                                            this.ResultTab.IsSelected = true;
                                        }
                                    }
                                }
                                catch (MySql.Data.MySqlClient.MySqlException ex)
                                {
                                    if (isErrorLoggingOn)
                                    {
                                        LogError.Log_Err("btnRunQuery_Click", ex);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (isErrorLoggingOn)
                                    {
                                        LogError.Log_Err("btnRunQuery_Click", ex);
                                    }
                                }
                                Mouse.OverrideCursor = null;
                            }
                            else
                            {
                                // it is old
                                //check to see if old querybuilder and new querybuilder is same, if different CompairQueryBuilder retuns true
                                if (mainWindow.CompairQueryBuilder(rv.QueryBulder, queryBuilder))
                                {
                                    Mouse.OverrideCursor = Cursors.Wait;
                                    try
                                    {
                                        string directoryPath = String.Empty;
                                        if (result != null)
                                        {
                                            if (result.directoryPath != null)
                                            {
                                                directoryPath = result.directoryPath;
                                            }
                                        }

                                        if (queryBuilder.CrossTabClause != null && queryBuilder.CrossTabClause.Col != null)
                                        {
                                            if (this.StackPanelResultViewControl.Children.Count == 1)
                                            {
                                                if (this.StackPanelResultViewControl.Children[0] != null)
                                                {
                                                    this.StackPanelResultViewControl.Children.RemoveAt(0);
                                                }
                                            }
                                            CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = crossTabViewControl.result;
                                            this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
                                            this.ResultTab.IsSelected = true;
                                            CloseableTabItem ti = (CloseableTabItem)mainWindow.tabControl1.SelectedItem;
                                            ti.labelStar.Content = "*";
                                        }
                                        else
                                        {
                                            MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = mainGridView1.result;
                                            mainGridView1.DataContext = result;
                                            tabItem.Content = mainGridView1;

                                            mainGridView1.MainDataGrid.Width = result.EndColumn * 160;
                                            mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                                            CloseableTabItem ti = (CloseableTabItem)mainWindow.tabControl1.SelectedItem;
                                            ti.labelStar.Content = "*";
                                        }

                                        if (directoryPath != String.Empty)
                                        {
                                            result.directoryPath = directoryPath;
                                        }

                                        result.isModified = true;
                                        result.isNew = false;

                                        this.DataContext = result;
                                        this.ResultTab.IsSelected = true;
                                    }
                                    catch (MySql.Data.MySqlClient.MySqlException ex)
                                    {
                                        if (isErrorLoggingOn)
                                        {
                                            LogError.Log_Err("btnRunQuery_Click", ex);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        if (isErrorLoggingOn)
                                        {
                                            LogError.Log_Err("btnRunQuery_Click", ex);
                                        }
                                    }
                                    Mouse.OverrideCursor = null;
                                }
                                this.ResultTab.IsSelected = true;
                            }
                        }
                    }
                }
                XmlSQLTabTxt.Text = queryBuilder.BuildQuery();
            }
            
            Console.WriteLine("Cross Tabulation View Control execution time: " + (DateTime.Now - startTime));
        }
        public static async Task <ResultViewModel> SaveAndSendNewMessage(SendMessageViewModel model, ServiceGateWayClient gatewayITask, TaskUser user, EnvironmentViewModel environment, List <JoinFileViewModel> newFiles)
        {
            var newFilesTojoin     = MapClJoinFileToJoinFileViewModel.Map(newFiles);
            var existingFilesToAdd = await Task.Run(() => gatewayITask.GetJoinFilesByPermId(model.ExistingFilesToJoin.ToArray()));

            var files = newFilesTojoin.ToList();

            foreach (var existing in existingFilesToAdd)
            {
                var f = existing;
                f.PermIdFileAlreadyArchived = f.PermId;
                files.Add(f);
            }

            var cltaskdocument = new ClTaskDocument
            {
                Task = new ClTask
                {
                    TechnicalId    = model.TaskId,
                    Description    = model.TaskDescription,
                    EmployerNumber = model.EmployerNumber,
                    WorkerNumber   = model.WorkerNumber
                }
            };

            var result = new ResultViewModel
            {
                NoError = true
            };
            //bool isOk = true;
            var task = await Task.Run(() => gatewayITask.SearchDocumentTask(model.TaskId, user.Language, true, MapClRessourcesToRessourcesViewModel.Map(user.RessourcesListWithAccess).ToArray(), long.Parse(user.Id)));

            task.CurrentStatus = model.Status;
            if (task.CurrentStatus != 4)
            {
                task.Task.EffectiveEndDate = DateTime.MinValue;
            }
            switch (model.TypeOfMessage)
            {
            case 1:     //Mail provenant de l'extérieur --> on n'enverra pas de mail de ce type
                break;

            case 2:     // commentaire
                Log.Write("SaveAndSendNewMessage", "Conversation", model.TaskId.ToString(), 3, "debut SaveComment");
                result.NoError = await SaveComment(gatewayITask, user, cltaskdocument, files, model);

                Log.Write("SaveAndSendNewMessage", "Conversation", model.TaskId.ToString(), 3, "fin SaveComment");
                if (result.NoError)
                {
                    result.NoError = await Task.Run(() => gatewayITask.UpdateTaskDocument(task, user.Id, user.CurrentEntityNumber, MapClRessourcesToRessourcesViewModel.Map(user.RessourcesListWithAccess).ToArray(), long.Parse(user.Id)));
                }
                break;

            case 3:     //Mail interne
                result.NoError = await SaveInternMessage(gatewayITask, user, cltaskdocument, files, model);

                if (model.AssignToUser)
                {
                    task.Context = int.Parse(model.InternRecipientId);
                }
                if (result.NoError)
                {
                    result.NoError = await Task.Run(() => gatewayITask.UpdateTaskDocument(task, user.Id, user.CurrentEntityNumber, MapClRessourcesToRessourcesViewModel.Map(user.RessourcesListWithAccess).ToArray(), long.Parse(user.Id)));
                }
                break;

            case 8:
            case 10:     //Mail destiné à l'extérieur
                var filesForEmail = GetFilesForEmail(existingFilesToAdd, newFilesTojoin);
                result = await SaveExternMessage(gatewayITask, user, cltaskdocument, files, filesForEmail, model);

                if (result.NoError && !model.IsDirectEmail)
                {
                    result.NoError = await Task.Run(() => gatewayITask.UpdateTaskDocument(task, user.Id, user.CurrentEntityNumber, MapClRessourcesToRessourcesViewModel.Map(user.RessourcesListWithAccess).ToArray(), long.Parse(user.Id)));
                }
                break;
            }
            return(result);
        }
Beispiel #35
0
        public ResultViewModel SavePerformanceCardDetail(PerformanceCardViewModel Model)
        {
            ResultViewModel error = new ResultViewModel();

            try
            {
                tblPerformanceEntryMaster entryMaster = new tblPerformanceEntryMaster
                {
                    RegistrationNo         = Model.RegNo,
                    ReviewId               = Model.ReviewId,
                    tblPerformanceMasterId = Model.PerformanceMasterId,
                    EnteredDate            = DateTime.Now,
                    EnteredBy              = Model.UserId,
                    BatchId               = Model.BatchId.Value,
                    AddmissionMasterId    = Model.AdmissionId,
                    tblWeeklyReviewMaster = Model.WeeklyTermId > 0 ? Model.WeeklyTermId : (int?)null,
                    Percentage            = Model.Percentage,
                    PerformanceReview     = Model.PerformanceReview
                };
                _context.tblPerformanceEntryMasters.Add(entryMaster);
                foreach (var item in Model.ParameterTypeInfoList)
                {
                    tblPerformanceParameterTypeResultMaster parameterType = new tblPerformanceParameterTypeResultMaster
                    {
                        tblPerformanceEntryMasterId = entryMaster.Id,
                        tblPerformanceMasterId      = item.PerformanceMasterId,
                        ParameterTypeId             = item.ParameterTypeId,
                        EnteredBy   = Model.UserId,
                        EnteredDate = DateTime.Now
                    };
                    _context.tblPerformanceParameterTypeResultMasters.Add(parameterType);
                    if (item.IsApplicable)
                    {
                        foreach (var obj in item.ParameterInfoList)
                        {
                            tblPerformanceParameterResultMaster parameter = new tblPerformanceParameterResultMaster
                            {
                                Rating  = obj.Rating,
                                Remarks = obj.Remarks,
                                tblPerformanceParameterTypeResultMasterId = parameterType.Id,
                                tblParameterId  = obj.TblParameterId,
                                EnteredBy       = Model.UserId,
                                EnteredDate     = DateTime.Now,
                                IsNotApplicable = false
                            };
                            _context.tblPerformanceParameterResultMasters.Add(parameter);
                        }
                    }
                    else
                    {
                        tblPerformanceParameterResultMaster parameter = new tblPerformanceParameterResultMaster
                        {
                            Rating = 0,
                            tblPerformanceParameterTypeResultMasterId = parameterType.Id,
                            tblParameterId  = item.PtId,
                            EnteredBy       = Model.UserId,
                            EnteredDate     = DateTime.Now,
                            IsNotApplicable = true
                        };
                        _context.tblPerformanceParameterResultMasters.Add(parameter);
                    }
                    _context.SaveChanges();
                    Model.tblPerformanceEntryMasterId = entryMaster.Id;
                }
                error.IsSuccess = true;
                error.Massage   = "Candidate performance card detail saved successfully!";
                return(error);
            }
            catch (Exception ex)
            {
                error.IsSuccess = false;
                error.Massage   = ex.Message + " " + ex.InnerException;
                return(error);
            }
        }
Beispiel #36
0
        public void DistributeIdioctoniaAmount(HttpContext context)
        {
            string json            = "";
            var    resultViewModel = new ResultViewModel();
            var    model           = new DistributionSetEntity();
            var    uIDArray        = Common.GetRequest("uIDArray");
            var    st  = new State();
            long   DID = 0;

            if (uIDArray != null && uIDArray != "")
            {
                var  sArray = JsonConvert.DeserializeObject <string[]>(uIDArray);
                bool result = false;
                for (int i = 0; i < sArray.Length; i++)
                {
                    var RandomValue     = 0;
                    var starttime       = DateTime.Now;
                    var endtime         = DateTime.Now;
                    var notice          = 1;
                    var TestType        = "1";
                    var Retest          = 0;
                    var LookR           = 0;
                    var answerStartTime = DateTime.Now;
                    var answerEndTime   = DateTime.Now.AddDays(14);
                    model._answerstarttime = answerStartTime;
                    model._answerendtime   = answerEndTime;
                    RandomValue            = 0;

                    if (notice == 1)//0是不发送,3是全是发送,1是站内信,2是邮件
                    {
                        Write(sArray[i], "", "您有一个新的测评", 3, Convert.ToInt32(context.Session["UserID"]));
                    }
                    //else if (notice == 2)
                    //{
                    //    RemindByEmail(uIDArray, "您有一个新测评");
                    //}
                    //else if (notice == 3)
                    //{
                    //    Write(uIDArray, "", "您有一个新测评", 3, Convert.ToInt32(context.Session["UserID"]));
                    //    RemindByEmail(uIDArray, "您有一个新测评");
                    //}

                    model._distributionname = TestType;
                    model._is_again         = Retest;
                    model._u_id             = Convert.ToInt32(context.Session["UserID"]);
                    model._is_notice        = notice;
                    model._is_seereport     = LookR;
                    model._is_notice        = notice;
                    DID = MgrServices.DistributeRecordService.InsertDistributionSet(model);
                    model._is_present  = RandomValue;
                    model._sendcontent = "";
                    result             = true;
                }
                int IntDID = 0;
                IntDID = Convert.ToInt32(DID);
                //关系表添加
                string amode = "";
                st.Sucess = 0;
                amode     = Common.GetRequest("AmountCode");
                //amode = amode.Substring(0, amode.Length - 1);
                string[]      sArrays = amode.Split(',');
                List <string> ACode   = sArrays.ToList();
                List <string> UserA   = sArray.ToList();
                var           list    = MgrServices.DistributeRecordService.BulkInsert(ACode, UserA, IntDID, Convert.ToInt32(context.Session["UserID"]));
                st.Fail               = list.Fail;
                st.Sucess             = list.Sucess;
                resultViewModel.State = result;
                context.Response.Write(JsonConvert.SerializeObject(resultViewModel));
            }

            else
            {
                resultViewModel.State = false;
                resultViewModel.Data  = "分配失败,未知原因";
                context.Response.Write(JsonConvert.SerializeObject(resultViewModel));
            }
        }
Beispiel #37
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Startup"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs"/> that contains the event data.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
            FrameworkElement.LanguageProperty.OverrideMetadata(
                typeof(FrameworkElement),
                new FrameworkPropertyMetadata(System.Windows.Markup.XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            Thread.CurrentThread.Name = "MainThread";

            base.OnStartup(e);

            // Init logger
            log4net.Config.XmlConfigurator.Configure();

            // Register handler for unhandled exceptions
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(this.App_DispatcherUnhandledException);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.CurrentDomain_UnhandledException);

            // Build
            var mainViewModel = new MainViewModel();

            this.startViewModel = new StartViewModel();
            var scanViewModel               = new ScanViewModel();
            var previewViewModel            = new PreviewViewModel();
            var previewNoFilesViewModel     = new PreviewNoFilesViewModel();
            var synchronizeViewModel        = new SynchronizeViewModel();
            var synchronizeNoFilesViewModel = new SynchronizeNoFilesViewModel();
            var resultViewModel             = new ResultViewModel();

            var synchronizer = new Synchronizer(new FileLogger());

            var startAction              = new StartAction();
            var scanAction               = new ScanAction(synchronizer);
            var previewAction            = new PreviewAction();
            var previewNoFilesAction     = new PreviewNoFilesAction();
            var synchronizeNoFilesAction = new SynchronizeNoFilesAction();
            var synchronizeAction        = new SynchronizeAction(synchronizer);
            var resultAction             = new ResultAction();

            var mainWindow = new MainWindow();

            // Bind
            startAction.Synchronize += scanAction.Process;

            scanAction.Preview        += previewAction.Process;
            scanAction.PreviewNoFiles += previewNoFilesAction.Process;
            scanAction.Canceled       += startAction.Process;

            previewAction.Synchronize        += synchronizeAction.Process;
            previewAction.SynchronizeNoFiles += synchronizeNoFilesAction.Process;
            previewAction.Canceled           += startAction.Process;

            previewNoFilesAction.Ok += startAction.Process;

            synchronizeAction.Result += resultAction.Process;

            synchronizeNoFilesAction.Ok += startAction.Process;

            resultAction.Ok += startAction.Process;

            // Inject
            startAction.Inject(mainViewModel);
            startAction.Inject(this.startViewModel);
            scanAction.Inject(mainViewModel);
            scanAction.Inject(scanViewModel);
            previewAction.Inject(mainViewModel);
            previewAction.Inject(previewViewModel);
            previewNoFilesAction.Inject(mainViewModel);
            previewNoFilesAction.Inject(previewNoFilesViewModel);
            synchronizeNoFilesAction.Inject(mainViewModel);
            synchronizeNoFilesAction.Inject(synchronizeNoFilesViewModel);
            synchronizeAction.Inject(mainViewModel);
            synchronizeAction.Inject(synchronizeViewModel);
            resultAction.Inject(mainViewModel);
            resultAction.Inject(this.startViewModel);
            resultAction.Inject(resultViewModel);

            mainWindow.Inject(mainViewModel);

            // Run
            this.startViewModel.LoadDefaultJobList();

            this.MainWindow = mainWindow;
            startAction.Process();
            this.MainWindow.Show();
        }
        /// <summary>
        /// Configuration Services Cookie Authentication Jwt format.
        /// </summary>
        /// <param name="services">The services conllection.</param>
        /// <param name="Configuration">The configuration.</param>
        public static void ConfigureCookieAuthen(this IServiceCollection services, IConfiguration Configuration)
        {
            var option = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ClockSkew        = System.TimeSpan.Zero,
                ValidIssuer      = Configuration["Jwt:Issuer"],
                ValidAudience    = Configuration["Jwt:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };

            services.AddAuthentication(opt =>
            {
                opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.Cookie.Name              = "access_token";
                options.SlidingExpiration        = true;
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                    var model = new ResultViewModel
                    {
                        IsError    = true,
                        StatusCode = context.Response.StatusCode,
                        Message    = $"{MessageValue.Unauthorized}"
                    };
                    string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    });
                    context.Response.OnStarting(async() =>
                    {
                        context.Response.ContentType = ConstantValue.ContentTypeJson;
                        await context.Response.WriteAsync(json);
                    });
                    return(System.Threading.Tasks.Task.CompletedTask);
                };
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
                    var model = new ResultViewModel
                    {
                        IsError    = true,
                        StatusCode = context.Response.StatusCode,
                        Message    = $"{MessageValue.UserRoleIsEmpty}"
                    };
                    string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    });
                    context.Response.OnStarting(async() =>
                    {
                        context.Response.ContentType = ConstantValue.ContentTypeJson;
                        await context.Response.WriteAsync(json);
                    });
                    return(System.Threading.Tasks.Task.CompletedTask);
                };
                options.TicketDataFormat = new CookieAuthenticateFormat(SecurityAlgorithms.HmacSha256, option);
            })
            .AddScheme <AuthenticationSchemeOptions, BasicAuthenticationHandler>(ConstantValue.BasicAuthentication, null);
        }
        public MainGirdViewControl(SQLBuilder.SelectQueryBuilder QuerryBuilder, string CurrentDatabaseName, string sqldata)
        {
            this.dbColumnQuerryBuilder = QuerryBuilder;
            InitializeComponent();
            result = new ResultViewModel(QuerryBuilder, CurrentDatabaseName);
            if (result != null)
            {

                this.DataContext = result;
                if (result.QueryBulder != null)
                {
                    if (result.QueryBulder.SelectedTables.Count != 0)
                    {
                        _tableName = result.QueryBulder.SelectedTables[0].Name;
                    }
                }
                //ShowControl();

                //CurrenPage = CurrenPage + 1;
                //this.lblPageNumber.Content = "Page " + CurrenPage.ToString() + " Of " + rowToatlPage.ToString();


                //rowToatlPage = getnumberOfPages(result.TotalIRows, result.rowPageSize);
                //columnToatlPage = getnumberOfPages(result.TotalColumns, result.columnPageSize);

                //if (rowToatlPage > 0)
                //{
                //    RowCurrenPage = 1;
                //    getPageInfo(RowCurrenPage, result.rowPageSize, result.TotalIRows, out startRow, out EndCurrentPageRow);
                //    this.lblRowNumber.Content = "Row " + startRow.ToString() + " - " + EndCurrentPageRow.ToString() + " Of " + result.TotalIRows.ToString();
                //    this.lblPageNumber.Content = "Page " + RowCurrenPage.ToString() + " Of " + rowToatlPage.ToString();
                //}
                //if (columnToatlPage > 0 && result.TotalIRows != 0)
                //{
                //    ColCurrenPage = 1;
                //    getPageInfo(ColCurrenPage, result.columnPageSize, result.TotalColumns, out startColumn, out EndCurrentPageColumn);
                //    this.lblColumnNumber.Content = "Col " + startColumn.ToString() + " - " + EndCurrentPageColumn.ToString() + " Of " + result.TotalColumns.ToString();
                //}

            }
        }
Beispiel #40
0
 public ResultView(UserModel user)
 {
     InitializeComponent();
     _resultViewModel = new ResultViewModel(user);
     DataContext      = _resultViewModel;
 }
Beispiel #41
0
        public static void CreateCrossTabulation(string filePath, DataTable dt, List<SQLBuilder.Clauses.Column> SelectedColumns, ResultViewModel rvm)
        {
            FileInfo f = new FileInfo(filePath);
            if (f.Exists)
                f.Delete();

            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook);
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            var stylesPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorkbookStylesPart>();
            Stylesheet styles = new CustomStylesheet();
            styles.Save(stylesPart);
            workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

            WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new DocumentFormat.OpenXml.Spreadsheet.SheetData());

            DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = (spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets()));

            Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
            sheets.Append(sheet);
            string cl = "A";
            uint row = 1;

            int index;
            Cell cell = new Cell();
            System.Windows.Controls.Label colRow = new System.Windows.Controls.Label();
            int lineNumber = 0;

            colRow.Content = "Cross Tabulation by " + rvm.QueryBulder.CrossTabulationResults.CrossTabColumn.AliasName;
            cell = InsertCellInWorksheet(cl, row, worksheetPart);
            cell.CellValue = new CellValue(Convert.ToString(colRow.Content));
            cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
            cell.StyleIndex = 7;

            row++;

            List<List<string>> groupByColumnValues = rvm.QueryBulder.CrossTabulationResults.GroupByColumnValueList;

            for (int groupByColIndex = 0; groupByColIndex < rvm.QueryBulder.CrossTabulationResults.GroupByColumns.Count; groupByColIndex++)
            {
                SQLBuilder.Clauses.Column groupByCol = rvm.QueryBulder.CrossTabulationResults.GroupByColumns.ElementAt<SQLBuilder.Clauses.Column>(groupByColIndex);

                string colFormat = SQLBuilder.Common.ColumnFormat.Instance.getColumnFormat(groupByCol.Format);
                CrossTabulationViewGroupByControl ctvgCntrl = new CrossTabulationViewGroupByControl();
                colRow.Content = Common.getColumnNameOrAlias(groupByCol);

                for (int i = 0; i <= groupByColumnValues.Count + 1; i++)
                {
                    if (groupByColIndex >= 26)
                    {
                        cl = Convert.ToString(Convert.ToChar(65 + ((groupByColIndex / 26) - 1))) + Convert.ToString(Convert.ToChar(65 + groupByColIndex % 26));
                    }
                    else
                    {
                        cl = Convert.ToString(Convert.ToChar(65 + groupByColIndex));
                    }
                    SharedStringTablePart shareStringPart;
                    if (spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
                    {
                        shareStringPart = spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                    }
                    else
                    {
                        shareStringPart = spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
                    }
                    if (row == 2)
                    {
                        index = InsertSharedStringItem(dt.Columns[groupByColIndex].ColumnName, shareStringPart);
                        cell = InsertCellInWorksheet(cl, row, worksheetPart);
                        cell.CellValue = new CellValue(Convert.ToString(dt.Columns[groupByColIndex]));
                        cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                        cell.StyleIndex = 7;
                    }
                    else if (row > 3)
                    {
                        cell = InsertCellInWorksheet(cl, row, worksheetPart);
                        cell.CellValue = new CellValue(Convert.ToString(groupByColumnValues.ElementAt<List<string>>(i - 2).ElementAt<string>(groupByColIndex)));
                    }
                    lineNumber = lineNumber + 1;
                    row++;
                }
                row = 2;
            }

            int groupByColCount = rvm.QueryBulder.CrossTabulationResults.GroupByColumns.Count;
            int summarrizeValueIndex = groupByColCount + 1;
            Dictionary<string, Object> dataMap = rvm.QueryBulder.CrossTabulationResults.DataMap;
            row = 1;
            foreach (string summaryMainValue in rvm.QueryBulder.CrossTabulationResults.CrossTabColumnVaues)
            {

                CrossTabulationViewSummaryMainControl summaryMain = new CrossTabulationViewSummaryMainControl();
                summaryMain.lblSummaryHeader.Content = summaryMainValue;
                int totalcolumn = rvm.QueryBulder.CrossTabulationResults.SummarizeColumns.Count + groupByColCount;
                for (int summaryColIndex = 0; summaryColIndex < rvm.QueryBulder.CrossTabulationResults.SummarizeColumns.Count; summaryColIndex++)
                {
                    SQLBuilder.Clauses.Column summaryCol = rvm.QueryBulder.CrossTabulationResults.SummarizeColumns.ElementAt<SQLBuilder.Clauses.Column>(summaryColIndex);
                    string summaryColName = summaryCol.AliasName;
                    string summarycolFormat = SQLBuilder.Common.ColumnFormat.Instance.getColumnFormat(summaryCol.Format);
                    CrossTabulationViewSummaryControl ctvsCtrl = new CrossTabulationViewSummaryControl();

                    for (int keyIndex = 0; keyIndex <= rvm.QueryBulder.CrossTabulationResults.KeyPrefixes.Count + 2; keyIndex++)
                    {
                        if (summaryColIndex >= 26)
                        {
                            cl = Convert.ToString(Convert.ToChar(65 + ((summarrizeValueIndex / 26) - 1))) + Convert.ToString(Convert.ToChar(65 + summarrizeValueIndex % 26));
                        }
                        else
                        {
                            cl = Convert.ToString(Convert.ToChar(65 + summarrizeValueIndex));
                        }
                        SharedStringTablePart shareStringPart;
                        if (spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
                        {
                            shareStringPart = spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                        }
                        else
                        {
                            shareStringPart = spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
                        }
                        if (row == 1)
                        {
                            index = InsertSharedStringItem(summaryMainValue, shareStringPart);
                            cell = InsertCellInWorksheet(cl, row, worksheetPart);
                            cell.CellValue = new CellValue(Convert.ToString(summaryMainValue));
                            cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                            cell.StyleIndex = 7;
                        }
                        else if (row == 2)
                        {
                            index = InsertSharedStringItem(summaryColName, shareStringPart);
                            cell = InsertCellInWorksheet(cl, row, worksheetPart);
                            cell.CellValue = new CellValue(Convert.ToString(summaryColName));
                            cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                            cell.StyleIndex = 7;
                        }
                        else if (row > 3)
                        {
                            string key = rvm.QueryBulder.CrossTabulationResults.KeyPrefixes.ElementAt<string>(keyIndex - 3);

                            string keyValue = key + summaryMainValue + summaryColIndex;

                            cell = InsertCellInWorksheet(cl, row, worksheetPart);
                            if (dataMap.ContainsKey(keyValue))
                            {
                                if (summarycolFormat != null)
                                {
                                    cell.CellValue = new CellValue(String.Format(summarycolFormat, dataMap[keyValue]));
                                }
                                else
                                {
                                    cell.CellValue = new CellValue(Convert.ToString(dataMap[keyValue]));
                                }
                            }
                            else
                            {
                                cell.CellValue = new CellValue(Convert.ToString("00"));
                            }

                        }
                        lineNumber = lineNumber + 1;

                        if (row > rvm.QueryBulder.CrossTabulationResults.KeyPrefixes.Count + 2)
                        {
                            row = 1;
                            summarrizeValueIndex = summarrizeValueIndex + 1;
                        }
                        else
                        {
                            row++;
                        }
                    }
                    lineNumber = 0;
                }
                row = 1;
                groupByColCount = groupByColCount + 1;
            }
            worksheetPart.Worksheet.Save();
            workbookpart.Workbook.Save();
            spreadsheetDocument.Close();
        }
        private async void CreateItem()
        {
            try
            {
                ResultViewModel result = new ResultViewModel {
                    IsError = true
                };
                if (IsUpdate)
                {
                    ItemModel item = new ItemModel()
                    {
                        Id             = UpdateItem.Id,
                        Name           = ItemName,
                        CategoryName   = SelectedCategory,
                        Price          = ConvertPrice(ItemPrice),
                        Cost           = ConvertPrice(ItemCost),
                        Color          = GetColor(),
                        Option1        = SetDefaultOption(),
                        Option1Price   = ConvertPrice(Price1),
                        Option2        = Option2,
                        Option2Price   = ConvertPrice(Price2),
                        Option3        = Option3,
                        Option3Price   = ConvertPrice(Price3),
                        Option4        = Option4,
                        Option4Price   = ConvertPrice(Price4),
                        CreateDateTime = UpdateItem.CreateDateTime,
                        UpdateDateTime = UpdateItem.UpdateDateTime,
                    };

                    result = await _productService.UpdateItem(item);
                }
                else
                {
                    if (String.IsNullOrEmpty(SelectedCategory) || SelectedCategory == "0")
                    {
                    }
                    else
                    {
                        ItemModel item = new ItemModel()
                        {
                            Name         = ItemName,
                            CategoryName = SelectedCategory,
                            Price        = ConvertPrice(ItemPrice),
                            Cost         = ConvertPrice(ItemCost),
                            Color        = GetColor(),
                            Option1      = Option1,
                            Option1Price = ConvertPrice(Price1),
                            Option2      = Option2,
                            Option2Price = ConvertPrice(Price2),
                            Option3      = Option3,
                            Option3Price = ConvertPrice(Price3),
                            Option4      = Option4,
                            Option4Price = ConvertPrice(Price4)
                        };
                        result = await _productService.CreateItem(item);
                    }
                }

                if (result != null && !result.IsError)
                {
                    ErrorViewModel errorViewModel = new ErrorViewModel("บันทึกรายการสำเร็จ", 3);
                    PopupNavigation.Instance.PushAsync(new Error(errorViewModel));
                    BackPageMethod();
                }
                else
                {
                    ErrorViewModel error = new ErrorViewModel("ผิดพลาด", 1);
                    PopupNavigation.Instance.PushAsync(new Error(error));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }