Beispiel #1
0
        internal void ClearDay()
        {
            var file = XmlFiles[SelectedFileName];

            if (file.Exists)
            {
                // Show dialog result.
                if (!GetDialogResult("Are you sure you wish to wipe this day from history log?" +
                                     Environment.NewLine +
                                     "If the selected record is for today any current history will also be lost.",
                                     "Wipe day log?"))
                {
                    return;
                }

                // If the record is todays record, we want to clear global history as well
                // to prevent it re-saving on exit.
                if (Records.FirstOrDefault().Start.ToShortDateString() == DateTime.Now.ToShortDateString())
                {
                    Globals.History = new List <HistoryRecord>();
                }

                Records = new List <HistoryRecord>();
                file.Delete();
                GetHistoryLogs();

                SetTemporaryStatusMessage("Day erased from logs.");
            }
        }
Beispiel #2
0
        public Job AddJob(string name, IRule rule)
        {
            var record          = Records.FirstOrDefault(r => r.Name == name);
            var jobAlreadyAdded = Jobs.Any(j => j.Name == name);

            if (record != null && !jobAlreadyAdded)
            {
                var job = new Job(name, rule, record.Id);

                Jobs.Add(job);

                return(job);
            }

            if (jobAlreadyAdded)
            {
                throw new CoreException($"Job with name '{name}' already added.");
            }

            if (record == null)
            {
                throw new CoreException($"Job with name '{name}' cann't be added. No record in db.");
            }

            throw new CoreException($"Cann't register the job '{name}'");
        }
Beispiel #3
0
        public T FindById(string id)
        {
            Records.Clear();

            foreach (var record in this.Repository.GetRecords())
            {
                Records.Add(record);
            }

            if (Records.Count > 0)
            {
                var found = Records.FirstOrDefault(p => p._EntityId == id);
                if (found == null)
                {
                    throw new UnableToLocateRecordId($"Unable to locate record id '{id}'", null);
                }
                else
                {
                    return(found);
                }
            }

            if (id != "*")
            {
                throw new UnableToLocateRecordId($"Unable to locate record id '{id}'", null);
            }

            return(new T());
        }
Beispiel #4
0
 protected void SortRecordsAsFollowings(IEnumerable <TableRecord> records)
 {
     foreach (TableRecord tr in records)
     {
         TableRecord currentTr = Records.FirstOrDefault(r => r.teamId == tr.teamId);
         currentTr.Position = tr.Position;
     }
 }
        public async Task LoadAsync(ICoffeeListModeHandler coffeeListModeHandler)
        {
            _coffeeListModeHandler = coffeeListModeHandler;
            await _coffeeService.InitializeAsync();

            Records        = _coffeeService.Records;
            SelectedRecord = Records.FirstOrDefault();
        }
Beispiel #6
0
        private void Search(object obj)
        {
            var record = Records.FirstOrDefault(r => r.Person.Cnic == SearchText);

            if (record != null)
            {
                PhoneApplicationService.Current.State["person"] = record;
                _mainPage.NavigationService.Navigate(new Uri("/PersonView.xaml", UriKind.Relative));
            }
        }
Beispiel #7
0
        public ServiceModels.ServiceResponse MergeBoard(InputModels.MergeInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var fromBoard = Records.FirstOrDefault(b => b.Id == input.FromId);
            var toBoard   = Records.FirstOrDefault(b => b.Id == input.ToId);

            if (fromBoard is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.FromId}'");
            }

            if (toBoard is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.ToId}'");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var messageBoards = DbContext.MessageBoards.Where(m => m.BoardId == fromBoard.Id).ToList();

            // Reassign messages to new board
            foreach (var messageBoard in messageBoards)
            {
                messageBoard.BoardId = toBoard.Id;
                DbContext.Update(messageBoard);
            }

            DbContext.SaveChanges();

            var categoryId = fromBoard.CategoryId;

            // Delete the board
            DbContext.Boards.Remove(fromBoard);

            DbContext.SaveChanges();

            // Remove the category if empty
            if (!DbContext.Boards.Any(b => b.CategoryId == categoryId))
            {
                var categoryRecord = Categories.FirstOrDefault(item => item.Id == categoryId);

                if (categoryRecord != null)
                {
                    DbContext.Categories.Remove(categoryRecord);
                    DbContext.SaveChanges();
                }
            }

            return(serviceResponse);
        }
Beispiel #8
0
        public UserStatus FindUser(string username, string password)
        {
            var user = Records.FirstOrDefault(u => u.Username == username && u.Password == password);

            if (user == null)
            {
                return(UserStatus.InvalidUsernameOrPassword);
            }

            return(UserStatus.OK(user));
        }
Beispiel #9
0
 private void SetSingleGroupsAsResolved(IEnumerable <IGrouping <short, TableRecord> > groupedRecords)
 {
     foreach (IGrouping <short, TableRecord> groupedRecord in groupedRecords)
     {
         if (groupedRecord.Count() == 1)
         {
             TableRecord currentTr = Records.FirstOrDefault(r => r.teamId == groupedRecord.First().teamId);
             currentTr.PointsVirtual = ResolvedValue;
         }
     }
 }
        public RequestStatus AddRequest(Request request)
        {
            if (Records.FirstOrDefault(r => r.IssuerId == request.IssuerId) != null)
            {
                return(RequestStatus.RequestExists);
            }

            Insert(request);
            SaveChanges();

            return(RequestStatus.OK);
        }
Beispiel #11
0
        public UserStatus AddUser(User user)
        {
            if (Records.FirstOrDefault(u => u.Username == user.Username) != null)
            {
                return(UserStatus.UserExists(user.Username));
            }

            Insert(user);
            SaveChanges();

            return(UserStatus.OK(user));
        }
Beispiel #12
0
        public T First(Func <T, bool> predicate)
        {
            var record = Records.FirstOrDefault(predicate);

            if (record == default(T))
            {
                Log.LogError("No record was found matching the predicate.");
                throw new HttpNotFoundError();
            }

            return(record);
        }
