public void SaveAnswers(string command)
    {
        ResultModel rm = new ResultModel ();
        rm.UserID = PlayerPrefs.GetInt ("UserIDforTest");
        rm.UserType = PlayerPrefs.GetString ("UserTypeforTest").Replace('"',' ').Trim();

        foreach (QuizPartModel qpm in options) {
            foreach(QuizOptionModel qom in qpm.Options){
                rm.Options.Add(qom);
            }
        }

        int counter = 0;
        for (int i=0; i<=toggles.Count-1; i++) {
                int limit = toggles[i].Length;
                for(int x =0; x<limit; x++){

            if(toggles[i][x].isOn == true){
                rm.Options[counter].Selected = true;
                    counter++;
            }else if(toggles[i][x].isOn ==false){
                rm.Options[counter].Selected = false;
                    counter++;
                }
            }
        }
            POSTResultCalculator cal = gameObject.GetComponent<POSTResultCalculator>();
            cal.ParseToJsonResult(rm, command);
    }
    //Creates a JSON from a resultModel and parses it to the POSTFacade
    public void ParseToJsonResult(ResultModel resultModel, string command)
    {
        JSONObject json = new JSONObject (JSONObject.Type.OBJECT);

            json.AddField("UserID", resultModel.UserID);
            json.AddField("UserType", resultModel.UserType);

            JSONObject arr = new JSONObject(JSONObject.Type.ARRAY);
            json.AddField("Answers",arr);
            foreach(QuizOptionModel qm in resultModel.Options){
            JSONObject ans = new JSONObject(JSONObject.Type.OBJECT);
                ans.AddField("ID",qm.Id);
                ans.AddField("Title",qm.Title);
                ans.AddField("Selected",qm.Selected);

            arr.Add(ans);
            }
        switch(command){
        case "SaveToServer":
        POSTFacade facade = gameObject.GetComponent<POSTFacade> ();
            facade.SaveQuizAnswers (json,resultModel.UserID.ToString());
            break;
        case "SaveLocal":
            PlayerPrefs.SetString("TestToSave_"+resultModel.UserID, json.Print());
            break;
        }
    }