Beispiel #13
0
        public string GetSetting(string name, bool forceGlobal)
        {
            var settingValue = string.Empty;

            if (!forceGlobal)
            {
                var userId = UserContext.ApplicationUser.Id;

                if (!UserSettings.ContainsKey(userId))
                {
                    lock (UserSettings) {
                        UserSettings.TryAdd(userId, new Dictionary <string, string>());
                    }
                }

                if (!UserSettings[userId].ContainsKey(name))
                {
                    var setting = Records.FirstOrDefault(r => r.Name == name && r.UserId == userId);

                    lock (UserSettings[userId]) {
                        if (!UserSettings[userId].ContainsKey(name))
                        {
                            UserSettings[userId].Add(name, setting?.Value ?? string.Empty);
                        }
                    }
                }

                UserSettings[userId].TryGetValue(name, out settingValue);
            }

            if (string.IsNullOrEmpty(settingValue))
            {
                if (!Settings.ContainsKey(name))
                {
                    var setting = Records.FirstOrDefault(r => r.Name == name && string.IsNullOrEmpty(r.UserId));

                    lock (Settings) {
                        if (!Settings.ContainsKey(name))
                        {
                            Settings.Add(name, setting?.Value ?? string.Empty);
                        }
                    }
                }

                Settings.TryGetValue(name, out settingValue);
            }

            return(settingValue);
        }
Beispiel #14
0
        /// <inheritdoc/>
        public bool Read()
        {
            if (_current == null)
            {
                _current = Records.FirstOrDefault();
                return(true);
            }
            var res = NextResult();

            if (res)
            {
                _current = Records[Records.IndexOf(_current) + 1];
            }
            return(res);
        }
Beispiel #15
0
        public ServiceModels.ServiceResponse MoveBoardUp(int id)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var targetBoard = Records.FirstOrDefault(b => b.Id == id);

            if (targetBoard is null)
            {
                serviceResponse.Error("No board found with that ID.");
                return(serviceResponse);
            }

            var categoryBoards = Records.Where(b => b.CategoryId == targetBoard.CategoryId).OrderBy(b => b.DisplayOrder).ToList();

            var currentIndex = 1;

            foreach (var board in categoryBoards)
            {
                board.DisplayOrder = currentIndex++;
                DbContext.Update(board);
            }

            DbContext.SaveChanges();

            targetBoard = categoryBoards.First(b => b.Id == id);

            if (targetBoard.DisplayOrder > 1)
            {
                var displacedBoard = categoryBoards.FirstOrDefault(b => b.DisplayOrder == targetBoard.DisplayOrder - 1);

                if (displacedBoard != null)
                {
                    displacedBoard.DisplayOrder++;
                    DbContext.Update(displacedBoard);
                }

                targetBoard.DisplayOrder--;
                DbContext.Update(targetBoard);

                DbContext.SaveChanges();
            }
            else
            {
                targetBoard.DisplayOrder = 2;
            }

            return(serviceResponse);
        }
Beispiel #16
0
        public void LoadRecordsToList(IEnumerable <RecordViewModel> records)
        {
            SelectedRecord = null;
            Records.Clear();
            Records.AddRange(records);

            if (_recordToSelect >= 0)
            {
                SelectedRecord  = Records.First(r => r.Id == _recordToSelect);
                _recordToSelect = -1;
            }
            else
            {
                SelectedRecord = Records.FirstOrDefault();
            }
        }
Beispiel #17
0
        private void ReadXml(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                Records        = new List <HistoryRecord>();
                SelectedRecord = new HistoryRecord();
                return;
            }

            FileInfo file = XmlFiles[fileName];
            var      temp = new List <HistoryRecord>();

            Globals.XmlToHistory(file.FullName, out temp);

            Records        = temp;
            SelectedRecord = Records.FirstOrDefault();
        }
Beispiel #18
0
        public virtual T FindRecord(Type type, bool exactMatch = false)
        {
            T result;

            result = default(T);

            if (type == null)
            {
                // PrintError

                goto Cleanup;
            }

            result = Records.FirstOrDefault(r => exactMatch ? r.GetType().GetInterfaces(false).Contains(type) : type.IsInstanceOfType(r));

Cleanup:

            return(result);
        }
Beispiel #19
0
        public void UpdateUserSettings(InputModels.UpdateAccountInput input)
        {
            var existingRecords = Records.Where(s => s.UserId == input.Id).ToList();

            if (existingRecords.Any())
            {
                DbContext.RemoveRange(existingRecords);
            }

            foreach (var settingInput in input.Settings)
            {
                if (string.IsNullOrEmpty(settingInput.Value))
                {
                    continue;
                }

                var siteSetting = Records.FirstOrDefault(s => !s.AdminOnly && s.Name == settingInput.Key && string.IsNullOrEmpty(s.UserId));

                if (siteSetting != null)
                {
                    var baseSetting = BaseSettings.Get(siteSetting.Name);

                    if (baseSetting.Options != null && !baseSetting.Options.Contains(settingInput.Value))
                    {
                        throw new HttpBadRequestError();
                    }

                    var record = new DataModels.SiteSetting {
                        UserId    = input.Id,
                        Name      = siteSetting.Name,
                        Value     = settingInput.Value,
                        AdminOnly = siteSetting.AdminOnly
                    };

                    DbContext.SiteSettings.Add(record);
                }
            }

            DbContext.SaveChanges();
        }
Beispiel #20
0
        public virtual T FindRecord(long uid)
        {
            T    result;
            long h, i;

            result = default(T);

            h = Array.FindIndex(Cache, r => r != null && r.Uid == uid);

            if (h >= 0)
            {
                result = Cache[h];
            }

            if (result == null)
            {
                result = Records.FirstOrDefault(r => r.Uid == uid);
            }

            if (result != null)
            {
                if (h == -1)
                {
                    h = Cache.Length - 1;
                }

                for (i = h - 1; i >= 0; i--)
                {
                    Cache[i + 1] = Cache[i];
                }

                Cache[0] = result;
            }

            return(result);
        }