示例#3
0
        /// <summary>
        /// Add a colony to the current ResultModel.
        /// </summary>
        /// <param name="x">Mouse X position.</param>
        /// <param name="y">Mouse Y position.</param>
        /// <param name="pictureBox">The current PictureBox that is used.</param>
        /// <param name="resultModel">The current used ResultModel.</param>
        /// // ADD COLONY TO RESULT MODEL
        public static void AddColony(int x, int y, PictureBox pictureBox, ResultModel resultModel)
        {
            try
            {
                // GET RELATIVE POSITION
                int realX = TranslateZoomMousePosition(new System.Drawing.Point(x, y), pictureBox).X;
                int realY = TranslateZoomMousePosition(new System.Drawing.Point(x, y), pictureBox).Y;

                // WITHIN PICTUREBOX
                if ((realX >= 0) && (realX <= pictureBox.Image.Width) && (realY >= 0) && (realY <= pictureBox.Image.Height))
                {
                    bool clicked = false;

                    // CHECK MOUSE LOCATION TO COLONY LOCATION
                    for (int i = 0; i < resultModel.ColonyList.Count; i++)
                    {
                        if (ClickedOnColony(realX, realY, resultModel.ColonyList[i]))
                        {
                            clicked = true;
                            break;
                        }
                    }

                    // IF MOUSE LOCATION IS NOT COLONY LOCATION, ADD NEW
                    if (!clicked)
                    {
                        resultModel.ColonyList.Add(new ColonyModel(new AForge.Point(realX, realY), GetAverageRadius(resultModel)));
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Toevoegen is mislukt.");
            }
        }
示例#4
0
 //Saves image in file storage and returns a string of the file path
 public static string SaveOnStorage(string fileStorage, ResultModel currentModel)
 {
     string folderPath = fileStorage + "" + currentModel.Gebruiker + "_" + currentModel.Datum.Year + currentModel.Datum.Month + currentModel.Datum.Day + currentModel.Datum.Minute + currentModel.Datum.Second + ".jpg";
     Bitmap tmpBitmap = currentModel.ResultImage as Bitmap;
     //New bitmap so program can save it.
     Bitmap newBitMap = new Bitmap(tmpBitmap);
     newBitMap.Save(folderPath, ImageFormat.Jpeg);
     newBitMap.Dispose();
     return folderPath;
 }
        /// <summary>
        /// Saves a resultModel to the database
        /// </summary>
        /// <param name="resultModel">The resultModel to save.</param>
        public void ResultModelToDB(ResultModel resultModel)
        {
            // CHECK FOR OPEN CONNECTION
            int connOpen = 0;
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
                connOpen = 1;
            }

            // STRING WITH QUERY
            string query = @"UPDATE Resultaat SET " +
                "Verdunning = @verdunning, "+
                "Kolonies = @kolonies, "+
                "Temperatuur = @temperatuur, "+
                "Soort = @soort, " +
                "Strain = @strain, " +
                "Tijdsduur = @tijdsduur, " +
                "Voedingsbodem = @voedingsbodem, " +
                "Bron = @bron, " +
                "Medium = @medium, " +
                "Behandeling = @behandeling, " +
                "Path = @path, " +
                "Kolonie_positie = @kolonie_positie " +
                "WHERE ID = @id";
            SqlCommand command = new SqlCommand(query, connection);

            // QUERY PARAMETERS
            command.Parameters.Add(new SqlParameter("verdunning", resultModel.Verdunning));
            command.Parameters.Add(new SqlParameter("kolonies", resultModel.Kolonies));
            command.Parameters.Add(new SqlParameter("temperatuur", resultModel.Temperatuur));
            command.Parameters.Add(new SqlParameter("soort", resultModel.Soort));
            command.Parameters.Add(new SqlParameter("strain", resultModel.Strain));
            command.Parameters.Add(new SqlParameter("tijdsduur", resultModel.Tijdsduur));
            command.Parameters.Add(new SqlParameter("voedingsbodem", resultModel.Voedingsbodem));
            command.Parameters.Add(new SqlParameter("bron", resultModel.Bron));
            command.Parameters.Add(new SqlParameter("medium", resultModel.Medium));
            command.Parameters.Add(new SqlParameter("behandeling", resultModel.Behandeling));
            command.Parameters.Add(new SqlParameter("path", resultModel.FilePath));
            command.Parameters.Add(new SqlParameter("kolonie_positie", resultModel.ColonyListToString()));

            command.Parameters.Add(new SqlParameter("id", resultModel.ID));
            command.ExecuteNonQuery();
            // CLEAR PARAMETERS
            command.Parameters.Clear();

            mainController.resultController.Init();
            // IF OPEN THEN CLOSE
            if (connOpen == 1)
                connection.Close();
        }
    public void ParseJsonFromFacade(JSONObject menuResults, JSONObject teachingPlans)
    {
        JSONObject arr = new JSONObject (JSONObject.Type.ARRAY);
        ResultModel rm;
        QuizOptionModel qom;
        List<QuizOptionModel> options = null;

        for (int i = 0; i<menuResults.Count; i++) {
            rm = new ResultModel ();

            rm.UserID = (int)int.Parse (menuResults [i].GetField ("UserID").ToString ());
            rm.UserType = menuResults [i].GetField ("UserType").ToString ().Replace('"',' ').Trim();
            if(rm.UserType == "Teacher"){
                //Only for test needs the ONLYFORTESTSCRIPT
                rm.StudentName = PlayerPrefs.GetString("UserName");
                //Maybe solution if UserName exist in PlayerPrefs when logged in
                //rm.StudentName = PlayerPrefs.GetString("UserName");
            }

            for(int x = 0 ; x<teachingPlans.Count ; x++){
                int tempStudentID = int.Parse(teachingPlans[x].GetField("StudentID").ToString());
                if(tempStudentID == rm.UserID){
                    rm.StudentName = teachingPlans[x].GetField("StudentName").ToString().Replace('"', ' ').Trim();
                    break;
                }
            }

            options = new List<QuizOptionModel> ();
            arr = menuResults [i].GetField ("Answers");
            for (int j = 0; j<arr.Count; j++) {

                qom = new QuizOptionModel ();
                qom.Id = (int)int.Parse (arr [j].GetField ("ID").ToString ());
                qom.Title = arr [j].GetField ("Title").ToString ();
                qom.Selected = Convert.ToBoolean(arr [j].GetField ("Selected").ToString());

                options.Add (qom);
            }
            rm.Options = options;

            resultModels.Add(rm);

        }
        resultModels.Reverse ();
        ResultCalculator resCal = gameObject.GetComponent<ResultCalculator> ();

        resCal.CalculateResult (resultModels);
    }
示例#7
0
 public JsonResult CapitalCallSummaryList(FormCollection collection)
 {
     CapitalCallSummaryModel model = new CapitalCallSummaryModel();
     this.TryUpdateModel(model, collection);
     string error = string.Empty;
     ResultModel resultModel = new ResultModel();
     CapitalCallReportDetail detail = null;
     if (ModelState.IsValid) {
         detail = ReportRepository.FindCapitalCall(model.CapitalCallId);
     }
     else {
         foreach (var values in ModelState.Values.ToList()) {
             foreach (var err in values.Errors.ToList()) {
                 if (string.IsNullOrEmpty(err.ErrorMessage) == false) {
                     error += err.ErrorMessage + "\n";
                 }
             }
         }
     }
     return Json(new { Error = error, Data = detail }, JsonRequestBehavior.AllowGet);
 }
示例#8
0
        public async Task <IResultModel> WorkDelete(int id)
        {
            var result = await _workRepository.DeleteAsync(id);

            return(ResultModel.Result(result));
        }
示例#9
0
        public static Tuple <bool, string> CanReplacePosition(string localID, string classID, List <ResultDetailModel> sourceItem, List <ResultDetailModel> targetItem, ResultModel resultModel)
        {
            ICommonDataManager commonDataManager = CacheManager.Instance.UnityContainer.Resolve <ICommonDataManager>();
            var cp   = commonDataManager.GetCPCase(localID);
            var rule = commonDataManager.GetAminRule(localID);
            var algo = commonDataManager.GetAminAlgoRule(localID);

            var positionsSource = GetMovablePositons(localID, classID, sourceItem, resultModel);
            var positionsTarget = GetMovablePositons(localID, classID, targetItem, resultModel);

            DayPeriodModel dpSource = sourceItem.FirstOrDefault().DayPeriod;
            DayPeriodModel dpTarget = targetItem.FirstOrDefault().DayPeriod;

            if (dpTarget != null && positionsSource.Item1.Exists(dp => dp.Day == dpTarget.Day && dp.PeriodName == dpTarget.PeriodName) &&
                dpSource != null && positionsTarget.Item1.Exists(dp => dp.Day == dpSource.Day && dp.PeriodName == dpSource.PeriodName))
            {
                return(Tuple.Create(true, string.Empty));
            }
            else
            {
                var sourceToTargetWarning = positionsSource.Item2.Where(dp => dp.DayPeriod.Day == dpTarget.Day && dp.DayPeriod.PeriodName == dpTarget.PeriodName).ToList();
                var targetToSourceWarning = positionsTarget.Item2.Where(dp => dp.DayPeriod.Day == dpSource.Day && dp.DayPeriod.PeriodName == dpSource.PeriodName).ToList();

                StringBuilder sb = new StringBuilder(100);

                sourceToTargetWarning?.ForEach(w =>
                {
                    sb.AppendLine(w.WaringMessage);
                });

                targetToSourceWarning?.ForEach(w =>
                {
                    sb.AppendLine(w.WaringMessage);
                });

                return(Tuple.Create(false, sb.ToString()));
            }
        }
示例#10
0
        public ActionResult EventResults(int id)
        {
            using (var context = new LeadGenContext())
            {
                var responseEvents = context.Responses.Include("OriginalEvent").Include("Responses").Include("Responses.OriginalQuestion").Where(p => p.OriginalEvent.EventId == id);

                if (!responseEvents.Any())
                    return RedirectToAction("Index", "Admin");

                ViewBag.EventId = id;

                var results = new List<QuestionResult>();
                ViewBag.EventTitle = responseEvents.First().OriginalEvent.EventName;

                ResultModel model = new ResultModel { Respondants = new List<Respondant>() };
                foreach (var e in responseEvents)
                {
                    model.Respondants.Add(new Respondant()
                                              {
                                                  EmailAddress = e.EmailAddress,
                                                  FirstName = e.FirstName,
                                                  LastName = e.LastName,
                                                  ZipCode = e.ZipCode
                                              });

                    foreach (var q in e.Responses.OrderBy(p => p.OriginalQuestion.QuestionId))
                    {
                        // is q in result list?
                        QuestionResponse q1 = q;
                        var questionResults = results.Where(p => p.QuestionText == q1.OriginalQuestion.QuestionText);
                        if (questionResults.Any())
                        {
                            // is answer in questionResult
                            var first = questionResults.First();
                            var answers = first.QuestionAnswers.Where(p => p.AnswerText == q1.Answer);
                            if (answers.Any())
                            {
                                var firstAnswer = answers.First();
                                firstAnswer.AnswerCount++;
                            }
                            else
                            {
                                first.QuestionAnswers.Add(new Answer() { AnswerText = q.Answer, AnswerCount = 1 });
                            }
                        }
                        else
                        {
                            results.Add(new QuestionResult
                                            {
                                                QuestionText = q.OriginalQuestion.QuestionText,
                                                QuestionAnswers = new List<Answer>() { new Answer() { AnswerCount = 1, AnswerText = q.Answer } }
                                            });
                        }
                    }
                }
                model.Results = results;

                return View(model);
            }
        }
示例#11
0
        private async void DepartmentEmployeeRegistration()
        {
            try

            {
                TokenNo();

                Drawable icon_error = Resources.GetDrawable(Resource.Drawable.alert);
                icon_error.SetBounds(0, 0, 40, 30);
                if (txt_EmployeeTokenNo.Text != "")
                {
                    if (txt_EmployeeName.Text != "")
                    {
                        if (txt_EmployeeAddress.Text != "")
                        {
                            if (txt_EmployeeContactNo.Text != "")
                            {
                                if (txt_EmployeeEmailID.Text != "")
                                {
                                    if (txt_EmployeeDepartmentID.Text != "")
                                    {
                                        if (txt_EmployeeDesignationID.Text != "")
                                        {
                                            if (txt_EmployeePassword.Text != "")
                                            {
                                                foreach (var item in ResultAllDesignationMaster)
                                                {
                                                    if (item.DesignationName.ToString().Trim() == (txt_EmployeeDesignationID.Text.Trim()))
                                                    {
                                                        _ObjDepartmentEmployeeRegistration.EmployeeDepartmentID  = item.DepartmentID;
                                                        _ObjDepartmentEmployeeRegistration.EmployeeDesignationID = item.DesignationID;
                                                    }
                                                }


                                                _ObjDepartmentEmployeeRegistration.DeviceTokenId     = DTI.ToString();
                                                _ObjDepartmentEmployeeRegistration.EmployeeTokenNo   = txt_EmployeeTokenNo.Text;
                                                _ObjDepartmentEmployeeRegistration.EmployeeName      = txt_EmployeeName.Text;
                                                _ObjDepartmentEmployeeRegistration.EmployeeAddress   = txt_EmployeeAddress.Text;
                                                _ObjDepartmentEmployeeRegistration.EmployeeContactNo = txt_EmployeeContactNo.Text;
                                                _ObjDepartmentEmployeeRegistration.EmployeeEmailID   = txt_EmployeeEmailID.Text;
                                                //_ObjDepartmentEmployeeRegistration.EmployeeDepartmentID = Convert.ToInt32(txt_EmployeeDepartmentID.Text);
                                                //_ObjDepartmentEmployeeRegistration.EmployeeDesignationID = Convert.ToInt32(txt_EmployeeDesignationID.Text);
                                                _ObjDepartmentEmployeeRegistration.EmployeePassword = txt_EmployeePassword.Text;
                                                _ObjDepartmentEmployeeRegistration.Date             = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
                                                // ADD Insert Code Here

                                                WebHelpper _objHelper = new WebHelpper();

                                                string Url = StatusModel.Url + "AddDepartmentEmployeeRegistration";

                                                progressDialog = ProgressDialog.Show(this, Android.Text.Html.FromHtml("<font color='#EC407A'> Please wait...</font>"), Android.Text.Html.FromHtml("<font color='#EC407A'> Data Inserting...</font>"), true);

                                                var PostString  = JsonConvert.SerializeObject(_ObjDepartmentEmployeeRegistration);
                                                var requestTemp = await _objHelper.MakePostRequest(Url, PostString, true);

                                                ResultModel ResultgetRequest = JsonConvert.DeserializeObject <ResultModel>(requestTemp);

                                                if (ResultgetRequest.success == 1)
                                                {
                                                    progressDialog.Hide();
                                                    Toast.MakeText(this, ResultgetRequest.msg, ToastLength.Short).Show();
                                                }

                                                else
                                                {
                                                    progressDialog.Hide();
                                                    Toast.MakeText(this, ResultgetRequest.msg, ToastLength.Short).Show();
                                                    return;
                                                }


                                                clear();
                                            }
                                            else
                                            {
                                                txt_EmployeePassword.RequestFocus();
                                                txt_EmployeePassword.SetError("Please Enter Password First", icon_error);
                                            }
                                        }
                                        else
                                        {
                                            txt_EmployeeDesignationID.RequestFocus();
                                            txt_EmployeeDesignationID.SetError("Please Select Designation First", icon_error);
                                        }
                                    }
                                    else
                                    {
                                        txt_EmployeeDepartmentID.RequestFocus();
                                        txt_EmployeeDepartmentID.SetError("Please Select Department First", icon_error);
                                    }
                                }
                                else
                                {
                                    txt_EmployeeEmailID.RequestFocus();
                                    txt_EmployeeEmailID.SetError("Please Enter Email ID First", icon_error);
                                }
                            }
                            else
                            {
                                txt_EmployeeContactNo.RequestFocus();
                                txt_EmployeeContactNo.SetError("Please Enter Contact Number First", icon_error);
                            }
                        }
                        else
                        {
                            txt_EmployeeAddress.RequestFocus();
                            txt_EmployeeAddress.SetError("Please Enter Address First", icon_error);
                        }
                    }
                    else
                    {
                        txt_EmployeeName.RequestFocus();
                        txt_EmployeeName.SetError("Please Enter Full Name First", icon_error);
                    }
                }
                else
                {
                    txt_EmployeeTokenNo.RequestFocus();
                    txt_EmployeeTokenNo.SetError("Please Enter Token Number First", icon_error);
                }
            }
            catch (Exception e)
            {
                progressDialog.Hide();
                string ErrorMsg = e.ToString();
                Toast.MakeText(this, ErrorMsg, ToastLength.Long).Show();
            }
        }
示例#12
0
        private static Tuple <List <DayPeriodModel>, List <PostionWithWarningInfo> > GetMovablePositons(string localID, string classID, List <ResultDetailModel> item, ResultModel resultModel)
        {
            //可用课位,最后取反返回不可用课位
            var dayPeriods   = new List <DayPeriodModel>();
            var notReachable = new List <PostionWithWarningInfo>();

            ICommonDataManager commonDataManager = CacheManager.Instance.UnityContainer.Resolve <ICommonDataManager>();
            var cp   = commonDataManager.GetCPCase(localID);
            var rule = commonDataManager.GetAminRule(localID);
            var algo = commonDataManager.GetAminAlgoRule(localID);

            //获取方案可用时间
            dayPeriods = cp?.Positions?.Where(p => p.IsSelected &&
                                              p.Position != XYKernel.OS.Common.Enums.Position.AB &&
                                              p.Position != XYKernel.OS.Common.Enums.Position.Noon &&
                                              p.Position != XYKernel.OS.Common.Enums.Position.PB)
                         ?.Select(d => d.DayPeriod)?.ToList() ?? new List <DayPeriodModel>();

            //TODO: 是否基于现有模型更新结果模型中的教师信息?
            item?.ForEach(it =>
            {
                List <string> teachers = new List <string>();
                teachers = it?.Teachers == null ? new List <string>() : it.Teachers.ToList();

                //1.0 移除教师在其他班级的课位
                if (teachers.Count > 0)
                {
                    resultModel.ResultClasses?.Where(c => c.ClassID != classID)?.ToList()?.ForEach(c =>
                    {
                        c.ResultDetails?.Where(rd => rd.Teachers != null && rd.Teachers.Intersect(teachers).Count() > 0)?.ToList()?.ForEach(t =>
                        {
                            notReachable.Add(new PostionWithWarningInfo()
                            {
                                DayPeriod = t.DayPeriod, WaringMessage = $"教师在课位({TimeOperation.GetDateInfo(t.DayPeriod)})安排有其他班级课程!"
                            });
                            dayPeriods.RemoveAll(p => p.Day == t.DayPeriod.Day && p.PeriodName == t.DayPeriod.PeriodName);
                        });
                    });
                }

                //2.0 检查批量规则 - 仅查权重为高级的规则
                rule?.TeacherTimes?.Where(t => t.Weight == 1 && teachers.Contains(t.TeacherID))?.ToList()?.ForEach(x =>
                {
                    if (x.ForbidTimes != null)
                    {
                        dayPeriods = TimeOperation.TimeSlotDiff(dayPeriods, x.ForbidTimes);

                        x.ForbidTimes.ForEach(fb =>
                        {
                            notReachable.Add(new PostionWithWarningInfo()
                            {
                                DayPeriod = fb, WaringMessage = $"教师在课位({TimeOperation.GetDateInfo(fb)})有禁止规则!"
                            });
                        });
                    }

                    if (x.MustTimes != null)
                    {
                        //必须时间暂不必查
                    }
                });

                rule?.CourseTimes?.Where(c => c.Weight == 1 && c.ClassID == classID && c.CourseID == it.CourseID)?.ToList()?.ForEach(x =>
                {
                    if (x.ForbidTimes != null)
                    {
                        dayPeriods = TimeOperation.TimeSlotDiff(dayPeriods, x.ForbidTimes);

                        x.ForbidTimes.ForEach(fb =>
                        {
                            notReachable.Add(new PostionWithWarningInfo()
                            {
                                DayPeriod = fb, WaringMessage = $"课程在课位({TimeOperation.GetDateInfo(fb)})有禁止规则!"
                            });
                        });
                    }

                    if (x.MustTimes != null)
                    {
                        int classHourNumber = cp.ClassHours.Where(ch => ch.ClassID == classID && ch.CourseID == it.CourseID).Count();

                        if (x.MustTimes.Count >= classHourNumber)
                        {
                            dayPeriods.ForEach(dp =>
                            {
                                if (!x.MustTimes.Exists(mt => mt.Day == dp.Day && mt.PeriodName == dp.PeriodName))
                                {
                                    notReachable.Add(new PostionWithWarningInfo()
                                    {
                                        DayPeriod = dp, WaringMessage = "课程应先满足排到必须规则指定课位内!"
                                    });
                                }
                            });

                            dayPeriods = TimeOperation.TimeSlotInterSect(dayPeriods, x.MustTimes);
                        }
                        else
                        {
                            List <DayPeriodModel> classHourTimes = resultModel.ResultClasses.Where(c => c.ClassID == classID)
                                                                   ?.SelectMany(c => c.ResultDetails)
                                                                   ?.Where(c => c.CourseID == it.CourseID)
                                                                   ?.Select(c => c.DayPeriod).ToList() ?? new List <DayPeriodModel>()
                            {
                            };

                            List <DayPeriodModel> classHoursInMust = TimeOperation.TimeSlotInterSect(x.MustTimes, classHourTimes);
                            if (classHoursInMust.Count < x.MustTimes.Count)
                            {
                                dayPeriods.ForEach(dp =>
                                {
                                    if (!x.MustTimes.Exists(mt => mt.Day == dp.Day && mt.PeriodName == dp.PeriodName))
                                    {
                                        notReachable.Add(new PostionWithWarningInfo()
                                        {
                                            DayPeriod = dp, WaringMessage = "课程应先满足排到必须规则指定课位内!"
                                        });
                                    }
                                });

                                dayPeriods = TimeOperation.TimeSlotInterSect(dayPeriods, x.MustTimes);
                            }
                            else
                            {
                                //如果课位在必须时间内,则只能和本班课时互换以保障课时优先在必须时间内
                                List <DayPeriodModel> mustTempTimes = TimeOperation.TimeSlotInterSect(x.MustTimes, new List <DayPeriodModel>()
                                {
                                    it.DayPeriod
                                });
                                if (mustTempTimes.Count == 1)
                                {
                                    dayPeriods.ForEach(dp =>
                                    {
                                        if (!classHourTimes.Exists(mt => mt.Day == dp.Day && mt.PeriodName == dp.PeriodName))
                                        {
                                            notReachable.Add(new PostionWithWarningInfo()
                                            {
                                                DayPeriod = dp, WaringMessage = "课程应先满足排到必须规则指定课位内!"
                                            });
                                        }
                                    });

                                    dayPeriods = TimeOperation.TimeSlotInterSect(dayPeriods, classHourTimes);
                                }
                            }
                        }
                    }
                });

                rule?.AmPmClassHours?.Where(a => a.Weight == 1 && a.ClassID == classID && a.CourseID == it.CourseID)?.ToList()?.ForEach(x =>
                {
                    int pmNumber     = 0;
                    int amNumber     = 0;
                    var timePosition = cp.Positions.Where(p => p.DayPeriod.Day == it.DayPeriod.Day && p.DayPeriod.PeriodName == it.DayPeriod.PeriodName).FirstOrDefault();
                    var classHours   = resultModel.ResultClasses?.Where(c => c.ClassID == classID)
                                       ?.SelectMany(c => c.ResultDetails)?.Where(c => c.CourseID == it.CourseID)?.ToList();

                    classHours?.ForEach(c =>
                    {
                        var tPosition = cp.Positions.Where(p => p.DayPeriod.Day == c.DayPeriod.Day && p.DayPeriod.PeriodName == c.DayPeriod.PeriodName).FirstOrDefault();
                        if (tPosition != null)
                        {
                            if (tPosition.Position == XYKernel.OS.Common.Enums.Position.AM)
                            {
                                amNumber = amNumber + 1;
                            }

                            if (tPosition.Position == XYKernel.OS.Common.Enums.Position.PM)
                            {
                                pmNumber = pmNumber + 1;
                            }
                        }
                    });

                    //If current time slot is AM, And PMMax is full, Disable PM
                    if (timePosition.Position == XYKernel.OS.Common.Enums.Position.AM)
                    {
                        if (x.PmMax > 0 && pmNumber >= x.PmMax)
                        {
                            //Disable PM
                            var pmTimes = cp.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.PM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, pmTimes);

                            pmTimes.ForEach(pt =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = pt, WaringMessage = "违反班级课程的下午最大课时规则!"
                                });
                            });
                        }

                        if (x.AmMax > 0 && amNumber > x.AmMax)
                        {
                            //Disable AM
                            var amTimes = cp.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.AM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, amTimes);

                            amTimes.ForEach(pt =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = pt, WaringMessage = "违反班级课程的上午最大课时规则!"
                                });
                            });
                        }
                    }

                    //If current time slot is PM, And AMMax is full, Disable AM
                    if (timePosition.Position == XYKernel.OS.Common.Enums.Position.PM)
                    {
                        if (x.AmMax > 0 && amNumber >= x.AmMax)
                        {
                            //Disable AM
                            var amTimes = cp.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.AM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, amTimes);

                            amTimes.ForEach(at =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = at, WaringMessage = "违反班级课程的上午最大课时规则!"
                                });
                            });
                        }

                        if (x.PmMax > 0 && pmNumber > x.PmMax)
                        {
                            //Disable PM
                            var pmTimes = cp.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.PM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, pmTimes);

                            pmTimes.ForEach(at =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = at, WaringMessage = "违反班级课程的下午最大课时规则!"
                                });
                            });
                        }
                    }
                });

                rule?.AmPmNoContinues.Where(a => a.Weight == 1 && teachers.Contains(a.TeacherID)).ToList()?.ForEach(x =>
                {
                    List <DayPeriodModel> currentTimeSlots = resultModel.ResultClasses?.SelectMany(c => c.ResultDetails)?.Where(c => c.Teachers != null && c.Teachers.Contains(x.TeacherID))?.ToList()?.Select(c => c.DayPeriod)?.ToList() ?? new List <DayPeriodModel>()
                    {
                    };
                    var amLast  = cp.Positions.Where(p => p.Position == XYKernel.OS.Common.Enums.Position.AM && p.DayPeriod.Day == DayOfWeek.Monday).OrderBy(p => p.PositionOrder).LastOrDefault();
                    var pmFirst = cp.Positions.Where(p => p.Position == XYKernel.OS.Common.Enums.Position.PM && p.DayPeriod.Day == DayOfWeek.Monday).OrderBy(p => p.PositionOrder).FirstOrDefault();
                    List <DayPeriodModel> amLasts  = new List <DayPeriodModel>();
                    List <DayPeriodModel> pmFirsts = new List <DayPeriodModel>();

                    if (amLast != null)
                    {
                        amLasts = cp.Positions.Where(p => p.Position == XYKernel.OS.Common.Enums.Position.AM && p.DayPeriod.PeriodName == amLast.DayPeriod.PeriodName).Select(p => p.DayPeriod).ToList();
                    }

                    if (pmFirst != null)
                    {
                        pmFirsts = cp.Positions.Where(p => p.Position == XYKernel.OS.Common.Enums.Position.PM && p.DayPeriod.PeriodName == pmFirst.DayPeriod.PeriodName).Select(p => p.DayPeriod).ToList();
                    }

                    //合并上午最后一节和下午第一节课位
                    List <DayPeriodModel> availableNoonTimes = TimeOperation.TimeSlotUnion(amLasts, pmFirsts);
                    //移除当前要移动的课位
                    currentTimeSlots = TimeOperation.TimeSlotDiff(currentTimeSlots, new List <DayPeriodModel>()
                    {
                        it.DayPeriod
                    });
                    //教师在中午的上课信息
                    List <DayPeriodModel> teacherNoonTimes             = TimeOperation.TimeSlotInterSect(currentTimeSlots, availableNoonTimes);
                    List <DayPeriodModel> teacherNotAvailableNoonTimes = new List <DayPeriodModel>()
                    {
                    };

                    availableNoonTimes.ForEach(an =>
                    {
                        if (teacherNoonTimes.Exists(t => t.Day == an.Day))
                        {
                            teacherNotAvailableNoonTimes.Add(an);
                        }
                    });

                    teacherNotAvailableNoonTimes = TimeOperation.TimeSlotDiff(teacherNotAvailableNoonTimes, teacherNoonTimes);
                    dayPeriods = TimeOperation.TimeSlotDiff(dayPeriods, teacherNotAvailableNoonTimes);

                    teacherNotAvailableNoonTimes.ForEach(tn =>
                    {
                        notReachable.Add(new PostionWithWarningInfo()
                        {
                            DayPeriod = tn, WaringMessage = "违反教师中午课时不连排规则!"
                        });
                    });
                });

                rule?.MasterApprenttices.Where(m => m.Weight == 1 && m.CourseID == it.CourseID && (teachers.Contains(m.MasterID) || teachers.Intersect(m.ApprenticeIDs).Count() > 0))?.ToList()?.ForEach(x =>
                {
                    //默认处理逻辑为徒弟之间也不允许同时排课, 不然无法保证互听课
                    List <string> tempTeachers = new List <string>();
                    tempTeachers.AddRange(x.ApprenticeIDs);
                    tempTeachers.AddRange(teachers);
                    tempTeachers.Add(x.MasterID);
                    tempTeachers = tempTeachers.Distinct().ToList();

                    var classHoursTimes = resultModel.ResultClasses?.SelectMany(c => c.ResultDetails)?.Where(c => c.CourseID == it.CourseID && c.Teachers.Intersect(tempTeachers).Count() > 0)?.ToList()?.Select(c => c.DayPeriod);

                    classHoursTimes?.ToList()?.ForEach(c =>
                    {
                        dayPeriods.RemoveAll(d => d.Day == c.Day && d.PeriodName == c.PeriodName);
                        notReachable.Add(new PostionWithWarningInfo()
                        {
                            DayPeriod = c, WaringMessage = "违反师徒跟随规则!"
                        });
                    });
                });

                rule?.Mutexes?.Where(m => m.Weight == 1 && m.CourseIDs != null && m.CourseIDs.Contains(it.CourseID))?.ToList()?.ForEach(x =>
                {
                    List <string> tempCourseIds = x.CourseIDs?.Select(xc => xc)?.ToList();
                    tempCourseIds.RemoveAll(t => t == it.CourseID);

                    var classHoursTimes = resultModel.ResultClasses
                                          ?.Where(r => r.ClassID == classID)?.SelectMany(c => c.ResultDetails)
                                          ?.Where(c => tempCourseIds.Contains(c.CourseID))
                                          ?.ToList()?.Select(c => c.DayPeriod.Day);

                    classHoursTimes?.ToList()?.ForEach(c =>
                    {
                        dayPeriods.Where(d => d.Day == c)?.ToList()?.ForEach(dp =>
                        {
                            notReachable.Add(new PostionWithWarningInfo()
                            {
                                DayPeriod = dp, WaringMessage = "违反课程互斥规则!"
                            });
                        });

                        dayPeriods.RemoveAll(d => d.Day == c);
                    });
                });

                #region 合班规则
                List <string> unionClassIDs = new List <string>();
                rule?.ClassUnions?.Where(cu => cu.ClassIDs != null && cu.ClassIDs.Contains(classID) && cu.CourseID == it.CourseID)?.ToList()?.ForEach(x => {
                    //Get All Union ClassID
                    x.ClassIDs.ForEach(cl => {
                        if (!unionClassIDs.Contains(cl))
                        {
                            unionClassIDs.Add(cl);
                        }
                    });
                });

                if (unionClassIDs.Count > 1)
                {
                    bool flag = true;
                    List <DayPeriodModel> timeslots = new List <DayPeriodModel>();

                    foreach (string classId in unionClassIDs)
                    {
                        var courseTimes = resultModel.ResultClasses?
                                          .Where(rc => rc.ClassID == classId)?
                                          .SelectMany(c => c.ResultDetails)?
                                          .Where(c => c.CourseID == it.CourseID)?
                                          .ToList()?.Select(c => c.DayPeriod)?.ToList() ?? new List <DayPeriodModel>();

                        if (timeslots.Count == 0)
                        {
                            timeslots = courseTimes;
                        }
                        else
                        {
                            List <DayPeriodModel> timesUnion = TimeOperation.TimeSlotUnion(timeslots.ToList(), courseTimes);
                            List <DayPeriodModel> timesDiff  = TimeOperation.TimeSlotDiff(timeslots.ToList(), courseTimes);
                            if (timesUnion.Count != timeslots.Count || timesDiff.Count != 0)
                            {
                                flag = false;
                            }
                        }
                    }

                    if (flag)
                    {
                        List <DayPeriodModel> timesInterSect = TimeOperation.TimeSlotInterSect(timeslots.ToList(), dayPeriods.ToList());
                        List <DayPeriodModel> timesDiff      = TimeOperation.TimeSlotDiff(dayPeriods.ToList(), timesInterSect.ToList());

                        timesDiff?.ForEach(c =>
                        {
                            dayPeriods.RemoveAll(d => d.Day == c.Day && d.PeriodName == c.PeriodName);
                            notReachable.Add(new PostionWithWarningInfo()
                            {
                                DayPeriod = c, WaringMessage = "违反合班规则!"
                            });
                        });
                    }
                }
                #endregion
            });

            return(Tuple.Create(dayPeriods, notReachable));
        }
示例#13
0
        public async Task <IResultModel> Upload(AttachmentUploadModel model, HttpRequest request)
        {
            var uploadModel = new FileUploadModel
            {
                Request  = request,
                FormFile = model.File,
                RootPath = _moduleCommonOptions.UploadPath,
                Module   = "Common",
                Group    = Path.Combine("Attachment", model.Module, model.Group)
            };

            //附件存储路径/Common/Attachment/{所属模块名称}/{所属分组模块}

            var result = await _fileUploadHelper.Upload(uploadModel);

            if (result.Successful)
            {
                var file   = result.Data;
                var entity = new AttachmentEntity
                {
                    Module   = model.Module,
                    Group    = model.Group,
                    FileName = file.FileName,
                    SaveName = file.SaveName,
                    Ext      = file.Ext,
                    Md5      = file.Md5,
                    Path     = file.Path,
                    FullPath = Path.Combine(file.Path, file.SaveName),
                    Size     = file.Size.Size,
                    SizeCn   = file.Size.ToString()
                };

                var mediaType = await _mediaTypeRepository.GetByExt(file.Ext);

                if (mediaType != null)
                {
                    entity.MediaType = mediaType.Value;
                }

                _uow.BeginTransaction();

                if (await _repository.AddAsync(entity))
                {
                    //如果需要授权访问附件,需要添加拥有者关联信息
                    if (!model.Auth || await _ownerRepository.AddAsync(new AttachmentOwnerEntity {
                        AttachmentId = entity.Id, AccountId = _loginInfo.AccountId
                    }))
                    {
                        _uow.Commit();

                        var resultModel = _mapper.Map <AttachmentUploadResultModel>(entity);
                        var url         = request.GetHost($"/common/attachment/download/{entity.Id}");
                        resultModel.Url = new Uri(url).ToString();

                        return(ResultModel.Success(resultModel));
                    }
                }
            }

            return(ResultModel.Failed("上传失败"));
        }