Beispiel #21
0
 public Stock GetBySymbol(string symbol)
 {
     return(Records.FirstOrDefault(c => c.Symbol == symbol));
 }
 public pocoBase Find(Guid id) => Records.FirstOrDefault(item => item.ID == id);
        public IResponse <ApiResponse> CalculateAttendence()
        {
            StringBuilder XmlBuilder  = null;
            int           AbsentCount = 0;
            IList <AttendenceReporter> ObjAttendenceReporterList = null;
            AttendenceReporter         ObjAttendenceReporter     = null;
            DateTime?AttendenceReportedDate = null;
            string   XmlData = null;
            string   Result  = null;
            DataSet  ds      = ObjAttendenceService.AttendeceReportService("sp_ClassDetails_GetUid", null);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                ObjAttendenceReporterList = new List <AttendenceReporter>();
                int    ClassUid       = 0;
                string ClassDetailUid = null;
                while (ClassUid < ds.Tables[0].Rows.Count)
                {
                    ClassDetailUid = null;
                    if (!string.IsNullOrEmpty(ds.Tables[0].Rows[ClassUid]["ClassDetailId"].ToString()))
                    {
                        ClassDetailUid = ds.Tables[0].Rows[ClassUid]["ClassDetailId"].ToString();
                        DataSet AttendenceSet = ObjAttendenceService.AttendeceReportService("sp_AttendenceAll_ByClassDetailUid", ClassDetailUid);
                        if (AttendenceSet.Tables.Count != 0 && AttendenceSet.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dr in AttendenceSet.Tables[0].Rows)
                            {
                                if (dr[6] != DBNull.Value)
                                {
                                    AttendenceReportedDate = Convert.ToDateTime(dr[6]);
                                    var CurrentWorkingMonthStartDay = new DateTime(AttendenceReportedDate.Value.Year, AttendenceReportedDate.Value.Month, 1);
                                    int TotalDays   = DateTime.DaysInMonth(CurrentWorkingMonthStartDay.Year, CurrentWorkingMonthStartDay.Month);
                                    int CurrentDays = 1;
                                    while (CurrentDays <= TotalDays)
                                    {
                                        var CurrentWorkingDay = new DateTime(AttendenceReportedDate.Value.Year, AttendenceReportedDate.Value.Month, CurrentDays);
                                        if (CurrentWorkingDay.DayOfWeek.ToString() != "Saturday" && CurrentWorkingDay.DayOfWeek.ToString() != "Sunday")
                                        {
                                            if (Convert.ToInt32(dr[CurrentDays + 6]) == 0)
                                            {
                                                AbsentCount++;
                                            }
                                        }
                                        CurrentDays++;
                                    }

                                    if (AbsentCount > 0)
                                    {
                                        ObjAttendenceReporter                = new AttendenceReporter();
                                        ObjAttendenceReporter.Year           = CurrentWorkingMonthStartDay.Year.ToString();
                                        ObjAttendenceReporter.Month          = CurrentWorkingMonthStartDay.Month.ToString();
                                        ObjAttendenceReporter.StudentUid     = dr[3].ToString();
                                        ObjAttendenceReporter.TenentId       = dr[1].ToString();
                                        ObjAttendenceReporter.MonthName      = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(CurrentWorkingMonthStartDay.Month);
                                        ObjAttendenceReporter.TotalAbs       = AbsentCount;
                                        ObjAttendenceReporter.ClassDetailUid = ClassDetailUid;
                                        ObjAttendenceReporterList.Add(ObjAttendenceReporter);
                                        AbsentCount = 0;
                                    }
                                }
                            }
                        }
                    }
                    ClassUid++;
                }
            }

            if (ObjAttendenceReporterList != null && ObjAttendenceReporterList.Count() > 0)
            {
                int    TotalWorkingDaysTillDate = TotalWorkingDaysTillDateFun(new DateTime(2018, 3, 1), DateTime.Now);
                string PreXmlSample             = "<field id=\"AbsentInJanuary\"></field>" +
                                                  "<field id=\"AbsentInFebruary\"></field>" +
                                                  "<field id =\"AbsentInMarch\"></field>" +
                                                  "<field id=\"AbsentInApril\"></field>" +
                                                  "<field id=\"AbsentInMay\"></field>" +
                                                  "<field id=\"AbsentInJune\"></field>" +
                                                  "<field id =\"AbsentInJuly\"></field>" +
                                                  "<field id=\"AbsentInAugust\"></field>" +
                                                  "<field id=\"AbsentInSeptember\"></field>" +
                                                  "<field id=\"AbsentInOctober\"></field>" +
                                                  "<field id=\"AbsentInNovember\"></field>" +
                                                  "<field id=\"AbsentInDecember\"></field>";

                XmlBuilder = new StringBuilder();
                XmlBuilder.Append("<? xml version=\"1.0\"?>");
                var AttendenceByGroup = ObjAttendenceReporterList.GroupBy(x => x.StudentUid);
                foreach (var Records in AttendenceByGroup)
                {
                    var TotalAbsent = Records.Sum(x => x.TotalAbs);
                    XmlBuilder.Append("<row>");
                    XmlBuilder.Append("<field id=\"StudentUid\">" + Records.FirstOrDefault().StudentUid + "</field>");
                    XmlBuilder.Append("<field id=\"TenentUid\">" + Records.FirstOrDefault().TenentId + "</field>");
                    XmlBuilder.Append("<field id=\"TotalWorkingDays\">" + TotalWorkingDaysTillDate + "</field>");
                    XmlBuilder.Append("<field id=\"TotalAbsent\">" + TotalAbsent + "</field>");
                    XmlBuilder.Append("<field id=\"AppliedLeavesUid\"></field>");
                    XmlBuilder.Append("<field id=\"ClassDetailId\">" + Records.FirstOrDefault().ClassDetailUid + "</field>");
                    string ActualXmlData = PreXmlSample;
                    foreach (var Item in Records)
                    {
                        if (ActualXmlData.IndexOf(Item.MonthName) != -1)
                        {
                            ActualXmlData = ActualXmlData.Replace(Item.MonthName + "\">", Item.MonthName + "\">" + Item.TotalAbs.ToString());
                        }
                    }
                    XmlBuilder.Append(ActualXmlData);
                    XmlBuilder.Append("</row>");
                    ActualXmlData = null;
                }

                XmlData = XmlBuilder.ToString();
                Result  = ObjAttendenceService.CalculatedAttendenceBulkUpload(XmlData);
                return(null);// Json(new { status = 200 }, JsonRequestBehavior.AllowGet);
            }

            return(null);// Json(new { status = 500 }, JsonRequestBehavior.AllowGet);
        }
Beispiel #24
0
 private RecordNode GetRecordByName(string recordName)
 {
     return(Records.FirstOrDefault(record => record.Name == recordName));
 }