示例#14
0
        public ActionResult Create(ProductRuleModel model)
        {
            var admin = UserInfo.CurrentUserName;

            if (ModelState.IsValid)
            {
                var resultModel = new ResultModel();
                model.StarDate = DateTime.Parse(model.TempStarDate);
                model.EndDate  = DateTime.Parse(model.TempEndDate);

                if (model.ProductRuleId != 0)
                {
                    switch (model.SalesRuleId)
                    {
                    case 1:
                        model.StarDate = DateTime.Now;
                        model.EndDate  = DateTime.Now;
                        break;

                    default:
                        break;
                    }
                    model.SalesRuleId = (int)ESalesRule.Discount;
                    var resultUp = _productRuleService.Update(model);
                    if (resultUp.IsValid)
                    {
                        resultModel.IsValid  = true;
                        resultModel.Messages = new List <string> {
                            "Modify promotion information success"
                        };
                    }
                    else
                    {
                        resultModel.IsValid  = false;
                        resultModel.Messages = new List <string> {
                            resultUp.Messages[0]
                        };
                    }
                    var opera = string.Format("修改商品促销:ProductRuleId={0},操作结果:{1}", model.ProductRuleId, resultModel.IsValid ? "成功" : "失败");
                    LogPackage.InserAC_OperateLog(opera, "商品管理--商品促销");
                }
                else
                {
                    model.ProductRuleId = MemCacheFactory.GetCurrentMemCache().Increment("commonId");
                    model.SalesRuleId   = (int)ESalesRule.Discount;
                    var result = _productRuleService.Add(model);
                    if (result.IsValid)
                    {
                        resultModel.IsValid  = true;
                        resultModel.Messages = new List <string> {
                            "Add promotion information success"
                        };
                    }
                    else
                    {
                        resultModel.IsValid  = false;
                        resultModel.Messages = new List <string> {
                            result.Messages[0]
                        };
                    }
                }
                return(Json(resultModel, JsonRequestBehavior.AllowGet));
            }
            else
            {
                DrowSalesRuleList();
            }
            return(PartialView(model));
        }
示例#15
0
        public ResultModel FindPwd(string account)
        {
            ResultModel result = new ResultModel()
            {
                Status = false
            };

            try
            {
                TimeSpan ts        = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var      timeStamp = Convert.ToInt64(ts.TotalMilliseconds); //当前时间戳
                                                                            //重设密码链接地址和页面标签
                string email, uName;
                string password;

                var userInfo = S_UserInfoDal.GetUserByUserAccount(account);
                if (userInfo == null)
                {
                    result.Status = false;
                    result.ReMsg  = "账户不存在!";
                    return(result);
                }
                email    = userInfo.UserEmail;
                uName    = userInfo.UserName;
                password = userInfo.UserPwd;
                DateTime sendTime = DateTime.Now;



                int timeliness = int.Parse(Utility.GetConfigurationValue("Timeliness"));
                var param      = Utility.Encrypt(account + "|" + password + "|" + sendTime.AddMinutes(timeliness)).Replace("+", "%2B");

                var    resetPwd = string.Format("<a href='http://{0}/Account/ResetPassWord?u={1}'>立即重设></a>", HttpContext.Current.Request.Url.Authority, param);
                string msg      = "";
                //发送修改密码的邮件
                var isSuccess = Utility.SendMail(
                    email,
                    ref msg,
                    Utility.GetConfigurationValue("ForgetPwdTitle"),
                    Utility.GetConfigurationValue("ForgetPwdContent")
                    .Replace("name", uName)
                    .Replace("p", "<p/>")
                    .Replace("Reset", resetPwd)
                    .Replace("timeliness", timeliness.ToString())
                    );

                if (isSuccess)
                {
                    UpdateSendEmailTime(account, sendTime);
                    result.Status = true;
                }
                else
                {
                    result.ReMsg = "邮件发送失败:" + msg;
                }
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.ReMsg  = ex.Message;
            }
            return(result);
        }
示例#16
0
        public ResultModel Login(string userName, string password, bool isRememberLogin)
        {
            ResultModel rm = new ResultModel()
            {
                Status = false
            };

            try
            {
                S_UserInfoViewModel u = S_UserInfoDal.GetUserByUserAccount(userName);
                if (u == null)
                {
                    rm.ReMsg = "1|此账号不存在,请重新输入!";
                    return(rm);
                }
                password = Utility.Encrypt(password + u.UserSalt);
                if (u.UserPwd != password)
                {
                    rm.ReMsg = "2|密码不正确,请重新输入!";
                    return(rm);
                }

                if (u.UserStatus == "0")
                {
                    rm.ReMsg = "1|此账户已禁用,请联系管理员!";
                    return(rm);
                }

                if (u.UserClass == "" && u.RoleID == 0)
                {
                    rm.ReMsg = "1|此账户无权登陆,请联系管理员!";
                    return(rm);
                }


                if (u.UserClass.Contains("1"))
                {
                    u.RoleID = -1;   // -1 为超级管理员
                }
                List <S_TreeInfoViewModel> treeList = new List <S_TreeInfoViewModel>();
                treeList = treeInfoBiz.GetListByRoleId(u.RoleID);


                if (treeList.Count == 0)
                {
                    rm.ReMsg = "1|此账户无权登陆,请重新输入!";
                    return(rm);
                }

                var tree = treeList.Where(i => i.ParentID != 0).OrderBy(i => i.TreeSort).FirstOrDefault();

                rm.ReturnUrl = tree.TreeUrl + "?treeId=" + treeList.FirstOrDefault(i => i.TreeId == tree.ParentID).TreeId;

                SetUserID(u.UserId);

                SetRoleMenuInfo(new LoginUserViewModel
                {
                    UserAccount = u.UserAccount,
                    UserName    = u.UserName,
                    UserId      = u.UserId,
                    RoleName    = u.RoleName,
                    TreeInfo    = treeList
                });


                rm.Status = true;
            }
            catch (SqlException sqlException)
            {
                rm.ReMsg = sqlException.Message;
                Logger.Error(string.Format("[User]:Login:{0}", " Login Failed,userName:" + userName));
            }
            catch (Exception ex)
            {
                rm.ReMsg = ex.Message;
            }
            return(rm);
        }
示例#17
0
        ResultModel GetformatedHtmlContents(List <string> logContents)
        {
            ResultModel   resultModel = new ResultModel();
            StringBuilder contents    = new StringBuilder();

            contents.AppendLine(buildLogTextHelper.InsertHtmlStartform());
            int counter = 0; int idx = 0;

            try
            {
                bool isError = IsErrorInLog(logContents);

                if (isError)
                {
                    contents.Append(buildLogTextHelper.FailImage);
                    contents.Append(buildLogTextHelper.Extraspace);
                    resultModel.IsError   = isError;
                    resultModel.TaskColor = "Red";
                }
                else
                {
                    contents.Append(buildLogTextHelper.SuccessImage);
                    contents.Append(buildLogTextHelper.Extraspace);
                    resultModel.IsError   = isError;
                    resultModel.TaskColor = "Green";
                }

                counter = 0;//double check
                foreach (var str in logContents)
                {
                    if (counter.Equals(0))
                    {
                        if (str.Contains("Starting: "))
                        {
                            idx = str.IndexOf("Starting: ");
                            if (idx > 0)
                            {
                                resultModel.TaskName = str.Substring(idx, str.Length - idx);
                                if (isError)
                                {
                                    contents.Append(buildLogTextHelper.RedSpanStart);
                                }
                                else
                                {
                                    contents.Append(buildLogTextHelper.GreenSpanStart);
                                }
                                contents.Append($"{resultModel.TaskName}");
                                contents.Append(buildLogTextHelper.spanEnd);
                                contents.AppendLine(buildLogTextHelper.HtmlLineBreak);
                                contents.AppendLine(buildLogTextHelper.HtmlLineBreak);
                                counter++;
                                continue;
                            }
                        }
                    }

                    contents.AppendLine(str.ToString());
                    contents.AppendLine(buildLogTextHelper.HtmlLineBreak);
                    counter++;
                }
                contents.AppendLine(buildLogTextHelper.HtmlLineBreak);

                contents.AppendLine(buildLogTextHelper.InsertHtmlEndForm());
                resultModel.HtmContent = contents.ToString();
            }
            catch (Exception)
            {
            }

            return(resultModel);
        }
示例#18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    var candId  = Session["CandId"].ToString();
                    var batchId = Session["BatchId"].ToString();
                    var tenant  = SessionHelper.GetTenantID(Session);
                    using (QuizBookDbEntities1 _db = new QuizBookDbEntities1())
                    {
                        if (string.IsNullOrEmpty(tenant))
                        {
                            ErecruitHelper.SetErrorData(new NullReferenceException("There must be a valid Organisation"), Session);
                            Response.Redirect("ErrorPage.aspx", false);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(candId))
                            {
                                ErecruitHelper.SetErrorData(new NullReferenceException("There must be a valid candidate"), Session);
                                Response.Redirect("ErrorPage.aspx", false);
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(batchId))
                                {
                                    ErecruitHelper.SetErrorData(new NullReferenceException("There must be a valid Batch"), Session);
                                    Response.Redirect("ErrorPage.aspx", false);
                                }
                                else
                                {
                                    var cid = long.Parse(candId);
                                    var bid = long.Parse(batchId);
                                    var tid = long.Parse(tenant);

                                    var repM   = _db.TestResultReports.FirstOrDefault(s => s.candId == cid && s.batchId == bid && s.tenantId == tid);
                                    var repSum = _db.TestReportSummaries.FirstOrDefault(x => x.ReportId == repM.Id);
                                    var repAns = _db.TestReportAnswers.Where(x => x.ReportId == repM.Id).ToList();



                                    logoCt.Src = GetUrl("book.png");

                                    //var result = _db.IndividualTestResult_sp(bid, cid, tid).ToList();
                                    //var cand = result.FirstOrDefault();

                                    candidateId.Text   = repM.candidateId.ToUpper();
                                    candidateName.Text = repM.candidateName.ToUpper();
                                    batchName.Text     = repM.batchName.ToUpper();
                                    tenantName.Text    = repM.tenantName.ToUpper();
                                    tstDate.Text       = repM.tstDate;


                                    var forList = repAns.Select(x => new
                                    {
                                        sn            = x.sn,
                                        question      = x.question,
                                        Mark          = x.Mark,
                                        Score         = x.Score,
                                        chosenAnswer  = x.chosenAnswer,
                                        correctAnswer = x.correctAnswer,
                                        Status        = x.correct == "Correct" ? "<span style='color:#008000;'>Right</span>":x.correct == "Partial"? "<span style='color:#ffb400;'>Partial</span>": " <span style='color:#f00;'>Wrong</span>",
                                    }).ToList();



                                    //var forList = result.Select((s, i) => new
                                    //{
                                    //    sn = (i + 1).ToString(),
                                    //    Question = s.QuestionDetails,
                                    //    Answer = string.IsNullOrEmpty(s.ChosenAnswerDetails) ? "Unanswered" : s.ChosenAnswerDetails,
                                    //    CorrectAnswer = s.CorrectAnswer,
                                    //    Status = s.Correct.HasValue ? s.Correct.Value ? "<b style='color:green;'>Right</b>" : "<b style='color:red;'>Wrong</b>" : "<b style='color:red;'>Wrong</b>"
                                    //}).ToList();

                                    ResultList.DataSource = forList;
                                    ResultList.DataBind();

                                    var summary = new ResultModel
                                    {
                                        Correct           = repSum.Correct.Value,
                                        Partial           = repSum.Partial.Value,
                                        Wrong             = repSum.Wrong.Value,
                                        Unanswered        = repSum.Unanswered.Value,
                                        CorrectPercent    = repSum.CorrectPercent.Value,
                                        PartialPercent    = repSum.PartialPercent.Value,
                                        WrongPercent      = repSum.WrongPercent.Value,
                                        UnansweredPercent = repSum.UnansweredPercent.Value,
                                        CorrectCount      = repSum.CorrectCount.Value,
                                        PartialCount      = repSum.PartialCount.Value,
                                        WrongCount        = repSum.WrongCount.Value,
                                        UnansweredCount   = repSum.UnansweredCount.Value,
                                        questionCount     = repSum.questionCount.HasValue ? repSum.questionCount.Value:0,
                                        questionTotalMark = repSum.questionTotalMark.HasValue? repSum.questionTotalMark.Value:0,
                                        testDate          = repSum.testDate.Value
                                    };

                                    var totalQustionMark = forList.Sum(x => x.Mark);

                                    Correct.Text           = repM.Correct.ToString();
                                    Wrong.Text             = repM.Wrong.ToString();
                                    Partial.Text           = repM.Partial.ToString();
                                    Unanswered.Text        = repM.Unanswered.ToString();
                                    percentage.Text        = repM.percentage.ToString();
                                    result_correct.Text    = summary.Correct.ToString();
                                    result_partial.Text    = summary.Partial.ToString();
                                    result_wrong.Text      = summary.Wrong.ToString();
                                    result_unanswered.Text = summary.Unanswered.ToString();
                                    sumation_result.Text   = (summary.Correct + summary.Partial).ToString() + " out of " + totalQustionMark;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WSProfile filter = new WSProfile(System.Reflection.Assembly.GetExecutingAssembly().FullName.Split(',')[0], Path.GetFileName(Request.Url.AbsolutePath) + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name, ApplicationType.WebApplication);
                    filter.LogError(ex);
                    //ErecruitHelper.SetErrorData(ex, Session);
                    //Response.Redirect("ErrorPage.aspx", false);
                }
            }
        }
示例#19
0
        public async Task <IResultModel <Guid> > Add(AccountAddModel model, IUnitOfWork uow = null)
        {
            var result = new ResultModel <Guid>();

            var account = _mapper.Map <AccountEntity>(model);

            var exists = await Exists(account);

            if (!exists.Successful)
            {
                return(exists);
            }

            //默认未激活状态,用户首次登录激活
            account.Status = AccountStatus.Inactive;

            //设置默认密码
            if (account.Password.IsNull())
            {
                if (_options != null && _options.DefaultPassword.NotNull())
                {
                    account.Password = _options.DefaultPassword;
                }
                else
                {
                    account.Password = "******";
                }
            }

            account.Password = _passwordHandler.Encrypt(account.UserName, account.Password);

            //如果uow参数为空,需要自动处理工作单元
            var noUow = uow == null;

            if (noUow)
            {
                uow = _dbContext.NewUnitOfWork();
            }

            if (await _accountRepository.AddAsync(account, uow))
            {
                if (model.Roles != null && model.Roles.Any())
                {
                    var accountRoleList = model.Roles.Select(m => new AccountRoleEntity {
                        AccountId = account.Id, RoleId = m
                    }).ToList();
                    if (await _accountRoleRepository.AddAsync(accountRoleList, uow))
                    {
                        if (noUow)
                        {
                            uow.Commit();
                        }

                        return(result.Success(account.Id));
                    }
                }
                else
                {
                    if (noUow)
                    {
                        uow.Commit();
                    }

                    return(result.Success(account.Id));
                }
            }

            return(result.Failed());
        }
示例#20
0
 public IResultModel TypeSelect()
 {
     return(ResultModel.Success(EnumExtensions.ToResult <ConfigType>()));
 }
示例#21
0
        /// <summary>
        /// 获取用户信息(用于支付,配合GetYH_UserForPayment方法使用)
        /// </summary>
        /// <param name="userInfoView">用户信息</param>
        /// <param name="compareUserInfoView">用于比较的用户信息</param>
        /// <returns>是否可以支付</returns>
        private ResultModel GetYH_UserForPaymentMessagePrivate(UserInfoViewForPayment userInfoView,
                                                               UserInfoViewForPayment compareUserInfoView, dynamic db)
        {
            ResultModel resultModel = new ResultModel()
            {
                IsValid = false
            };

            if (userInfoView == null || userInfoView.IsDelete == 1)
            {
                //没有找到该用户
                resultModel.Messages.Add(CultureHelper.GetAPPLangSgring("USER_QUERY_NOT_FOUND", compareUserInfoView.LanguageId));
            }
            else
            {
                if (userInfoView.IsLock == 1)
                {
                    //账户被锁定,请联系客服
                    resultModel.Messages.Add(CultureHelper.GetAPPLangSgring("USER_QUERY_ACCOUNT_LOCKED", compareUserInfoView.LanguageId));
                }
                //进行密码检测
                else if (compareUserInfoView != null)
                {
                    if (string.IsNullOrEmpty(userInfoView.PayPassWord))
                    {
                        resultModel.Messages.Add(CultureHelper.GetAPPLangSgring("MONEY_ORDER_SETPAYPASSWORD", compareUserInfoView.LanguageId));
                    }
                    else
                    {
                        int passwordType = (int)UserEnums.PasswordType.PayPassword;

                        //查看是否有历史输入错误记录

                        List <YH_PasswordErrorModel> passwordErrors =
                            passwordErrorService.GetPasswordErrorInfo(userInfoView.UserID, passwordType, db).Data;

                        //交易密码错误信息
                        YH_PasswordErrorModel passwordErrorModel = null;
                        if (passwordErrors == null || passwordErrors.Count == 0)
                        {
                            //如果用户交易密码不同数据库交易密码
                            if (compareUserInfoView.PayPassWord != userInfoView.PayPassWord)
                            {
                                passwordErrorModel = new YH_PasswordErrorModel()
                                {
                                    Account         = userInfoView.Account,
                                    UserID          = userInfoView.UserID,
                                    VerifyTime      = DateTime.Now,
                                    PassWordType    = passwordType,
                                    FailVerifyTimes = 1
                                };
                                passwordErrorService.AddError(passwordErrorModel, db);
                                resultModel.Messages.Add(CultureHelper.GetAPPLangSgring("MONEY_ORDER_PAYPASSWORD_ERROR", compareUserInfoView.LanguageId));
                            }
                            else
                            {
                                resultModel.IsValid = true;
                            }
                        }
                        else
                        {
                            passwordErrorModel = passwordErrors[0];

                            //获取有关交易密码限制的参数
                            List <ParameterSetModel> payPwdParams =
                                parameterSetService.GetParameterSetsBy(new long[]
                            {
                                ParameterSetExtension.PARAM_PAYPASSWORD_TIME, ParameterSetExtension.PARAM_PAYPASSWORD_COUNT
                            }, db).Data;

                            //次数限制参数
                            ParameterSetModel payPwdCount =
                                payPwdParams.FirstOrDefault(
                                    x => x.ParamenterID == ParameterSetExtension.PARAM_PAYPASSWORD_COUNT);

                            //时间限制参数
                            ParameterSetModel payPwdTime =
                                payPwdParams.FirstOrDefault(
                                    x => x.ParamenterID == ParameterSetExtension.PARAM_PAYPASSWORD_TIME);

                            //限制次数
                            int count = payPwdCount == null ? 5 : Convert.ToInt32(payPwdCount.PValue);

                            //限制时间(分钟)
                            double time = payPwdTime == null ? 120 : Convert.ToDouble(payPwdTime.PValue);

                            //限制时间
                            DateTime limitTime = passwordErrorModel.VerifyTime.AddMinutes(time);

                            //交易密码是否正确
                            bool isPwdTrue = compareUserInfoView.PayPassWord == userInfoView.PayPassWord;

                            //错误次数等于限制次数 并且当前时间小于限制时间 则不允许进行交易密码验证
                            if (passwordErrorModel.FailVerifyTimes >= count &&
                                limitTime > DateTime.Now)
                            {
                                resultModel.Messages.Add(string.Format(CultureHelper.GetAPPLangSgring("MONEY_ORDER_PAYPASSWORDCOUNT", compareUserInfoView.LanguageId), count, Math.Ceiling((limitTime - DateTime.Now).TotalMinutes)));
                                return(resultModel);
                            }

                            if (!isPwdTrue)
                            {
                                if (passwordErrorModel.FailVerifyTimes >= count && limitTime <= DateTime.Now)
                                {
                                    //如果用户交易密码不同数据库交易密码,进行次数设置为1,验证时间为当前时间

                                    passwordErrorModel.FailVerifyTimes = 1;
                                    passwordErrorModel.VerifyTime      = DateTime.Now;
                                    passwordErrorService.Update(passwordErrorModel, db);
                                    resultModel.Messages.Add(CultureHelper.GetAPPLangSgring("MONEY_ORDER_PAYPASSWORD_ERROR", compareUserInfoView.LanguageId));
                                }
                                else if (passwordErrorModel.FailVerifyTimes < count)
                                {
                                    //如果用户交易密码不同数据库交易密码,进行次数设置为1,验证时间为当前时间

                                    passwordErrorModel.FailVerifyTimes = passwordErrorModel.FailVerifyTimes + 1;
                                    passwordErrorModel.VerifyTime      = DateTime.Now;
                                    passwordErrorService.Update(passwordErrorModel, db);
                                    resultModel.Messages.Add(CultureHelper.GetAPPLangSgring("MONEY_ORDER_PAYPASSWORD_ERROR", compareUserInfoView.LanguageId));
                                }
                                else
                                {
                                    resultModel.Messages.Add(CultureHelper.GetAPPLangSgring("MONEY_ORDER_PAYPASSWORD_ERROR", compareUserInfoView.LanguageId));
                                }
                            }
                            else
                            {
                                //将错误次数清空
                                passwordErrorModel.FailVerifyTimes = 0;
                                passwordErrorModel.VerifyTime      = DateTime.Now;
                                passwordErrorService.Update(passwordErrorModel, db);


                                resultModel.IsValid = true;
                            }
                        }
                    }
                }
                else
                {
                    resultModel.IsValid = true;
                }
            }
            return(resultModel);
        }