Beispiel #25
0
        public async Task SaveTestSessionOverView()
        {
            await Task.Delay(0);

            if (commonDataService.StudentTestFormOverview != null)
            {
                var model = JsonConvert.DeserializeObject <FormParamterClass>(commonDataService.StudentTestFormOverview.formParameters);
                model.ProgramLabelId = null;
                var programSelected = ProgramNoteList.FirstOrDefault(p => p.selected);
                if (programSelected != null && model.ProgramLabelId != programSelected.id)
                {
                    model.ProgramLabelId = programSelected.id;
                }
                commonDataService.StudentTestFormOverview.formParameters = JsonConvert.SerializeObject(model);
            }
            IsOverviewChanged = false;
            if (commonDataService.StudentTestForms != null && commonDataService.StudentTestForms.Any())
            {
                if (commonDataService.IsCompleteForm)
                {
                    foreach (var item in commonDataService.StudentTestForms)
                    {
                        var str        = item.rawScore.HasValue ? item.rawScore.Value + "" : "";
                        var testrecord = TestSessionRecords.FirstOrDefault(p => p.ContentCategoryId == item.contentCategoryId);
                        if (testrecord != null && (testrecord.TestDate != item.testDate || testrecord.RawScore != str || testrecord.ExaminerID != item.examinerId))
                        {
                            IsOverviewChanged = true;
                            break;
                        }
                    }
                }
                else if (commonDataService.IsAcademicForm)
                {
                    foreach (var item in commonDataService.StudentTestForms)
                    {
                        var str        = item.rawScore != null && item.rawScore.HasValue ? item.rawScore.Value + "" : "";
                        var testrecord = AcademicTestSessionRecords.FirstOrDefault(p => p.ContentCategoryId == item.contentCategoryId);
                        if (testrecord != null && (testrecord.TestDate != item.testDate || testrecord.RawScore != str || testrecord.ExaminerID != item.examinerId))
                        {
                            IsOverviewChanged = true;
                            break;
                        }
                    }

                    if (!IsOverviewChanged)
                    {
                        var testRecord = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == 162);
                        if (testRecord != null)
                        {
                            var overviewrecord = AcademicTestSessionRecords.FirstOrDefault(p => p.ContentCategoryId == 162);
                            if (overviewrecord != null)
                            {
                                if (!overviewrecord.ShowTimerErrorMessage && !testRecord.TimeTaken.HasValue)
                                {
                                    IsOverviewChanged = true;
                                }
                                else if (overviewrecord.ShowTimerErrorMessage && testRecord.TimeTaken.HasValue)
                                {
                                    IsOverviewChanged = true;
                                }
                                else if (!overviewrecord.ShowTimerErrorMessage && testRecord.TimeTaken.HasValue && testRecord.TimeTaken.Value != Convert.ToInt32(overviewrecord.Timer.TotalSeconds))
                                {
                                    IsOverviewChanged = true;
                                }
                                else if (!overviewrecord.ShowTimerErrorMessage && !testRecord.TimeTaken.HasValue)
                                {
                                    IsOverviewChanged = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (var item in commonDataService.StudentTestForms)
                    {
                        var str        = item.rawScore.HasValue ? item.rawScore.Value + "" : "";
                        var testrecord = Records.FirstOrDefault(p => p.ContentCategoryId == item.contentCategoryId);
                        if (testrecord != null && (testrecord.TestDate != item.testDate || testrecord.RawScore != str || testrecord.ExaminerID != item.examinerId))
                        {
                            IsOverviewChanged = true;
                            break;
                        }
                    }
                }
            }
            if (IsOverviewChanged)
            {
                //studentTestFormsService.DeleteAll(LocalformInstanceId);
                if (commonDataService.IsCompleteForm)
                {
                    if (TestSessionRecords != null && TestSessionRecords.Any())
                    {
                        var lstStudentTestForms = new List <StudentTestForms>();
                        foreach (var item in TestSessionRecords)
                        {
                            if (!item.IsDateVisible)
                            {
                                continue;
                            }
                            var StudentTestForms = new StudentTestForms();
                            StudentTestForms.IsBaselCeilingApplied  = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).IsBaselCeilingApplied;
                            StudentTestForms.BaselCeilingReached    = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).BaselCeilingReached;
                            StudentTestForms.LocalStudentTestFormId = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).LocalStudentTestFormId;
                            StudentTestForms.LocalformInstanceId    = LocalformInstanceId;
                            StudentTestForms.testDate        = item.TestDate;
                            StudentTestForms.Notes           = item.Notes;
                            StudentTestForms.TSOStatus       = item.Status;
                            StudentTestForms.rawScore        = !string.IsNullOrEmpty(item.RawScore) ? Convert.ToInt32(item.RawScore) : default(int?);
                            StudentTestForms.rawScoreEnabled = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).rawScoreEnabled;
                            if (item.Examiner != null && item.Examiner != "Select Examiner")
                            {
                                StudentTestForms.examinerId = Convert.ToInt32(commonDataService.SearchStaffResponseModel.FirstOrDefault(p => p.FirstNameLastName == item.Examiner).UserID);
                            }
                            StudentTestForms.contentCategoryId = item.ContentCategoryId;
                            StudentTestForms.createDate        = DateTime.Now;
                            lstStudentTestForms.Add(StudentTestForms);
                        }
                        //studentTestFormsService.InsertAll(lstStudentTestForms);
                        commonDataService.StudentTestForms = new List <StudentTestForms>(lstStudentTestForms);
                    }
                }
                else if (commonDataService.IsAcademicForm)
                {
                    if (AcademicTestSessionRecords != null && AcademicTestSessionRecords.Any())
                    {
                        var lstStudentTestForms = new List <StudentTestForms>();
                        foreach (var item in AcademicTestSessionRecords)
                        {
                            if (!item.DomainVisibility)
                            {
                                continue;
                            }
                            var StudentTestForms = new StudentTestForms();
                            StudentTestForms.IsBaselCeilingApplied  = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).IsBaselCeilingApplied;
                            StudentTestForms.BaselCeilingReached    = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).BaselCeilingReached;
                            StudentTestForms.LocalformInstanceId    = LocalformInstanceId;
                            StudentTestForms.LocalStudentTestFormId = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).LocalStudentTestFormId;
                            StudentTestForms.testDate = item.TestDate;
                            if (item.ContentCategoryId == 162)
                            {
                                if (!item.ShowTimerErrorMessage)
                                {
                                    StudentTestForms.TimeTaken = Convert.ToInt32(item.Timer.TotalSeconds);
                                }
                                else
                                {
                                    StudentTestForms.TimeTaken = null;
                                }
                            }
                            StudentTestForms.Notes           = item.Notes;
                            StudentTestForms.TSOStatus       = item.Status;
                            StudentTestForms.rawScore        = !string.IsNullOrEmpty(item.RawScore) ? Convert.ToInt32(item.RawScore) : default(int?);
                            StudentTestForms.rawScoreEnabled = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).rawScoreEnabled;
                            if (item.Examiner != null && item.Examiner != "Select Examiner")
                            {
                                StudentTestForms.examinerId = Convert.ToInt32(commonDataService.SearchStaffResponseModel.FirstOrDefault(p => p.FirstNameLastName == item.Examiner).UserID);
                            }
                            StudentTestForms.contentCategoryId = item.ContentCategoryId;
                            StudentTestForms.createDate        = DateTime.Now;
                            lstStudentTestForms.Add(StudentTestForms);
                        }
                        //studentTestFormsService.InsertAll(lstStudentTestForms);
                        commonDataService.StudentTestForms = new List <StudentTestForms>(lstStudentTestForms);
                    }
                }
                else
                {
                    var lstStudentTestForms = new List <StudentTestForms>();
                    foreach (var item in Records)
                    {
                        if (!item.IsDateVisible)
                        {
                            continue;
                        }
                        var StudentTestForms = new StudentTestForms();
                        StudentTestForms.IsBaselCeilingApplied  = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).IsBaselCeilingApplied;
                        StudentTestForms.BaselCeilingReached    = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).BaselCeilingReached;
                        StudentTestForms.LocalformInstanceId    = LocalformInstanceId;
                        StudentTestForms.LocalStudentTestFormId = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).LocalStudentTestFormId;
                        StudentTestForms.testDate        = item.TestDate;
                        StudentTestForms.Notes           = item.Notes;
                        StudentTestForms.TSOStatus       = item.Status;
                        StudentTestForms.rawScore        = !string.IsNullOrEmpty(item.RawScore) ? Convert.ToInt32(item.RawScore) : default(int?);
                        StudentTestForms.rawScoreEnabled = commonDataService.StudentTestForms.FirstOrDefault(p => p.contentCategoryId == item.ContentCategoryId).rawScoreEnabled;
                        if (item.Examiner != null && item.Examiner != "Select Examiner")
                        {
                            StudentTestForms.examinerId = Convert.ToInt32(commonDataService.SearchStaffResponseModel.FirstOrDefault(p => p.FirstNameLastName == item.Examiner).UserID);
                        }
                        StudentTestForms.contentCategoryId = item.ContentCategoryId;
                        StudentTestForms.createDate        = DateTime.Now;
                        lstStudentTestForms.Add(StudentTestForms);
                    }
                    commonDataService.StudentTestForms = new List <StudentTestForms>(lstStudentTestForms);
                }
                commonDataService.ResetTestDate?.Invoke();
            }
        }