示例#22
0
        /// <summary>
        /// Remove a colony from the current ResultModel.
        /// </summary>
        /// <param name="x">Mouse X position.</param>
        /// <param name="y">Mouse Y position.</param>
        /// <param name="pictureBox">The current PictureBox that is used.</param>
        /// <param name="resultModel">The current used ResultModel.</param>
        // REMOVE COLONY FROM RESULT MODEL
        public static void RemoveKolonie(int x, int y, PictureBox pictureBox, ResultModel resultModel)
        {
            try
            {
                // GET RELATIVE POSITION
                int realX = TranslateZoomMousePosition(new System.Drawing.Point(x, y), pictureBox).X;
                int realY = TranslateZoomMousePosition(new System.Drawing.Point(x, y), pictureBox).Y;

                // CHECK MOUSE LOCATION TO COLONY LOCATION
                for (int i = 0; i < resultModel.ColonyList.Count; i++)
                {
                    if (ClickedOnColony(realX, realY, resultModel.ColonyList[i]))
                    {
                        resultModel.ColonyList.RemoveAt(i);
                        break;
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Verwijderen is mislukt.");
            }
        }
示例#23
0
        public ResultModel Get([FromQuery] QueryRitualMoney q)
        {
            ResultModel result = new ResultModel();

            if (!string.IsNullOrEmpty(q.Name))
            {
                q.Name = q.Name.Trim().ToUpper();
            }
            var query = from m in _context.members
                        where (string.IsNullOrEmpty(q.Name) ? true : m.Name.ToUpper().Contains(q.Name)) &&
                        (string.IsNullOrEmpty(q.Identity) ? true : m.Identity == q.Identity)
                        select m;

            //select new { m.Name, m.Identity };

            if (query.Count() == 0)
            {
                result.IsSuccess = true;
                result.Message   = "查無資料";
                return(result);
            }

            foreach (var i in query)
            {
                var records = _context.Entry(i)
                              .Collection(q => q.RitualMoneyRecords)
                              .Query()
                              .ToList();

                q.RitualMoneyRecords.AddRange(records);
            }

            if (q.Year != null)
            {
                //if (q.Year < 2019 || q.Year > 2029)
                //{
                //    result.IsSuccess = false;
                //    result.Message = "Input Year should be in range of 2019 to 2029.";
                //    return result;
                //}

                var copyList = new List <RitualMoneyRecord>(q.RitualMoneyRecords);
                //foreach (var j in q.RitualMoneyRecords) {
                //     if (DateTime.Parse(j.BorrowDate).Year != q.Year) {
                //         copyList.Remove(j);
                //     }
                // }
                foreach (var j in q.RitualMoneyRecords)
                {
                    if (j.BorrowDate.Year != q.Year)
                    {
                        copyList.Remove(j);
                    }
                }
                q.RitualMoneyRecords = copyList;
            }
            if (q.Month != null)
            {
                if (q.Month < 1 || q.Month > 12)
                {
                    result.IsSuccess = false;
                    result.Message   = "月份請輸入1~12月.";
                    return(result);
                }
                var copyList = new List <RitualMoneyRecord>(q.RitualMoneyRecords);
                foreach (var j in q.RitualMoneyRecords)
                {
                    //if (DateTime.Parse(j.BorrowDate).Month != q.Month)
                    //{
                    //    copyList.Remove(j);
                    //}
                    if (j.BorrowDate.Month != q.Month)
                    {
                        copyList.Remove(j);
                    }
                }
                q.RitualMoneyRecords = copyList;
            }

            result.IsSuccess = true;
            result.Data      = q.RitualMoneyRecords.OrderByDescending(o => o.RitualMoneyRecordId);

            return(result);
        }
示例#24
0
        public async Task <IResultModel> FamilyDelete(int id)
        {
            var result = await _familyRepository.DeleteAsync(id);

            return(ResultModel.Result(result));
        }
示例#25
0
        public async Task <IResultModel <ModuleBuildCodeResultModel> > BuildCode(Guid moduleId, IList <ClassEntity> classList = null)
        {
            var result = new ResultModel <ModuleBuildCodeResultModel>();

            var module = await _repository.GetAsync(moduleId);

            if (module == null)
            {
                return(result.Failed("模块不存在"));
            }

            //创建模块生成对象
            var moduleBuildModel = _mapper.Map <ModuleBuildModel>(module);

            moduleBuildModel.Prefix   = _codeGeneratorOptions.Prefix;
            moduleBuildModel.UiPrefix = _codeGeneratorOptions.UiPrefix;

            var id             = Guid.NewGuid().ToString();
            var rootPath       = _codeGeneratorOptions.BuildCodePath;
            var moduleFullName = $"{_codeGeneratorOptions.Prefix}.Module.{module.Code}";
            var buildModel     = new TemplateBuildModel
            {
                RootPath             = Path.Combine(rootPath, id, moduleFullName),
                NuGetPackageVersions = _nugetHelper.GetVersions()
            };

            if (classList == null)
            {
                //如果classList参数为null,表示生成整个解决方案
                buildModel.GenerateSln = true;
                classList = await _classRepository.QueryAllByModule(module.Id);
            }

            foreach (var classEntity in classList)
            {
                var classBuildModel = _mapper.Map <ClassBuildModel>(classEntity);
                var propertyList    = await _propertyRepository.QueryByClass(classEntity.Id);

                if (propertyList.Any())
                {
                    //查询属性
                    foreach (var propertyEntity in propertyList)
                    {
                        var propertyBuildModel = _mapper.Map <PropertyBuildModel>(propertyEntity);

                        //如果属性类型是枚举,查询枚举信息
                        if (propertyEntity.Type == PropertyType.Enum && propertyEntity.EnumId.NotEmpty())
                        {
                            var enumEntity = await _enumRepository.GetAsync(propertyEntity.EnumId);

                            propertyBuildModel.Enum = new EnumBuildModel
                            {
                                Name    = enumEntity.Name,
                                Remarks = enumEntity.Remarks
                            };

                            var enumItemList = await _enumItemRepository.QueryByEnum(propertyEntity.EnumId);

                            propertyBuildModel.Enum.ItemList = enumItemList.Select(m => new EnumItemBuildModel
                            {
                                Name    = m.Name,
                                Remarks = m.Remarks,
                                Value   = m.Value
                            }).ToList();
                        }

                        classBuildModel.PropertyList.Add(propertyBuildModel);
                    }
                }

                var modelPropertyList = await _modelPropertyRepository.QueryByClass(classEntity.Id);

                if (modelPropertyList.Any())
                {
                    foreach (var propertyEntity in modelPropertyList)
                    {
                        var modelPropertyBuildModel = _mapper.Map <ModelPropertyBuildModel>(propertyEntity);
                        //如果属性类型是枚举,查询枚举信息
                        if (propertyEntity.Type == PropertyType.Enum && propertyEntity.EnumId.NotEmpty())
                        {
                            var enumEntity = await _enumRepository.GetAsync(propertyEntity.EnumId);

                            modelPropertyBuildModel.Enum = new EnumBuildModel
                            {
                                Name    = enumEntity.Name,
                                Remarks = enumEntity.Remarks
                            };

                            var enumItemList = await _enumItemRepository.QueryByEnum(propertyEntity.EnumId);

                            modelPropertyBuildModel.Enum.ItemList = enumItemList.Select(m => new EnumItemBuildModel
                            {
                                Name    = m.Name,
                                Remarks = m.Remarks,
                                Value   = m.Value
                            }).ToList();
                        }

                        classBuildModel.ModelPropertyList.Add(modelPropertyBuildModel);
                    }
                }

                classBuildModel.Method = await _classMethodRepository.GetByClass(classEntity.Id);

                moduleBuildModel.ClassList.Add(classBuildModel);
            }

            buildModel.Module = moduleBuildModel;

            var builder = new DefaultTemplateBuilder();

            builder.Build(buildModel);

            var outputPath = Path.Combine(rootPath, id);

            ZipFile.CreateFromDirectory(outputPath, Path.Combine(rootPath, id + ".zip"));

            //删除临时文件
            Directory.Delete(outputPath, true);

            var resultModel = new ModuleBuildCodeResultModel
            {
                Id   = id,
                Name = moduleBuildModel.Name + ".zip"
            };

            return(result.Success(resultModel));
        }
示例#26
0
        /// <summary>
        /// Install gear settings
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual async Task <ResultModel> InstallAsync(SetupModel model)
        {
            var response = new ResultModel();
            var settings = GearWebApplication.Settings(_hostingEnvironment);

            TableQueryBuilder instance = null;

            switch (model.DataBaseType)
            {
            case DbProviderType.MsSqlServer:
                instance = new MsSqlTableQueryBuilder();
                settings.ConnectionStrings.Provider = DbProvider.SqlServer;
                break;

            case DbProviderType.PostgreSql:
                instance = new NpgTableQueryBuilder();
                settings.ConnectionStrings.Provider = DbProvider.PostgreSQL;
                break;
            }

            if (instance == null)
            {
                response.Errors.Add(new ErrorModel(string.Empty, "No provider registered"));
                return(response);
            }

            var(isConnected, error) = instance.IsSqlServerConnected(model.DatabaseConnectionString);
            if (!isConnected)
            {
                response.Errors.Add(new ErrorModel(string.Empty, error));
                return(response);
            }

            settings.ConnectionStrings.ConnectionString = model.DatabaseConnectionString;

            var tenantMachineName = TenantUtils.GetTenantMachineName(model.Organization.Name);

            if (string.IsNullOrEmpty(tenantMachineName))
            {
                response.Errors.Add(new ErrorModel(string.Empty, "Invalid name for organization"));
                return(response);
            }
            settings.IsConfigured = true;
            settings.SystemConfig.MachineIdentifier = $"_{tenantMachineName}_";
            var result = JsonConvert.SerializeObject(settings, Formatting.Indented);

            GearWebApplication.InitModulesMigrations();
            await System.IO.File.WriteAllTextAsync(ResourceProvider.AppSettingsFilepath(_hostingEnvironment), result);

            await _permissionService.SetOrResetPermissionsOnCacheAsync();

            var tenant =
                await _applicationDbContext.Tenants.FirstOrDefaultAsync(x => x.MachineName == tenantMachineName || x.Id == GearSettings.TenantId);

            if (tenant == null)
            {
                response.Errors.Add(new ErrorModel(string.Empty, "Something went wrong"));
                return(response);
            }

            tenant.Name    = model.Organization.Name;
            tenant.SiteWeb = model.Organization.SiteWeb;
            _applicationDbContext.Tenants.Update(tenant);

            //Set user settings
            var superUser = await _signInManager.UserManager.Users.FirstOrDefaultAsync();

            if (superUser != null)
            {
                superUser.UserName      = model.SysAdminProfile.UserName;
                superUser.Email         = model.SysAdminProfile.Email;
                superUser.UserFirstName = model.SysAdminProfile.FirstName;
                superUser.UserLastName  = model.SysAdminProfile.LastName;

                var hasher         = new PasswordHasher <GearUser>();
                var hashedPassword = hasher.HashPassword(superUser, model.SysAdminProfile.Password);
                superUser.PasswordHash = hashedPassword;
                await _signInManager.UserManager.UpdateAsync(superUser);
            }

            var contextRequest = await _applicationDbContext.PushAsync();

            if (!contextRequest.IsSuccess)
            {
                return(contextRequest);
            }

            GearApplication.BackgroundTaskQueue.PushBackgroundWorkItemInQueue(async x =>
            {
                var service = x.InjectService <IDynamicService>();
                //Register in memory types
                await service.RegisterInMemoryDynamicTypesAsync();
            });

            //Send welcome message to user
            await _notify.SendNotificationAsync(new List <Guid>
            {
                superUser?.Id.ToGuid() ?? Guid.Empty
            },
                                                new Notification
            {
                Subject            = $"Welcome to Gear App {model.SysAdminProfile.FirstName} {model.SysAdminProfile.LastName}",
                Content            = "The GEAR app is an integration system with your company's business, it has the skills to develop new applications, and allows you to create from the visual environment.",
                NotificationTypeId = NotificationType.Info
            });

            //sign in user
            await _signInManager.PasswordSignInAsync(superUser, model.SysAdminProfile.Password, true, false);

            response.IsSuccess = true;
            GearApplication.AppState.InstallOnProgress = false;
            GearApplication.AppState.Installed         = true;
            GearApplication.BackgroundTaskQueue.AddToExecutePendingBackgroundWorkItems();
            return(response);
        }
示例#27
0
        public async Task <IActionResult> Login(UserForLogin user, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(user));
            }

            ResultModel result = new ResultModel();

            var data = JsonConvert.SerializeObject(user);

            result = await _callApi.CallAPI(data, new Uri(_config["api"].ToString() + "/auth/login"), "POST");

            TempData["IsSuccess"] = result.IsSuccess;
            TempData["msg"]       = result.Message;

            if (result.IsSuccess)
            {
                var LoginUser = new LoginUser();
                LoginUser = JsonConvert.DeserializeObject <LoginUser>(result.Data.ToString());
                double LoginExpireMinute = Convert.ToDouble(_config["LoginExpireMinute"]);
                if (user.keepLogin)
                {
                    LoginExpireMinute = 43200;
                }
                var splitToken    = LoginUser.access_token.Split('.');
                var payloadBase64 = splitToken[1];
                payloadBase64 = payloadBase64.PadRight(payloadBase64.Length + (4 - payloadBase64.Length % 4) % 4, '=');
                var payloadText = Encoding.UTF8.GetString(Convert.FromBase64String(payloadBase64));

                var payload = new Payload();
                payload = JsonConvert.DeserializeObject <Payload>(payloadText);

                var Set_access_token  = new ResultModel();
                var Set_refresh_token = new ResultModel();
                var Cookieoptions     = new CookieOptions();
                Cookieoptions.Expires  = DateTime.Now.AddMinutes(LoginExpireMinute);
                Cookieoptions.SameSite = SameSiteMode.Strict;
                Cookieoptions.HttpOnly = true;

                Set_access_token  = _cookieHelper.Set("access_token", LoginUser.access_token, Cookieoptions);
                Set_refresh_token = _cookieHelper.Set("refresh_token", LoginUser.refresh_token, Cookieoptions);
                if (!Set_access_token.IsSuccess || !Set_refresh_token.IsSuccess)
                {
                    TempData["msg"] = "Write cookies error.";
                    return(View());
                }

                //建立 Claim,也就是要寫到 Cookie 的內容
                var claims = new[] { new Claim("UserId", payload.nameid.ToString()),
                                     new Claim("Name", payload.unique_name), };

                //建立證件,類似你的駕照或護照
                ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                //將 ClaimsIdentity 設定給 ClaimsPrincipal (持有者)
                ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);

                //登入動作
                await HttpContext.SignInAsync(principal, new AuthenticationProperties()
                {
                    //是否可以被刷新
                    AllowRefresh = true,
                    // 設置了一個 1 天 有效期的持久化 cookie
                    IsPersistent = user.keepLogin, //IsPersistent = false,瀏覽器關閉即刻登出
                    //用戶頁面停留太久,逾期時間,在此設定的話會覆蓋Startup.cs裡的逾期設定
                    ExpiresUtc = DateTime.Now.AddMinutes(LoginExpireMinute),
                });
            }


            if (!result.IsSuccess)
            {
                return(View(user));
            }

            if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));//導到原始要求網址
            }
            else
            {
                return(RedirectToAction("Index", "Home"));//到登入後的第一頁,自行決定
            }
        }