Beispiel #26
0
		public void EvalReportInfo(ReportName reportName, ScaffoldContext context, ReportDates reportDates,
			int currShiftIndex=-1,
			int export_excel = 0,			
			string selectedSortOfProduction=null,
			string[] baseStrings=null,//хранится выгрузки в base64 рисунки графиков			
			Controller curr_controller = null
			)
		{
			//В некоторых случаях, вроде экспорта в эксель, можно использовать уже вычисленные данные
			if (
			#region IsNeedCachedDateForReport
				(this.Successfull
				&&(export_excel==1
					&&!ReportListForRebuildForExcel.Contains(reportName.Eng))//Некоторые отчёты требуют не округлённые данные для экселя, так что формируем их заново
					|| shiftsReportNames.Contains(reportName.Eng))//Или для смен
				&& this.ReportName != null
				&& reportName.Eng == this.ReportName.Eng
				&& this.ReportDates.StartDate == reportDates.StartDate
				&& this.ReportDates.EndDate == reportDates.EndDate
			#endregion
				)
			{
				//Данные по сменам формируются из списка смен в периоде, но выводится только одна, так что обновляем эти данные
				if (shiftsReportNames.Contains(reportName.Eng))
				{
					this.CurrShiftIndex = currShiftIndex;
					ReportDates.RecalcShiftsDate(this);//Пересчитываем края текущей смены					
				}
				if (baseStrings != null)
				{
					this.BaseStrings = baseStrings;
				}
				this.SelectedSortOfProduction = selectedSortOfProduction;
				return;
			}
			#region init var
			this.Successfull = false;
			this.stopwatch.Restart();


			this.CurrShiftIndex = currShiftIndex;
			this.ReportDates = reportDates;
			this.SelectedSortOfProduction = selectedSortOfProduction;
			this.BaseStrings = baseStrings;
			this.ReportName = reportName;
			
			this.Dbcontext = context;			
			this.Curr_controller = curr_controller;
			
			this.IsByDay = IsByDay_report_list.Contains(reportName.Eng);
			isBDM1 = BDM1_reports_list.Contains(reportName.Eng);
			this.PlaceName = isBDM1 ? "БДМ-1" : "БДМ-2";			
			placeId = isBDM1 ? 1:2;
			
			

			this.roundNum = 3;
			this.Sums = new Dictionary<string, double[]>();			
			this.Records_List = new Dictionary<string, List<object>>();
			this.Records = new List<object>();
			#endregion
			switch (reportName.Eng)//на основе названия отчёта дополнительные операции над записями
			{
				case "ConsumptionByCycleByBDM1"://БДМ-1 по видам продукции
				case "ConsumptionByCycleByBDM2"://БДМ-2 по видам продукции
				case "ConsumptionByBDM1ByDay"://БДМ-1(Суточный)
				case "ConsumptionByBDM2ByDay"://БДМ-2(Суточный)
											  //делаем итого для нужных категорий
											  //double[] sums = StaticMethods.Generate_sums(RecordsToShow_ConsumptionByCycleByBDM);
					Records = Form_records<ConsumptionByCycleOfProduction>("ConsumptionByCycle").Select(r=>(object)r).ToList();
					var t_sum = Sums_CycleOfProduction(Records.Select(r => (ISums_CycleOfProduction)r).ToList());
					if (t_sum!=null)
					{
						Sums.Add("ConsumptionByCycleByBDM", t_sum);
					}
					
					break;
				case "TERperMonthperTonne"://Средневзвешенное ТЭР на тонну по циклам производства
										   //В данном отчете ограничение по датам используется для ограничения SKU по которым выводить годовой отчет, год передается отдельно
					Records_List = new Dictionary<string, List<object>>();
					Records_List.Add("TERperMonthperTonne",Form_records<TERperMonthperTonne>("TERperMonthperTonne").Select(r => (object)r).ToList());
					Records_List.Add("TERperCycleperTonne", Form_records<TERperCycleperTonne>("TERperCycleperTonne").Select(r => (object)r).ToList());
					Records_List.Add("TER_Plan", Form_records<TERperMonthperTonne>("TER_Plan").Select(r => (object)r).ToList());
					break;
				case "EnergyConsumptionByManufactureByHour"://Часовой расход электроэнергии по производству
					#region case "EnergyConsumptionByManufactureByHour"

					//Задача для каждого поля для указного для подсчёта, посчитать данные в разрезе списка индификаторов в Constants.places
					//Довольно интересный алгоритм, позволяющий делать группировку по динамическому Id закреплённому за местами Constants.places
					// причем за одно место может быть закреленно несколько ID
					//Получаем в результате массив double, где индекс массива это индекс места в Constants.places
					// А сам массив содержит информацию в разрезе часа, по всем местам.
					var precompute_data = Form_records<EnergyConsumptionByManufactureByHour>();
					if (precompute_data == null || precompute_data.Count == 0)
					{
						break;
					}
					//Собираем id по которым будем считать итоговую сумму по производству(колонка итого:)
					List<int> total_sums_place_ids_EnergyConsumptionByManufactureByHour = new List<int>();

					Constants.places_total.Values.ToList()
						.ForEach(r =>
						{ total_sums_place_ids_EnergyConsumptionByManufactureByHour.AddRange(r); }
							);

					////строка итого, храним Dictionary<string, double> для поддержки и других видов ТЭР, газа, пара и т.д.
					//List<Dictionary<string, double>> sums_EnergyConsumptionByManufactureByHour = new List<Dictionary<string, double>>();
					//подсчитываем данные по местам
					//var data_EnergyConsumptionByManufactureByHour; //= new Dictionary<string, List<double>>();
					var field_name_EnergyConsumptionByManufactureByHour = "EnergyConsumption";
					
					Records= precompute_data
							.Select(r => ((IHaveMeasureDate)r).Measure_Date)
							.Distinct()
							.Select(Measure_Date => {

								var values = SumField_byPlaceId(field_name_EnergyConsumptionByManufactureByHour, precompute_data.Where(r => ((IHaveMeasureDate)r).Measure_Date == Measure_Date).Select(r=>(EnergyConsumptionByManufactureByHour)r) .ToList(), roundNum, total_sums_place_ids_EnergyConsumptionByManufactureByHour);

								return new Data_EnergyConsumptionByManufactureByHour
								{
									Date = Measure_Date.ToShortDateString(),
									Time = Measure_Date.ToShortTimeString(),
									Values = values//массив из double с показаниями за текущий слайс на время и дату
								};

							}).ToList<object>();

					//Добавляем строковые итоги
					//Нужно пробежатся по срезам по часам и посчитать итоговые данные по каждому месту
					//напомню что индекс в массиве data это индекс места массиве Constants.places_total
					var sums_row_EnergyConsumptionByManufactureByHour = new double[places.Count + 1];//разменость +1 потому что ещё считаем последную колонку итого
					var param_values = typeof(Data_EnergyConsumptionByManufactureByHour).GetProperty("Values");
					foreach (var data in Records)
					{

						var curr_data = (List<double>)param_values.GetValue(data);
						for (int i = 0; i < curr_data.Count; i++)
						{
							sums_row_EnergyConsumptionByManufactureByHour[i] += curr_data[i];
						}

					}
					Sums.Add("row_EnergyConsumptionByManufactureByHour", sums_row_EnergyConsumptionByManufactureByHour);
					break;
				#endregion
				case "EnergyConsumptionByDevicesByDay"://Суточный расход электроэнергии по учётам
				case "EnergyConsumptionByDevicesByHour"://Часовой расход электроэнергии по учётам
					#region EnergyConsumptionByDevicesBy
					Stopwatch tempWatch = new Stopwatch();
					tempWatch.Start();
					//отличия только в группировках между этими отчетами, так что формируем признак
					//EnergyConsumptionByDevices
					//Собираем записи для формирования вывода
					//Т.к список устройств динамический, то под него нельзя создать класс, так что делаем группировки по ходу
					Records  = Form_records<EnergyConsumptionByDevices>("EnergyConsumptionByDevicesByDay").Select(r => (object)r).ToList();
					tempWatch.Stop();
					//Для строки Итого:
					Sums.Add("EnergyConsumptionByDevices", 
							Records
							.Select(r=>(EnergyConsumptionByDevices)r)
							.GroupBy(r => r.Device_Name,
							(g, r) => Math.Round(r.Sum(e => e.EnergyConsumption ?? 0), 3))
							.Append(0)
							.ToArray());



					//Для колонки Итого по производству:
					Sums.Add("EnergyConsumptionByDevices_col_production",
							Records
							.Select(r => (EnergyConsumptionByDevices)r)					
							.Where(r => Constants.EnergyConsumptionByDevices_total_devices.ContainsKey(r.Device_Name))//итого для строк считаем только для определенных колонок
							.GroupBy(r => r.Measure_Date, (g, rs) => rs.Sum(r => r.EnergyConsumption) ?? 0).ToArray());
					//Добавляем сумму по производству
					Sums["EnergyConsumptionByDevices"][Sums["EnergyConsumptionByDevices"].Length-1] = (Sums["EnergyConsumptionByDevices_col_production"].Sum(r => r));

										
					break;
				#endregion
				case "ConsumptionByManufactureByPeriod"://общая по производству
					#region "ConsumptionByManufactureByPeriod"
					Records = Form_records<ConsumptionByManufactureByPeriod>().Select(r=>(object)r).ToList();
					
					//Подготавливаем лист id мест по которым будем считать данные для итогов
					List<int> total_sums_place_ids = new List<int>();					
					Constants.places_total.Values.ToList()
						.ForEach(r =>
						{ total_sums_place_ids.AddRange(r); }
							);

					//Задача для каждого поля для указного для подсчёта,
					//посчитать данные в разрезе списка индификаторов в Constants.places
					var fInfo_ConsumptionByManufactureByPeriod = typeof(ConsumptionByManufactureByPeriod).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
					Records_List = new Dictionary<string, List<object>>(Constants.fields_to_sum_ConsumptionByManufactureByPeriod.Count);
					foreach (var field_name in Constants.fields_to_sum_ConsumptionByManufactureByPeriod)
					{
						//подсчитываем данные по местам
						Records_List.Add(field_name, 
							SumField_byPlaceId(
								field_name,
								Records
								 .Select(r=>(ConsumptionByManufactureByPeriod)r)
								 .ToList(),
								roundNum,
								total_sums_place_ids)
							.Select(r=>(object)r)
							.ToList());
					}
					break;
				#endregion
				case "ConsumptionByBDM1ByHour"://БДМ-1(Часовой)
				case "ConsumptionByBDM2ByHour"://БДМ-2(Часовой)
					#region ConsumptionByBDMByHour
					Records = Form_records<ConsumptionByBDMbyHour>("ConsumptionByBDMByHour").Select(r=>(object)r).ToList();
					if (Records==null||Records.Count==0)
					{
						break;
					}
					//Из-за того что для вывода по часового мы берем сетку по часам,
					//а циклы могот заканчиватся и начинатся внутри часа, то на эти цикла происходит дублирование по параметрам, 
					//так что пробегаемся по записям и ищем такие случаи, и объединяем их в одну запись 

					//берем элементы по count-2 потому что сравниваем два элемента и последний не счем сравнивать
					var temp_recs = new List<ConsumptionByBDMbyHour>();
					for (int i = 0; i < Records.Count - 1; i++)
					{
						var curr = (IHaveComposition)Records.ElementAt(i);
						var next = (IHaveComposition)Records.ElementAt(i + 1);
						var excludeProp = new Dictionary<string, bool>() {["ID"]=false,["Composition"]=false};

						if (IsEqualPropValue(firstObject: curr, secondObject: next, excludePropList: excludeProp))
						{
							curr.Composition += ", " + next.Composition;
							i++;
						}
						temp_recs.Add((ConsumptionByBDMbyHour)curr);
					}
					Records = temp_recs.Select(r=>(object)r).ToList();
					//Для строки Итого:
					Sums.Add("ConsumptionByBDMByHour",

						value:
						//чтобы получить итого по записям, выделяем нужные столбцы и добаляем столбец по кторому будем вести группировку
						GetSumsAndAvgProp(
							Records.Select(r => (ConsumptionByBDMbyHour)r).ToList(), 
							propForSumList: tesSumList.ToDictionary(r => r, r => false),
							propForAvgList: tesAvgList.ToDictionary(r => r, r => false))
						 .Select(d => (double)(d??0.0)).ToArray());//распаковываем в дабл
					break;
				#endregion
				case "SkuDataByShifts_BDM1":
				case "SkuDataByShifts_BDM2":
					#region SkuDataByShifts
					var ter_list_shifts = Constants.ter_list_shifts;
					//нарезаем указный период на смены
					var shifts_list = new List<Shift>();
					int shift_index = 0;

					reportDates.CurrShiftStart = reportDates.CurrShiftStart.AddHours(-reportDates.ShiftLength);
					reportDates.CurrShiftEnd = reportDates.CurrShiftEnd.AddHours(-reportDates.ShiftLength);
					while (true)
					{
						if (reportDates.CurrShiftStart > DateTime.Now || reportDates.CurrShiftStart > reportDates.EndDate)//поледняя смена не должна выходить за текущюю дату или конец преиода
						{
							break;
						}
						else
						{
							shifts_list.Add(new Shift() { shift_start = reportDates.CurrShiftStart, shift_end = reportDates.CurrShiftEnd, shift_index = shift_index });
						}
						reportDates.CurrShiftStart = reportDates.CurrShiftStart.AddHours(reportDates.ShiftLength);
						reportDates.CurrShiftEnd = reportDates.CurrShiftEnd.AddHours(reportDates.ShiftLength);
						shift_index++;
					}

					var shiftStart = DateTime.Now;
					var shiftEnd = DateTime.Now;
					//если смена не выбрана(-1) то выводим последнию смену в нарезке, иначе выбраную смену
					if (shifts_list.Count > 0)
					{
						shiftStart = shifts_list[GetCurShiftIndex(currShiftIndex, shifts_list.Count)].shift_start;
						shiftEnd = shifts_list[GetCurShiftIndex(currShiftIndex, shifts_list.Count)].shift_end;
					}
					else
					{
						shiftStart = reportDates.CurrShiftStart;
						shiftEnd = reportDates.CurrShiftEnd;
					}

					reportDates.CurrShiftStart= shiftStart;
					reportDates.CurrShiftEnd = shiftEnd;

					Records_List.Add("SkuDataByShifts",
						Form_records<SkuDataByShifts>("SkuDataByShifts")						
						.OrderBy(r => r.CycleDateBegin)
						.Select(r=>(object)r)
						.ToList());
					var sku_list = Records_List["SkuDataByShifts"]
									.Select(r => ((IHaveSku)r).Sku)
									.ToList();


					Records_List.Add("Shifts_plan",  
						context.StgPlanTer
						 .Where(r => r.Year == shiftStart.Year
									&& r.Month == shiftStart.Month
									&& sku_list.Contains(r.Sku)
									&& r.PlaceId == (isBDM1 ? 1 : 2))
						 .Select(r=>(object)r)
						 .ToList());



					Records_List.Add("Shifts_index_list", shifts_list.Select(r => (object)r.shift_index.ToString()).ToList());
					Records_List.Add("Shifts_dates_list", shifts_list
															.Select(r => $"{r.shift_start.ToShortDateString()} {r.shift_start.ToShortTimeString()}-{r.shift_end.ToShortDateString()} {r.shift_end.ToShortTimeString()}")
															.Select(r=>(object)r)
															.ToList());
				
					//if (export_excel == 1)
					//{ return Excel_methods.Export_to_Excel_SkuDataByShifts(new ExcelExport(), report_name, shiftStart, shiftEnd, placeName: place_name, this, baseStrings, RecordsToShow_SkuDataByShifts, ter_list_shifts, shiftId: RecordsToShow_SkuDataByShifts.Count > 0 ? RecordsToShow_SkuDataByShifts.FirstOrDefault().ShiftId : 0, machinist_name: RecordsToShow_SkuDataByShifts.Count > 0 ? RecordsToShow_SkuDataByShifts.FirstOrDefault().Machinist_name : ""); }
					break;
				#endregion
				default:
					break;
			}
			//Если нужен список продуктов
			if (Records?.Count>0? Records?.FirstOrDefault().GetType().GetInterface("IListSortOfProd") != null:false)
			{
				ListSortOfProd = Records.OrderBy(m => ((IListSortOfProd)m).SortofProduction).Select(m => ((IListSortOfProd)m).SortofProduction).Distinct().ToArray();
				if (SelectedSortOfProduction != null && SelectedSortOfProduction != "All")
					Records = Records.Where(r => ((IListSortOfProd)r).SortofProduction == SelectedSortOfProduction).ToList();
			}
			//Округляем все поля
			RoundProps();
			this.Successfull = true;			
		}
Beispiel #27
0
        public ServiceModels.ServiceResponse AddBoard(InputModels.CreateBoardInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            if (Records.Any(b => b.Name == input.Name))
            {
                serviceResponse.Error(nameof(input.Name), "A board with that name already exists");
            }

            DataModels.Category categoryRecord = null;

            if (!string.IsNullOrEmpty(input.NewCategory))
            {
                input.NewCategory = input.NewCategory.Trim();
            }

            if (!string.IsNullOrEmpty(input.NewCategory))
            {
                categoryRecord = Categories.FirstOrDefault(c => c.Name == input.NewCategory);

                if (categoryRecord is null)
                {
                    var displayOrder = Categories.DefaultIfEmpty().Max(c => c.DisplayOrder);

                    categoryRecord = new DataModels.Category {
                        Name         = input.NewCategory,
                        DisplayOrder = displayOrder + 1
                    };

                    DbContext.Categories.Add(categoryRecord);
                }
            }
            else
            {
                try {
                    var categoryId = Convert.ToInt32(input.Category);
                    categoryRecord = Categories.First(c => c.Id == categoryId);

                    if (categoryRecord is null)
                    {
                        serviceResponse.Error(nameof(input.Category), "No category was found with this ID.");
                    }
                }
                catch (FormatException) {
                    serviceResponse.Error(nameof(input.Category), "Invalid category ID");
                }
            }

            if (!string.IsNullOrEmpty(input.Name))
            {
                input.Name = input.Name.Trim();
            }

            if (string.IsNullOrEmpty(input.Name))
            {
                serviceResponse.Error(nameof(input.Name), "Name is a required field.");
            }

            if (!string.IsNullOrEmpty(input.Description))
            {
                input.Description = input.Description.Trim();
            }

            var existingRecord = Records.FirstOrDefault(b => b.Name == input.Name);

            if (existingRecord != null)
            {
                serviceResponse.Error(nameof(input.Name), "A board with that name already exists");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            DbContext.SaveChanges();

            var record = new DataModels.Board {
                Name        = input.Name,
                Description = input.Description,
                CategoryId  = categoryRecord.Id
            };

            DbContext.Boards.Add(record);

            DbContext.SaveChanges();

            serviceResponse.RedirectPath = UrlHelper.Action(nameof(Controllers.Boards.Manage), nameof(Controllers.Boards), new { id = record.Id });

            return(serviceResponse);
        }
Beispiel #28
0
        public ServiceModels.ServiceResponse UpdateBoard(InputModels.EditBoardInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var record = Records.FirstOrDefault(b => b.Id == input.Id);

            if (record is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.Id}'");
            }

            DataModels.Category newCategoryRecord = null;

            if (!string.IsNullOrEmpty(input.NewCategory))
            {
                input.NewCategory = input.NewCategory.Trim();
            }

            if (!string.IsNullOrEmpty(input.NewCategory))
            {
                newCategoryRecord = Categories.FirstOrDefault(c => c.Name == input.NewCategory);

                if (newCategoryRecord is null)
                {
                    var displayOrder = Categories.DefaultIfEmpty().Max(c => c.DisplayOrder);

                    newCategoryRecord = new DataModels.Category {
                        Name         = input.NewCategory,
                        DisplayOrder = displayOrder + 1
                    };

                    DbContext.Categories.Add(newCategoryRecord);
                    DbContext.SaveChanges();
                }
            }
            else
            {
                try {
                    var newCategoryId = Convert.ToInt32(input.Category);
                    newCategoryRecord = Categories.FirstOrDefault(c => c.Id == newCategoryId);

                    if (newCategoryRecord is null)
                    {
                        serviceResponse.Error(nameof(input.Category), "No category was found with this ID.");
                    }
                }
                catch (FormatException) {
                    serviceResponse.Error(nameof(input.Category), "Invalid category ID");
                }
            }

            if (!string.IsNullOrEmpty(input.Name))
            {
                input.Name = input.Name.Trim();
            }

            if (string.IsNullOrEmpty(input.Name))
            {
                serviceResponse.Error(nameof(input.Name), "Name is a required field.");
            }

            if (!string.IsNullOrEmpty(input.Description))
            {
                input.Description = input.Description.Trim();
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            record.Name        = input.Name;
            record.Description = input.Description;

            var oldCategoryId = -1;

            if (record.CategoryId != newCategoryRecord.Id)
            {
                var categoryBoards = Records.Where(r => r.CategoryId == record.CategoryId).ToList();

                if (categoryBoards.Count() <= 1)
                {
                    oldCategoryId = record.CategoryId;
                }

                record.CategoryId = newCategoryRecord.Id;
            }

            var boardRoles = RoleRepository.BoardRoles.Where(r => r.BoardId == record.Id).ToList();

            foreach (var boardRole in boardRoles)
            {
                DbContext.BoardRoles.Remove(boardRole);
            }

            if (input.Roles != null)
            {
                var roleIds = RoleRepository.SiteRoles.Select(r => r.Id).ToList();

                foreach (var inputRole in input.Roles)
                {
                    if (roleIds.Contains(inputRole))
                    {
                        DbContext.BoardRoles.Add(new DataModels.BoardRole {
                            BoardId = record.Id,
                            RoleId  = inputRole
                        });
                    }
                    else
                    {
                        serviceResponse.Error($"Role does not exist with id '{inputRole}'");
                    }
                }
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            DbContext.Update(record);
            DbContext.SaveChanges();

            if (oldCategoryId >= 0)
            {
                var oldCategoryRecord = Categories.FirstOrDefault(item => item.Id == oldCategoryId);

                if (oldCategoryRecord != null)
                {
                    DbContext.Categories.Remove(oldCategoryRecord);
                    DbContext.SaveChanges();
                }
            }

            serviceResponse.RedirectPath = UrlHelper.Action(nameof(Controllers.Boards.Manage), nameof(Controllers.Boards), new { id = record.Id });

            return(serviceResponse);
        }
Beispiel #29
0
 public Ingredient GetIngredientByName(string name)
 {
     return(Records.FirstOrDefault(d => d.Name == name));
 }