示例#28
0
        public async Task <IResultModel> Delete(Guid id)
        {
            var result = await _repository.DeleteAsync(id);

            return(ResultModel.Result(result));
        }
示例#29
0
    public void FailTest(ResultStatus resultStatus)
    {
        var result = ResultModel.Fail("test error", resultStatus);

        Assert.Equal(resultStatus, result.Status);
    }
示例#30
0
        /// <summary>
        /// Get request from KubeMQ and run the appropriate method
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private Response HandleIncomingRequest(RequestReceive request)
        {
            ResultModel result = new ResultModel();

            KubeMQ.MSMQSDK.Messages.Message MessageBody = null;
            _logger.LogDebug("Received Message from {0} for: {1} ", request.ReplyChannel, request.Metadata);
            try
            {
                _logger.LogInformation("Started Converting Object to request Message");
                MSMQMeta meta = new MSMQMeta();
                meta = meta.FromString(request.Metadata);
                switch (meta.ActionType)
                {
                case "Exists":
                    result = common.Exists(meta.Path);
                    break;

                case "Create":
                    result = common.CreateQueue(meta.Path);
                    break;

                case "Purge":
                    result = common.PurgeQueue(meta.Path);
                    break;

                case "Delete":
                    result = common.DeleteQueue(meta.Path);
                    break;

                case "Send":
                    MessageBody = Converter.FromByteArray(request.Body) as KubeMQ.MSMQSDK.Messages.Message;
                    result      = common.SendToQueue(meta, MessageBody);
                    break;

                case "Peek":
                    result = common.PeekQueue(meta.Path);
                    break;

                case "RegisterPeek":
                    result = common.PeekEvent(meta.Path, meta.ChannelToReturn);
                    break;

                case "UnRegisterPeek":
                    result = common.UnregisterPeek(meta.Path);
                    break;

                case "BeginPeek":
                    result = common.BeginPeek(meta.Path);
                    break;

                case "RegisterReceive":
                    result = common.EventReceive(meta.Path, meta.ChannelToReturn);
                    break;

                case "UnRegisterRecieve":
                    result = common.UnregisterReceive(meta.Path);
                    break;

                case "BeginReceive":
                    result = common.BeginRecieve(meta.Path);
                    break;

                case "SendJson":
                    string str = System.Text.Encoding.Default.GetString(request.Body);
                    result = common.SendJsonRequestToQueue(meta, str);
                    break;
                }
                if (result.exception != null)
                {
                    return(new Response(request)
                    {
                        Metadata = "Error",
                        Body = Converter.ToByteArray(result),
                        CacheHit = false,
                        ClientID = clientID,
                        Error = result.exception.ToString(),
                        Executed = false
                    });
                }
                else
                {
                    return(new Response(request)
                    {
                        Metadata = "Ok",
                        Body = Converter.ToByteArray(result),
                        CacheHit = false,
                        ClientID = clientID,
                        Executed = true,
                        Error = "none"
                    });
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogCritical(ex.ToString());
                return(null);
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex.ToString());
                return(null);
            }
        }
 private void castCallback(ResultModel result, Action <results.Medal.getList> handler)
 {
     results.Medal.getList r = (results.Medal.getList)result;
     handler(r);
 }
示例#32
0
        /// <summary>
        /// 验证当前调整课程-佟良远
        /// </summary>
        /// <param name="localID">本地方案ID</param>
        /// <param name="classID">班级ID</param>
        /// <param name="item">调整的项</param>
        /// <returns></returns>
        public static List <DayPeriodModel> CheckCanAdjustPosition(string localID, string classID, List <ResultDetailModel> item, ResultModel resultModel)
        {
            var positions = GetMovablePositons(localID, classID, item, resultModel);
            //单向检查结果
            List <DayPeriodModel> oneWayPositions = positions.Item1;
            //双向校验
            List <DayPeriodModel> twoWayPositions = new List <DayPeriodModel>();

            oneWayPositions?.ForEach(x =>
            {
                List <ResultDetailModel> targetItem = resultModel.ResultClasses.Where(rc => rc.ClassID == classID)?
                                                      .SelectMany(rc => rc.ResultDetails)?.ToList()?
                                                      .Where(rd => rd.DayPeriod.Day == x.Day && rd.DayPeriod.PeriodName == x.PeriodName)?.ToList();

                if ((targetItem?.Count() ?? 0) == 0)
                {
                    twoWayPositions.Add(x);
                }
                else
                {
                    Tuple <bool, string> checkresult = CanReplacePosition(localID, classID, item, targetItem, resultModel);
                    if (checkresult.Item1)
                    {
                        twoWayPositions.Add(x);
                    }
                }
            });

            #region 在返回结果中增加当前课位
            DayPeriodModel currentPosition = item?.FirstOrDefault()?.DayPeriod;
            if (currentPosition != null)
            {
                twoWayPositions = TimeOperation.TimeSlotUnion(twoWayPositions, new List <DayPeriodModel>()
                {
                    currentPosition
                });
            }
            #endregion

            return(twoWayPositions);
        }
示例#33
0
 public JsonResult FundBreakDownReport(FormCollection collection)
 {
     FundBreakDownModel model = new FundBreakDownModel();
     this.TryUpdateModel(model, collection);
     string error = string.Empty;
     ResultModel resultModel = new ResultModel();
     FundBreakDownReportDetail fundBreakDownReportDetail = null;
     if (ModelState.IsValid) {
         fundBreakDownReportDetail = ReportRepository.FindFundBreakDownReport(model.FundId);
     }
     else {
         foreach (var values in ModelState.Values.ToList()) {
             foreach (var err in values.Errors.ToList()) {
                 if (string.IsNullOrEmpty(err.ErrorMessage) == false) {
                     error += err.ErrorMessage + "\n";
                 }
             }
         }
     }
     return Json(new { Error = error, Data = fundBreakDownReportDetail }, JsonRequestBehavior.AllowGet);
 }
示例#34
0
        public void panel_Click(object sender, EventArgs e)
        {
            // SAVE CURRENT MODEL TO RESULT MODEL
            SaveToModel();

            if (inleesView.temporaryPanel != null)
            {
                inleesView.temporaryPanel.BorderStyle = System.Windows.Forms.BorderStyle.None;
            }
            //Set selection and remove selection from other
            Panel t = (Panel)sender;

            // SET CURRENT MODEL
            currentModel = mainController.resultModelList[(int)t.Tag];
            t.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            inleesView.currentResult = currentModel;
            inleesView.pictureBox.Image = inleesView.currentResult.ResultImage;
            inleesView.temporaryPanel = t;

            SetTextFields();
            inleesView.SetButtons(currentModel.Berekend);
            mainController.colonyController = new ColonyController();

            inleesView.OptionSelect = 0;
            inleesView.DrawCircles();
            inleesView.pictureBox.Invalidate();
            inleesView.erp.Clear();
            inleesView.ResetColorPanels();
        }
示例#35
0
 public JsonResult UnfundedCapitalCallBalanceReport(FormCollection collection)
 {
     UnfundedCapitalCallBalanceModel model = new UnfundedCapitalCallBalanceModel();
     this.TryUpdateModel(model, collection);
     string error = string.Empty;
     ResultModel resultModel = new ResultModel();
     FlexigridData flexgridData = new FlexigridData();
     int pageIndex = DataTypeHelper.ToInt32(collection["pageIndex"]);
     int pageSize = DataTypeHelper.ToInt32(collection["pageSize"]);
     string sortName = collection["sortName"];
     string sortOrder = collection["sortOrder"];
     int totalRows = 0;
     if (ModelState.IsValid) {
         List<UnfundedCapitalCallBalanceReportDetail> unfundedCapitalCallBalances = ReportRepository.FindUnfundedCapitalCallBalanceReport(pageIndex, pageSize, sortName, sortOrder, ref totalRows, model.FundId, (model.StartDate ?? Convert.ToDateTime("01/01/1900")), (model.EndDate ?? DateTime.Now));
         flexgridData.total = totalRows;
         flexgridData.page = 1;
         foreach (var unfundedCapitalCallBalance in unfundedCapitalCallBalances) {
             flexgridData.rows.Add(new FlexigridRow {
                 cell = new List<object> {
                    unfundedCapitalCallBalance.DealNo,
                    unfundedCapitalCallBalance.FundName,
                    unfundedCapitalCallBalance.UnfundedAmount
                 }
             });
         }
     }
     else {
         foreach (var values in ModelState.Values.ToList()) {
             foreach (var err in values.Errors.ToList()) {
                 if (string.IsNullOrEmpty(err.ErrorMessage) == false) {
                     error += err.ErrorMessage + "\n";
                 }
             }
         }
     }
     return Json(new { Error = error, Data = flexgridData, page = pageIndex, total = totalRows }, JsonRequestBehavior.AllowGet);
 }
示例#36
0
 public ActionResult ExportUnfundedCapitalCallBalanceDetail(FormCollection collection)
 {
     ExportUnfundedCapitalCallBalanceDetailModel model = new ExportUnfundedCapitalCallBalanceDetailModel();
     this.TryUpdateModel(model);
     if (ModelState.IsValid) {
         string error = string.Empty;
         ResultModel resultModel = new ResultModel();
         FlexigridData flexgridData = new FlexigridData();
         int pageIndex = DataTypeHelper.ToInt32(collection["pageIndex"]);
         int pageSize = DataTypeHelper.ToInt32(collection["pageSize"]);
         string sortName = collection["sortName"];
         string sortOrder = collection["sortOrder"];
         int totalRows = 0;
         model.UnfundedCapitalCallBalanceReportDetails = ReportRepository.FindUnfundedCapitalCallBalanceReport(pageIndex, pageSize, sortName, sortOrder, ref totalRows, model.FundId, (model.StartDate ?? Convert.ToDateTime("01/01/1900")), (model.EndDate ?? DateTime.Now));
     }
     if (model.UnfundedCapitalCallBalanceReportDetails == null)
         model.UnfundedCapitalCallBalanceReportDetails = new List<UnfundedCapitalCallBalanceReportDetail>();
     return View(model);
 }
示例#37
0
        public async Task <IResultModel> EducationDelete(int id)
        {
            var result = await _educationRepository.DeleteAsync(id);

            return(ResultModel.Result(result));
        }
示例#38
0
        public async Task <ResultModel> Put(int id, [FromBody] EditRecord editRecord)
        {
            var  result = new ResultModel();
            bool check  = false;

            //檢查是否空請求
            foreach (PropertyInfo property in editRecord.GetType().GetProperties())
            {
                if (property.GetValue(editRecord) != null)
                {
                    check = true;
                    break;
                }
            }
            if (check == false)
            {
                result.IsSuccess = false;
                result.Message   = "請輸入資料";
                return(result);
            }
            //================
            var recordToUpdate = _context.RitualMoneyRecords.FirstOrDefault(r => r.RitualMoneyRecordId == id);

            if (recordToUpdate != null)
            {
                //限制未還款的紀錄先去還款頁面處理
                if (recordToUpdate.IsReturn == false && editRecord.ReturnAmount != null)
                {
                    result.IsSuccess = false;
                    result.Message   = "尚有未還願的借用紀錄";
                    return(result);
                }
                if (editRecord.BorrowAmount != null)
                {
                    recordToUpdate.BorrowAmount = editRecord.BorrowAmount;
                }
                if (editRecord.ReturnAmount != null)
                {
                    recordToUpdate.ReturnAmount = editRecord.ReturnAmount;
                }
                try
                {
                    await _context.SaveChangesAsync();

                    result.IsSuccess = true;
                    result.Message   = "編輯成功";
                }
                catch (Exception e) {
                    result.IsSuccess = false;
                    result.Message   = "DB error.";
                }
            }
            else
            {
                result.Message   = "查無發財金紀錄";
                result.IsSuccess = false;
            }

            var accessToken = Request.Headers["Authorization"];
            var user        = await _TokenGetUserHelper.GetUser(accessToken);

            //logger.Info("userId=" + user.Id + ", username="******"\nEdit " + "RitualMoney id= " + recordToUpdate.RitualMoneyRecordId + " successfully.");


            return(result);
        }
示例#39
0
        public void BerekenKolonies(PictureBox picturebox, bool bgSelect, ResultModel resultModel)
        {
            try
            {
                ColonyController c = new ColonyController();
                c.RangeRed = new AForge.IntRange(239, 239);
                c.RangeGreen = new AForge.IntRange(228, 228);
                c.RangeBlue = new AForge.IntRange(176, 176);
                // PROCESS IMAGE
                resultModel.ColonyList = c.ProcessImage(picturebox, bgSelect);

                // SET AANTAL COUNTED CELLS
                resultModel.Kolonies = resultModel.ColonyList.Count;
                Console.WriteLine(resultModel.ColonyList.Count);
            }
            catch (Exception) { }
        }
示例#40
0
        /// <summary>
        /// Will make new List<float> which will contain the all the colony radius from a colony resultList. Will return the average of this resultList.
        /// </summary>
        /// <returns>A float that is the average radius of the radius of a colony resultList.</returns>
        public static float GetAverageRadius(ResultModel resultModel)
        {
            List<float> averageColonyRadius = new List<float>();

            foreach (ColonyModel colony in resultModel.ColonyList)
            {
                averageColonyRadius.Add(colony.Radius);
            }
            return averageColonyRadius.Average();
        }
示例#41
0
        public async Task <IResultModel <SystemConfigModel> > GetConfig(string host = null)
        {
            var result = new ResultModel <SystemConfigModel>();

            if (!_cache.TryGetValue(SystemConfigCacheKey, out SystemConfigModel model))
            {
                model = new SystemConfigModel();

                var configList = await _configRepository.QueryByPrefix(SystemConfigPrefix);

                foreach (var config in configList)
                {
                    switch (config.Key)
                    {
                    case SystemConfigKey.Title:
                        model.Title = config.Value;
                        break;

                    case SystemConfigKey.Logo:
                        model.Logo = config.Value;
                        break;

                    case SystemConfigKey.Home:
                        model.Home = config.Value;
                        break;

                    case SystemConfigKey.UserInfoPage:
                        model.UserInfoPage = config.Value;
                        break;

                    case SystemConfigKey.ButtonPermission:
                        model.ButtonPermission = config.Value.ToBool();
                        break;

                    case SystemConfigKey.Auditing:
                        model.Auditing = config.Value.ToBool();
                        break;

                    case SystemConfigKey.LoginVerifyCode:
                        model.LoginVerifyCode = config.Value.ToBool();
                        break;

                    case SystemConfigKey.ToolbarFullscreen:
                        model.Toolbar.Fullscreen = config.Value.ToBool();
                        break;

                    case SystemConfigKey.ToolbarSkin:
                        model.Toolbar.Skin = config.Value.ToBool();
                        break;

                    case SystemConfigKey.ToolbarLogout:
                        model.Toolbar.Logout = config.Value.ToBool();
                        break;

                    case SystemConfigKey.ToolbarUserInfo:
                        model.Toolbar.UserInfo = config.Value.ToBool();
                        break;

                    case SystemConfigKey.CustomCss:
                        model.CustomCss = config.Value;
                        break;
                    }
                }

                await _cache.SetAsync(SystemConfigCacheKey, model);
            }

            if (host.NotNull() && model.Logo.NotNull())
            {
                model.LogoUrl = new Uri($"{host}/upload/{model.Logo}").ToString().ToLower();
            }

            return(result.Success(model));
        }
 private void castCallback(ResultModel result, Action <results.Medal.unlock> handler)
 {
     results.Medal.unlock r = (results.Medal.unlock)result;
     handler(r);
 }
示例#43
0
        public async Task <IResultModel> GetLeaveInfo(int id)
        {
            var info = await _leaveInfoRepository.GetByEmployeeId(id);

            return(ResultModel.Success(info));
        }
示例#44
0
        //Loadpicture from an resultList of filenames
        public void LoadPictures(List<string> fileNames)
        {
            //String for failed files
            string faultyitems = "";

            foreach (string name in fileNames)
            {
                try
                {
                    if (!CheckIfPicLoaded(name))
                    {
                        image = new Bitmap(name);
                        ResultModel result = new ResultModel(image);
                        result.FilePath = name;
                        result.Index = mainController.resultModelList.Count;
                        //mainController.resultModelList.Insert(0, result);
                        mainController.resultModelList.Add(result);
                        mainController.inleesView.inleesImageView = new CustomPanelView();
                        result.panel.Click += new System.EventHandler(mainController.inleesViewController.panel_Click);

                    }
                }
                //Fills string with the path name of the failed file
                catch (ArgumentException)
                {
                    faultyitems = faultyitems + name + "\n";
                }
            }
            mainController.inleesViewController.AddPicture();
            //If there was an error it returns a messagebox with an string of the failed files and then restarts the method
            if (faultyitems != "")
            {
                MessageBox.Show("De volgende bestanden waren geen foto of waren corrupt: \n " + faultyitems);
                SelectPicture();
            }
            //File.Create(Application.StartupPath + "/Config.txt").Close();
        }
示例#45
0
        protected override ResultModel DoAfterUploadFile(string fullFileName)
        {
            try
            {
                ResultModel result = new ResultModel();
                result.message = "";
                //读取文件 excel
                DataTable dt = KGMFramework.WebApp.Library.ExcelHelper.ExcelImport(fullFileName, 0);
                if (dt == null || dt.Rows.Count == 0)
                {
                    result.bSuccess = false;
                    result.message  = "获取文件信息失败";
                    return(result);
                }

                List <Mst_GoodsInfo> GoodsList = new List <Mst_GoodsInfo>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Mst_GoodsInfo info = new Mst_GoodsInfo();
                    info.F_EnCode        = dt.Rows[i]["商品编码"].ToString();
                    info.F_FullName      = dt.Rows[i]["商品名称"].ToString();
                    info.F_SpecifModel   = dt.Rows[i]["规格型号"].ToString();
                    info.F_Unit          = dt.Rows[i]["单位"].ToString();
                    info.F_ShelfLife     = dt.Rows[i]["保质期(天)"].ToString();
                    info.F_SellingPrice  = dt.Rows[i]["销售价格(元)"].ToString();
                    info.F_PurchasePrice = dt.Rows[i]["采购价格(元)"].ToString();
                    info.F_BasicRate     = dt.Rows[i]["基本税率"].ToString();
                    info.F_Description   = dt.Rows[i]["备注"].ToString();
                    info.F_ProDate       = dt.Rows[i]["生产日期"].ToDate();
                    info.F_Long          = dt.Rows[i]["长度(cm)"].ToString();
                    info.F_Wide          = dt.Rows[i]["宽度(cm)"].ToString();
                    info.F_Height        = dt.Rows[i]["高度(cm)"].ToString();
                    info.F_NetWeight     = dt.Rows[i]["净重(kg)"].ToString();
                    info.F_GrossWeight   = dt.Rows[i]["毛重(kg)"].ToString();
                    info.F_Volume        = dt.Rows[i]["体积(cm²)"].ToString();
                    info.F_EnabledMark   = true;
                    SearchCondition search = new SearchCondition();
                    search.AddCondition("F_EnCode", dt.Rows[i]["商品编码"].ToString(), SqlOperator.Equal);
                    search.AddCondition("F_FullName", dt.Rows[i]["商品名称"].ToString(), SqlOperator.Equal);
                    List <Mst_GoodsInfo> infoList = BLLFactory <Mst_Goods> .Instance.Find(GetConditionStr(search));

                    if (infoList.Count > 0)
                    {
                        info.F_Id = infoList[0].F_Id;
                    }
                    GoodsList.Add(info);
                }
                BLLFactory <Mst_Goods> .Instance.InsertRange(GoodsList);

                result.bSuccess = true;
                result.message  = "导入成功";


                return(result);
            }
            catch (Exception)
            {
                ResultModel result = new ResultModel();
                result.bSuccess = true;
                result.message  = "导入失败";
                return(result);
            }
        }
示例#46
0
        //Get result from the database. ID = the id from the selected row.
        public ResultModel GetDataFromDataBase(int id)
        {
            ResultModel resultModel = new ResultModel();
            String Kolonie_positie = "";

            //If connection is closed > open..if open, skip
            int connOpen = 0;
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
                connOpen = 1;
            }

            //Query
            String query = @"SELECT * FROM Resultaat WHERE ID = @ID";

            SqlCommand cmd = new SqlCommand(query, connection);
            cmd.Parameters.Add(new SqlParameter("ID", id));

            //Read the result
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    resultModel.ID = (int)reader["ID"];
                    resultModel.Gebruiker = reader.GetString(1);
                    resultModel.Verdunning = (int)reader["Verdunning"];
                    resultModel.Kolonies = (int)reader["Kolonies"];
                    resultModel.Datum = (DateTime)reader["Datum"];
                    resultModel.Temperatuur = (int)reader["Temperatuur"];
                    resultModel.Soort = reader.GetString(6);
                    resultModel.Strain = reader.GetString(7);
                    resultModel.Tijdsduur = (int)reader["Tijdsduur"];
                    resultModel.Voedingsbodem = reader.GetString(9);
                    resultModel.Bron = reader.GetString(10).Trim();
                    resultModel.Medium = reader.GetString(11).Trim();
                    resultModel.Behandeling = reader["Behandeling"].ToString();
                    resultModel.FilePath = reader["Path"].ToString();
                    Kolonie_positie = reader["Kolonie_positie"].ToString();
                }

                // IF OPEN THEN CLOSE
                if (connOpen == 1)
                    connection.Close();
            }
            cmd.Parameters.Clear();
            Console.WriteLine(Kolonie_positie + "test");
            resultModel.ColonyList = GetColonyListFromString(Kolonie_positie);

            if (resultModel.ColonyList.Count > 0)
            {
                resultModel.Berekend = true;
            }

            return resultModel;
        }
示例#47
0
        public IResultModel UpdateConfig(SystemConfigModel model)
        {
            if (model == null)
            {
                return(ResultModel.Failed());
            }

            var tasks = new List <Task>();

            _uow.BeginTransaction();

            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Title,
                Value   = model.Title,
                Remarks = "系统标题"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Logo,
                Value   = model.Logo,
                Remarks = "系统Logo"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Home,
                Value   = model.Home,
                Remarks = "系统首页"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.UserInfoPage,
                Value   = model.UserInfoPage,
                Remarks = "个人信息页"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ButtonPermission,
                Value   = model.ButtonPermission.ToString(),
                Remarks = "启用按钮权限"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Auditing,
                Value   = model.Auditing.ToString(),
                Remarks = "启用审计日志"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.LoginVerifyCode,
                Value   = model.LoginVerifyCode.ToString(),
                Remarks = "启用登录验证码功能"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarFullscreen,
                Value   = model.Toolbar.Fullscreen.ToString(),
                Remarks = "显示工具栏全屏按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarSkin,
                Value   = model.Toolbar.Skin.ToString(),
                Remarks = "显示工具栏皮肤按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarLogout,
                Value   = model.Toolbar.Logout.ToString(),
                Remarks = "显示工具栏退出按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarUserInfo,
                Value   = model.Toolbar.UserInfo.ToString(),
                Remarks = "显示工具栏用户信息按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.CustomCss,
                Value   = model.CustomCss,
                Remarks = "自定义CSS样式"
            }));

            Task.WaitAll(tasks.ToArray());

            _uow.Commit();

            _cache.RemoveAsync(SystemConfigCacheKey).Wait();

            return(ResultModel.Success());
        }