/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnDelete_Click(object sender, EventArgs e) { int?categoryId = null; var service = new ScheduleService(); var item = service.Get(int.Parse(hfScheduleId.Value)); if (item != null) { string errorMessage; if (!service.CanDelete(item, out errorMessage)) { ShowReadonlyDetails(item); mdDeleteWarning.Show(errorMessage, ModalAlertType.Information); } else { categoryId = item.CategoryId; service.Delete(item, CurrentPersonId); service.Save(item, CurrentPersonId); // reload page, selecting the deleted data view's parent var qryParams = new Dictionary <string, string>(); if (categoryId != null) { qryParams["CategoryId"] = categoryId.ToString(); } NavigateToPage(this.CurrentPage.Guid, qryParams); } } }
public void ShouldDeleteFromRepositoryAndReturnTrue() { var idToDelete = 1; var entity = new Schedule { Id = idToDelete, ShipId = shipId }; shipRepositoryMock.Setup(x => x.Find(shipId)).Returns(new Ship { Schedules = new List <Schedule>() }); repositoryMock.Setup(x => x.Find(idToDelete)).Returns(entity); repositoryMock.Setup(x => x.Update(entity)); var result = service.Delete(idToDelete); Assert.IsTrue(result); repositoryMock.Verify(x => x.Delete(idToDelete), Times.Once()); }
private Command DeleteLesson( ScheduleService service, Func <string, string> requestInput) => args => { var id = requestInput("Введите ID класса для удаления"); Del(() => service.Delete(new SchoolClass { Id = id })); };
private Command DeleteExercise( ScheduleService service, Func <string, string> requestInput) => args => { var id = requestInput("Введите ID удаляемого занятия"); Del(() => service.Delete(new Exercise { Id = id })); };
private Command DeleteTeacher( ScheduleService service, Func <string, string> requestInput) => args => { var id = requestInput("Введите ID преподавателя для удаления"); Del(() => service.Delete(new Teacher { Id = id })); };
private Command DeleteStudent( ScheduleService service, Func <string, string> requestInput) => args => { var id = requestInput("Введите ID ученика для удаления"); Del(() => service.Delete(new Student { Id = id })); };
/// <summary> /// 删除日程 /// </summary> /// <param name="context"></param> private void DelSchedule(HttpContext context) { string result = ""; string id = context.Request.Form["id"]; if (id.Length > 0) { jsonModel = bll.Delete(Convert.ToInt32(id)); result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; } context.Response.Write(result); }
public async Task <IHttpActionResult> DeleteSchedule(int id) { Schedule schedule = await _schedules.Find(id); if (schedule == null) { return(NotFound()); } await _schedules.Delete(schedule); return(Ok((ScheduleResultViewModel)schedule)); }
private Command DeleteTeacherLesson( ScheduleService service, Func <string, string> requestInput) => args => { var teacherId = requestInput("Введите ID преподавателя"); var lessonId = requestInput("Введите ID предмета"); var teacherLesson = new TeacherLesson { Teacher = new Teacher { Id = teacherId }, Lesson = new Lesson { Id = lessonId } }; Del(() => service.Delete(teacherLesson)); };
/// <summary> /// Handles the Delete event of the gSchedules control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gSchedules_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); ScheduleService scheduleService = new ScheduleService(rockContext); Schedule schedule = scheduleService.Get(e.RowKeyId); if (schedule != null) { string errorMessage; if (!scheduleService.CanDelete(schedule, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } scheduleService.Delete(schedule); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Handles the Delete event of the gSchedules control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gSchedules_Delete(object sender, RowEventArgs e) { RockTransactionScope.WrapTransaction(() => { ScheduleService scheduleService = new ScheduleService(); Schedule schedule = scheduleService.Get((int)e.RowKeyValue); if (schedule != null) { string errorMessage; if (!scheduleService.CanDelete(schedule, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } scheduleService.Delete(schedule, CurrentPersonId); scheduleService.Save(schedule, CurrentPersonId); } }); BindGrid(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { EventItemOccurrence eventItemOccurrence = null; using (var rockContext = new RockContext()) { bool newItem = false; var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext); var eventItemOccurrenceGroupMapService = new EventItemOccurrenceGroupMapService(rockContext); var registrationInstanceService = new RegistrationInstanceService(rockContext); var scheduleService = new ScheduleService(rockContext); int eventItemOccurrenceId = hfEventItemOccurrenceId.ValueAsInt(); if (eventItemOccurrenceId != 0) { eventItemOccurrence = eventItemOccurrenceService .Queryable("Linkages") .Where(i => i.Id == eventItemOccurrenceId) .FirstOrDefault(); } if (eventItemOccurrence == null) { newItem = true; eventItemOccurrence = new EventItemOccurrence { EventItemId = PageParameter("EventItemId").AsInteger() }; eventItemOccurrenceService.Add(eventItemOccurrence); } int?newCampusId = ddlCampus.SelectedValueAsInt(); if (eventItemOccurrence.CampusId != newCampusId) { eventItemOccurrence.CampusId = newCampusId; if (newCampusId.HasValue) { var campus = new CampusService(rockContext).Get(newCampusId.Value); eventItemOccurrence.Campus = campus; } else { eventItemOccurrence.Campus = null; } } eventItemOccurrence.Location = tbLocation.Text; string iCalendarContent = sbSchedule.iCalendarContent; var calEvent = ScheduleICalHelper.GetCalenderEvent(iCalendarContent); if (calEvent != null && calEvent.DTStart != null) { if (eventItemOccurrence.Schedule == null) { eventItemOccurrence.Schedule = new Schedule(); } eventItemOccurrence.Schedule.iCalendarContent = iCalendarContent; } else { if (eventItemOccurrence.ScheduleId.HasValue) { var oldSchedule = scheduleService.Get(eventItemOccurrence.ScheduleId.Value); if (oldSchedule != null) { scheduleService.Delete(oldSchedule); } } } if (!eventItemOccurrence.ContactPersonAliasId.Equals(ppContact.PersonAliasId)) { PersonAlias personAlias = null; eventItemOccurrence.ContactPersonAliasId = ppContact.PersonAliasId; if (eventItemOccurrence.ContactPersonAliasId.HasValue) { personAlias = new PersonAliasService(rockContext).Get(eventItemOccurrence.ContactPersonAliasId.Value); } if (personAlias != null) { eventItemOccurrence.ContactPersonAlias = personAlias; } } eventItemOccurrence.ContactPhone = PhoneNumber.FormattedNumber(PhoneNumber.DefaultCountryCode(), pnPhone.Number); eventItemOccurrence.ContactEmail = tbEmail.Text; eventItemOccurrence.Note = htmlOccurrenceNote.Text; // Remove any linkage no longer in UI Guid uiLinkageGuid = LinkageState != null ? LinkageState.Guid : Guid.Empty; foreach (var linkage in eventItemOccurrence.Linkages.Where(l => !l.Guid.Equals(uiLinkageGuid)).ToList()) { eventItemOccurrence.Linkages.Remove(linkage); eventItemOccurrenceGroupMapService.Delete(linkage); } // Add/Update linkage in UI if (!uiLinkageGuid.Equals(Guid.Empty)) { var linkage = eventItemOccurrence.Linkages.Where(l => l.Guid.Equals(uiLinkageGuid)).FirstOrDefault(); if (linkage == null) { linkage = new EventItemOccurrenceGroupMap(); eventItemOccurrence.Linkages.Add(linkage); } linkage.CopyPropertiesFrom(LinkageState); // update registration instance if (LinkageState.RegistrationInstance != null) { if (LinkageState.RegistrationInstance.Id != 0) { linkage.RegistrationInstance = registrationInstanceService.Get(LinkageState.RegistrationInstance.Id); } if (linkage.RegistrationInstance == null) { var registrationInstance = new RegistrationInstance(); registrationInstanceService.Add(registrationInstance); linkage.RegistrationInstance = registrationInstance; } linkage.RegistrationInstance.CopyPropertiesFrom(LinkageState.RegistrationInstance); } } if (!Page.IsValid) { return; } if (!eventItemOccurrence.IsValid) { // Controls will render the error messages return; } rockContext.SaveChanges(); var qryParams = new Dictionary <string, string>(); qryParams.Add("EventCalendarId", PageParameter("EventCalendarId")); qryParams.Add("EventItemId", PageParameter("EventItemId")); if (newItem) { NavigateToParentPage(qryParams); } else { qryParams.Add("EventItemOccurrenceId", eventItemOccurrence.Id.ToString()); NavigateToPage(RockPage.Guid, qryParams); } } }
public void CrudTest() { service.Save(sClass); var savedClass = service.Find((SchoolClass c) => c.Id == sClass.Id); AssertClassesEquals(savedClass, sClass); service.Save(sClass1); var savedClass1 = service.Find((SchoolClass c) => c.Id == sClass1.Id); AssertClassesEquals(savedClass1, sClass1); service.Save(student); var savedStudent = service.Find((Student s) => s.Id == student.Id); AssertStudentsEquals(savedStudent, student); service.Save(student1); var savedStudent1 = service.Find((Student s) => s.Id == student1.Id); AssertStudentsEquals(savedStudent1, student1); service.Save(lesson); var savedLesson = service.Find((Lesson l) => l.Id == lesson.Id); AssertLessonsEquals(savedLesson, lesson); service.Save(lesson1); var savedLesson1 = service.Find((Lesson l) => l.Id == lesson1.Id); AssertLessonsEquals(savedLesson1, lesson1); service.Save(teacher); var savedTeacher = service.Find((Teacher t) => t.Id == teacher.Id); AssertTeachersEquals(savedTeacher, teacher); service.Save(teacher1); var savedTeacher1 = service.Find((Teacher t) => t.Id == teacher1.Id); AssertTeachersEquals(savedTeacher1, teacher1); service.Save(teacherLesson); var savedTeacherLesson = service.Find((TeacherLesson tl) => tl.LessonId == teacherLesson.Lesson.Id && tl.TeacherId == teacherLesson.Teacher.Id); AssertTeacherLessonEquals(savedTeacherLesson, teacherLesson); service.Save(exercise); var savedExercise = service.Find((Exercise e) => e.Id == exercise.Id); AssertExercisesEquals(savedExercise, exercise); sClass.ClassNumber = 4; service.Save(sClass); var savedChangedClass = service.Find((SchoolClass c) => c.Id == sClass.Id); AssertClassesEquals(savedChangedClass, sClass); student.LastName = "fdkjdkdfk"; student.SchoolClass = sClass1; service.Save(student); var savedChangedStudent = service.Find((Student s) => s.Id == student.Id); AssertStudentsEquals(savedChangedStudent, student); lesson.Name = "kdkdkdmeee"; service.Save(lesson); var savedChangedLesson = service.Find((Lesson l) => l.Id == lesson.Id); AssertLessonsEquals(savedChangedLesson, lesson); teacher.LastName = "Djldfsn"; service.Save(teacher); var savedChangedTeacher = service.Find((Teacher t) => t.Id == teacher.Id); AssertTeachersEquals(savedChangedTeacher, teacher); exercise.Auditory = 434; service.Save(exercise); var savedChangedExercise = service.Find((Exercise e) => e.Id == exercise.Id); AssertExercisesEquals(savedChangedExercise, exercise); service.Delete(student); Assert.IsNull(service.Find((Student s) => s.Id == student.Id)); Assert.IsNotNull(service.Find((SchoolClass c) => c.Id == sClass1.Id)); service.Delete(student1); Assert.IsNull(service.Find((Student s) => s.Id == student1.Id)); Assert.IsNotNull(service.Find((SchoolClass c) => c.Id == sClass.Id)); service.Delete(exercise); Assert.IsNull(service.Find((Exercise e) => e.Id == exercise.Id)); service.Delete(sClass); Assert.IsNull(service.Find((SchoolClass c) => c.Id == sClass.Id)); service.Delete(sClass1); Assert.IsNull(service.Find((SchoolClass c) => c.Id == sClass1.Id)); service.Delete(lesson); Assert.IsNull(service.Find((Lesson l) => l.Id == lesson.Id)); service.Delete(lesson1); Assert.IsNull(service.Find((Lesson l) => l.Id == lesson1.Id)); service.Delete(teacher); Assert.IsNull(service.Find((Teacher t) => t.Id == teacher.Id)); service.Delete(teacher1); Assert.IsNull(service.Find((Teacher t) => t.Id == teacher1.Id)); }
public IActionResult Delete(string ScheduleId) { _scheduleService.Delete(ScheduleId); return(Ok()); }
/// <summary> /// Syncs an eSpace event into Rock. /// </summary> /// <param name="eSpaceClient">The eSpace client</param> /// <param name="eSpaceEvent">The eSpace event</param> /// <param name="occurrencesFilter">The filter to use when syncing occurrences</param> /// <returns>The synced Rock event</returns> public static async Task SyncEvent( Client eSpaceClient, ESpace.Event eSpaceEvent, GetEventOccurrencesOptions occurrencesFilter, EventCalendarCache globalCalendar, EventCalendarCache publicCalendar, EventCalendarCache privateCalendar, string occurrenceApprovedAttributeKey ) { using (var rockContext = new RockContext()) { // Create our services var eventItemService = new EventItemService(rockContext); var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext); var eventItemAudienceService = new EventItemAudienceService(rockContext); var scheduleService = new ScheduleService(rockContext); var personService = new PersonService(rockContext); // Get or create the linked Rock event var rockEvent = eventItemService.GetOrCreateByForeignId( "EventCalendarItems,EventItemOccurrences", ForeignKey_eSpaceEventId, eSpaceEvent.EventId.Value, out var _ ); // Track if we needed to update anything var changed = false; // Update the Name if (rockEvent.Name != eSpaceEvent.EventName) { changed = true; rockEvent.Name = eSpaceEvent.EventName; } // Update the Active State var eSpaceEventIsActive = eSpaceEvent.Status != ESpaceStatus_Draft; if (rockEvent.IsActive != eSpaceEventIsActive) { changed = true; rockEvent.IsActive = eSpaceEventIsActive; } // Update the Approval State var eSpaceEventIsApproved = eSpaceEvent.Status == ESpaceStatus_Approved; if (rockEvent.IsApproved != eSpaceEventIsApproved) { changed = true; rockEvent.IsApproved = eSpaceEventIsApproved; if (eSpaceEventIsApproved) { rockEvent.ApprovedOnDateTime = DateTime.Now; } else { rockEvent.ApprovedOnDateTime = null; } } // Update the Summary if (rockEvent.Summary != eSpaceEvent.Description) { changed = true; rockEvent.Summary = eSpaceEvent.Description; } // Update the details Url var eSpaceEventPublicLink = eSpaceEvent.PublicLink?.ToString(); if (rockEvent.DetailsUrl != eSpaceEventPublicLink) { changed = true; rockEvent.DetailsUrl = eSpaceEventPublicLink; } // Update the audiences var eSpaceCategories = MatchCategories(eSpaceEvent.Categories); // Check global calendar if (globalCalendar != null) { rockEvent.AddToCalendar(globalCalendar, out var addedToCalendar); changed = changed || addedToCalendar; } var eventCalendarItemService = new EventCalendarItemService(rockContext); // Check public calendar if (publicCalendar != null) { if (eSpaceEvent.IsPublic ?? false) { rockEvent.AddToCalendar(publicCalendar, out var addedToCalendar); changed = changed || addedToCalendar; } else { rockEvent.RemoveFromCalendar(eventCalendarItemService, publicCalendar, out var removedFromCalendar); changed = changed || removedFromCalendar; } } // Check private calendar if (privateCalendar != null) { if (!(eSpaceEvent.IsPublic ?? false)) { rockEvent.AddToCalendar(privateCalendar, out var addedToCalendar); changed = changed || addedToCalendar; } else { rockEvent.RemoveFromCalendar(eventCalendarItemService, privateCalendar, out var removedFromCalendar); changed = changed || removedFromCalendar; } } // Fetch the occurrences for the event if (occurrencesFilter == null) { occurrencesFilter = new GetEventOccurrencesOptions { StartDate = DateTime.Now } } ; occurrencesFilter.EventId = eSpaceEvent.EventId; var eSpaceEventOccurrences = await eSpaceClient.GetEventOccurrences(occurrencesFilter); // Calculate some stuff for the occurrences var campusLocations = MatchLocations(eSpaceEvent.IsOffSite ?? false ? eSpaceEvent.PublicLocations : eSpaceEvent.Locations); var contactPerson = personService.FindPerson(eSpaceEvent.Contacts.FirstOrDefault()); var firstESpaceOccurrence = eSpaceEventOccurrences.FirstOrDefault(); if (firstESpaceOccurrence != null) { // Update the Description if (rockEvent.Description != firstESpaceOccurrence.PublicHtmlNotes) { rockEvent.Description = firstESpaceOccurrence.PublicHtmlNotes; changed = true; } } var syncedRockOccurrences = new List <EventItemOccurrence>();; var rockOccurrencesWithAttributeChanges = new List <EventItemOccurrence>(); // Update each occurrence foreach (var eSpaceOccurrence in eSpaceEventOccurrences) { foreach (var campusLocation in campusLocations) { var rockOccurrence = SyncOccurrence(eSpaceEvent, eSpaceOccurrence, rockEvent, campusLocation, contactPerson, occurrenceApprovedAttributeKey, out var occurrenceChanged, out var occurrenceAttributeChanged); changed = changed || occurrenceChanged; syncedRockOccurrences.Add(rockOccurrence); if (occurrenceAttributeChanged) { rockOccurrencesWithAttributeChanges.Add(rockOccurrence); } } } // Remove any desynced occurrences var removedOccurrences = rockEvent.EventItemOccurrences.Except(syncedRockOccurrences).ToList(); foreach (var occurrence in removedOccurrences) { rockEvent.EventItemOccurrences.Remove(occurrence); if (occurrence.Schedule != null) { scheduleService.Delete(occurrence.Schedule); occurrence.Schedule = null; } eventItemOccurrenceService.Delete(occurrence); changed = true; } // If anything was updated, save it if (changed) { rockContext.SaveChanges(); } // If any occurrences had attributes modified, save them foreach (var rockOccurrence in rockOccurrencesWithAttributeChanges) { rockOccurrence.SaveAttributeValues(); } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { Metric metric; var rockContext = new RockContext(); MetricService metricService = new MetricService(rockContext); MetricCategoryService metricCategoryService = new MetricCategoryService(rockContext); MetricValueService metricValueService = new MetricValueService(rockContext); bool deleteValuesOnSave = sender == btnDeleteValuesAndSave; int metricId = hfMetricId.Value.AsInteger(); if (metricId == 0) { metric = new Metric(); } else { metric = metricService.Get(metricId); } metric.Title = tbTitle.Text; metric.Subtitle = tbSubtitle.Text; metric.Description = tbDescription.Text; metric.IconCssClass = tbIconCssClass.Text; metric.SourceValueTypeId = ddlSourceType.SelectedValueAsId(); metric.XAxisLabel = tbXAxisLabel.Text; metric.YAxisLabel = tbYAxisLabel.Text; metric.IsCumulative = cbIsCumulative.Checked; var origEntityType = metric.EntityTypeId.HasValue ? EntityTypeCache.Read(metric.EntityTypeId.Value) : null; var newEntityType = etpEntityType.SelectedEntityTypeId.HasValue ? EntityTypeCache.Read(etpEntityType.SelectedEntityTypeId.Value) : null; if (origEntityType != null && !deleteValuesOnSave) { if (newEntityType == null || newEntityType.Id != origEntityType.Id) { // if the EntityTypeId of this metric has changed to NULL or to another EntityType, warn about the EntityId values being wrong bool hasEntityValues = metricValueService.Queryable().Any(a => a.MetricId == metric.Id && a.EntityId.HasValue); if (hasEntityValues) { nbEntityTypeChanged.Text = string.Format( "Warning: You can't change the series partition to {0} when there are values associated with {1}. Do you want to delete existing values?", newEntityType != null ? newEntityType.FriendlyName : "<none>", origEntityType.FriendlyName); mdEntityTypeChanged.Show(); nbEntityTypeChanged.Visible = true; return; } } } metric.EntityTypeId = etpEntityType.SelectedEntityTypeId; int sourceTypeDataView = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid()).Id; int sourceTypeSQL = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid()).Id; var personService = new PersonService(rockContext); var metricChampionPerson = personService.Get(ppMetricChampionPerson.SelectedValue ?? 0); metric.MetricChampionPersonAliasId = metricChampionPerson != null ? metricChampionPerson.PrimaryAliasId : null; var adminPerson = personService.Get(ppAdminPerson.SelectedValue ?? 0); metric.AdminPersonAliasId = adminPerson != null ? adminPerson.PrimaryAliasId : null; if (metric.SourceValueTypeId == sourceTypeSQL) { metric.SourceSql = ceSourceSql.Text; } else { metric.SourceSql = string.Empty; } if (metric.SourceValueTypeId == sourceTypeDataView) { metric.DataViewId = ddlDataView.SelectedValueAsId(); } else { metric.DataViewId = null; } var scheduleSelectionType = rblScheduleSelect.SelectedValueAsEnum <ScheduleSelectionType>(); if (scheduleSelectionType == ScheduleSelectionType.NamedSchedule) { metric.ScheduleId = ddlSchedule.SelectedValueAsId(); } else { metric.ScheduleId = hfUniqueScheduleId.ValueAsInt(); } if (!Page.IsValid) { return; } if (!metric.IsValid) { // Controls will render the error messages return; } if (!cpMetricCategories.SelectedValuesAsInt().Any()) { cpMetricCategories.ShowErrorMessage("Must select at least one category"); return; } // do a WrapTransaction since we are doing multiple SaveChanges() rockContext.WrapTransaction(() => { var scheduleService = new ScheduleService(rockContext); var schedule = scheduleService.Get(metric.ScheduleId ?? 0); int metricScheduleCategoryId = new CategoryService(rockContext).Get(Rock.SystemGuid.Category.SCHEDULE_METRICS.AsGuid()).Id; if (schedule == null) { schedule = new Schedule(); // make it an "Unnamed" metrics schedule schedule.Name = string.Empty; schedule.CategoryId = metricScheduleCategoryId; } // if the schedule was a unique schedule (configured in the Metric UI, set the schedule's ical content to the schedule builder UI's value if (scheduleSelectionType == ScheduleSelectionType.Unique) { schedule.iCalendarContent = sbSchedule.iCalendarContent; } if (!schedule.HasSchedule() && scheduleSelectionType == ScheduleSelectionType.Unique) { // don't save as a unique schedule if the schedule doesn't do anything schedule = null; } else { if (schedule.Id == 0) { scheduleService.Add(schedule); // save to make sure we have a scheduleId rockContext.SaveChanges(); } } if (schedule != null) { metric.ScheduleId = schedule.Id; } else { metric.ScheduleId = null; } if (metric.Id == 0) { metricService.Add(metric); // save to make sure we have a metricId rockContext.SaveChanges(); } // update MetricCategories for Metric metric.MetricCategories = metric.MetricCategories ?? new List <MetricCategory>(); var selectedCategoryIds = cpMetricCategories.SelectedValuesAsInt(); // delete any categories that were removed foreach (var metricCategory in metric.MetricCategories.ToList()) { if (!selectedCategoryIds.Contains(metricCategory.CategoryId)) { metricCategoryService.Delete(metricCategory); } } // add any categories that were added foreach (int categoryId in selectedCategoryIds) { if (!metric.MetricCategories.Any(a => a.CategoryId == categoryId)) { metricCategoryService.Add(new MetricCategory { CategoryId = categoryId, MetricId = metric.Id }); } } rockContext.SaveChanges(); // delete MetricValues associated with the old entityType if they confirmed the EntityType change if (deleteValuesOnSave) { metricValueService.DeleteRange(metricValueService.Queryable().Where(a => a.MetricId == metric.Id && a.EntityId.HasValue)); // since there could be 1000s of values that got deleted, do a SaveChanges that skips PrePostProcessing rockContext.SaveChanges(true); } // delete any orphaned Unnamed metric schedules var metricIdSchedulesQry = metricService.Queryable().Select(a => a.ScheduleId); int?metricScheduleId = schedule != null ? schedule.Id : (int?)null; var orphanedSchedules = scheduleService.Queryable() .Where(a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != (metricScheduleId ?? 0)) .Where(s => !metricIdSchedulesQry.Any(m => m == s.Id)); foreach (var item in orphanedSchedules) { scheduleService.Delete(item); } if (orphanedSchedules.Any()) { rockContext.SaveChanges(); } }); var qryParams = new Dictionary <string, string>(); qryParams["MetricId"] = metric.Id.ToString(); if (hfMetricCategoryId.ValueAsInt() == 0) { int?parentCategoryId = PageParameter("ParentCategoryId").AsIntegerOrNull(); int?metricCategoryId = new MetricCategoryService(new RockContext()).Queryable().Where(a => a.MetricId == metric.Id && a.CategoryId == parentCategoryId).Select(a => a.Id).FirstOrDefault(); hfMetricCategoryId.Value = metricCategoryId.ToString(); } qryParams["MetricCategoryId"] = hfMetricCategoryId.Value; qryParams["ExpandedIds"] = PageParameter("ExpandedIds"); NavigateToPage(RockPage.Guid, qryParams); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { Metric metric; var rockContext = new RockContext(); MetricService metricService = new MetricService(rockContext); MetricCategoryService metricCategoryService = new MetricCategoryService(rockContext); int metricId = hfMetricId.Value.AsInteger(false) ?? 0; if (metricId == 0) { metric = new Metric(); } else { metric = metricService.Get(metricId); } metric.Title = tbTitle.Text; metric.Subtitle = tbSubtitle.Text; metric.Description = tbDescription.Text; metric.IconCssClass = tbIconCssClass.Text; metric.SourceValueTypeId = ddlSourceType.SelectedValueAsId(); metric.XAxisLabel = tbXAxisLabel.Text; metric.YAxisLabel = tbYAxisLabel.Text; metric.IsCumulative = cbIsCumulative.Checked; metric.EntityTypeId = etpEntityType.SelectedEntityTypeId; var personService = new PersonService(rockContext); var metricChampionPerson = personService.Get(ppMetricChampionPerson.SelectedValue ?? 0); metric.MetricChampionPersonAliasId = metricChampionPerson != null ? metricChampionPerson.PrimaryAliasId : null; var adminPerson = personService.Get(ppAdminPerson.SelectedValue ?? 0); metric.AdminPersonAliasId = adminPerson != null ? adminPerson.PrimaryAliasId : null; metric.SourceSql = ceSourceSql.Text; metric.DataViewId = ddlDataView.SelectedValueAsId(); if (rblScheduleSelect.SelectedValueAsEnum <ScheduleSelectionType>() == ScheduleSelectionType.NamedSchedule) { metric.ScheduleId = ddlSchedule.SelectedValueAsId(); } else { metric.ScheduleId = hfUniqueScheduleId.ValueAsInt(); } if (!Page.IsValid) { return; } if (!metric.IsValid) { // Controls will render the error messages return; } if (!cpMetricCategories.SelectedValuesAsInt().Any()) { cpMetricCategories.ShowErrorMessage("Must select at least one category"); return; } // do a WrapTransaction since we are doing multiple SaveChanges() RockTransactionScope.WrapTransaction(() => { var scheduleService = new ScheduleService(rockContext); var schedule = scheduleService.Get(metric.ScheduleId ?? 0); int metricScheduleCategoryId = new CategoryService(rockContext).Get(Rock.SystemGuid.Category.SCHEDULE_METRICS.AsGuid()).Id; if (schedule == null) { schedule = new Schedule(); // make it an "Unnamed" metrics schedule schedule.Name = string.Empty; schedule.CategoryId = metricScheduleCategoryId; } schedule.iCalendarContent = sbSchedule.iCalendarContent; if (schedule.Id == 0) { scheduleService.Add(schedule); // save to make sure we have a scheduleId rockContext.SaveChanges(); } metric.ScheduleId = schedule.Id; if (metric.Id == 0) { metricService.Add(metric); // save to make sure we have a metricId rockContext.SaveChanges(); } // update MetricCategories for Metric metric.MetricCategories = metric.MetricCategories ?? new List <MetricCategory>(); var selectedCategoryIds = cpMetricCategories.SelectedValuesAsInt(); // delete any categories that were removed foreach (var metricCategory in metric.MetricCategories) { if (!selectedCategoryIds.Contains(metricCategory.CategoryId)) { metricCategoryService.Delete(metricCategory); } } // add any categories that were added foreach (int categoryId in selectedCategoryIds) { if (!metric.MetricCategories.Any(a => a.CategoryId == categoryId)) { metricCategoryService.Add(new MetricCategory { CategoryId = categoryId, MetricId = metric.Id }); } } rockContext.SaveChanges(); // delete any orphaned Unnamed metric schedules var metricIdSchedulesQry = metricService.Queryable().Select(a => a.ScheduleId); var orphanedSchedules = scheduleService.Queryable() .Where(a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != schedule.Id) .Where(s => !metricIdSchedulesQry.Any(m => m == s.Id)); foreach (var item in orphanedSchedules) { scheduleService.Delete(item); } if (orphanedSchedules.Any()) { rockContext.SaveChanges(); } }); var qryParams = new Dictionary <string, string>(); qryParams["MetricId"] = metric.Id.ToString(); if (hfMetricCategoryId.ValueAsInt() == 0) { int?parentCategoryId = PageParameter("ParentCategoryId").AsInteger(); int?metricCategoryId = new MetricCategoryService(new RockContext()).Queryable().Where(a => a.MetricId == metric.Id && a.CategoryId == parentCategoryId).Select(a => a.Id).FirstOrDefault(); hfMetricCategoryId.Value = metricCategoryId.ToString(); } qryParams["MetricCategoryId"] = hfMetricCategoryId.Value; NavigateToPage(RockPage.Guid, qryParams); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { bool wasSecurityRole = false; bool triggersUpdated = false; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); var roleGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()); int roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : int.MinValue; int?parentGroupId = hfParentGroupId.Value.AsIntegerOrNull(); if (parentGroupId != null) { var allowedGroupIds = LineQuery.GetCellGroupIdsInLine(CurrentPerson, rockContext); if (!allowedGroupIds.Contains(parentGroupId.Value)) { nbMessage.Text = "You are not allowed to add a group to this parent group."; nbMessage.Visible = true; pnlEditDetails.Visible = false; btnSave.Enabled = false; return; } var parentGroup = groupService.Get(parentGroupId.Value); if (parentGroup != null) { CurrentGroupTypeId = parentGroup.GroupTypeId; if (!lppLeader.PersonId.HasValue) { nbMessage.Text = "A Leader is required."; nbMessage.Visible = true; return; } if (!GroupLocationsState.Any()) { nbMessage.Text = "A location is required."; nbMessage.Visible = true; return; } if (CurrentGroupTypeId == 0) { return; } Group group = new Group(); group.IsSystem = false; group.Name = string.Empty; // add/update any group locations that were added or changed in the UI (we already removed the ones that were removed above) foreach (var groupLocationState in GroupLocationsState) { GroupLocation groupLocation = group.GroupLocations.Where(l => l.Guid == groupLocationState.Guid).FirstOrDefault(); if (groupLocation == null) { groupLocation = new GroupLocation(); group.GroupLocations.Add(groupLocation); } else { groupLocationState.Id = groupLocation.Id; groupLocationState.Guid = groupLocation.Guid; var selectedSchedules = groupLocationState.Schedules.Select(s => s.Guid).ToList(); foreach (var schedule in groupLocation.Schedules.Where(s => !selectedSchedules.Contains(s.Guid)).ToList()) { groupLocation.Schedules.Remove(schedule); } } groupLocation.CopyPropertiesFrom(groupLocationState); var existingSchedules = groupLocation.Schedules.Select(s => s.Guid).ToList(); foreach (var scheduleState in groupLocationState.Schedules.Where(s => !existingSchedules.Contains(s.Guid)).ToList()) { var schedule = scheduleService.Get(scheduleState.Guid); if (schedule != null) { groupLocation.Schedules.Add(schedule); } } } GroupMember leader = new GroupMember(); leader.GroupMemberStatus = GroupMemberStatus.Active; leader.PersonId = lppLeader.PersonId.Value; leader.Person = new PersonService(rockContext).Get(lppLeader.PersonId.Value); leader.GroupRole = parentGroup.GroupType.Roles.Where(r => r.IsLeader).FirstOrDefault() ?? parentGroup.GroupType.DefaultGroupRole; group.Name = String.Format("{0}, {1}", leader.Person.NickName, leader.Person.LastName); group.Description = tbDescription.Text; group.CampusId = parentGroup.CampusId; group.GroupTypeId = CurrentGroupTypeId; group.ParentGroupId = parentGroupId; group.IsSecurityRole = false; group.IsActive = true; group.IsPublic = true; if (dpStartDate.SelectedDate.HasValue) { group.CreatedDateTime = dpStartDate.SelectedDate.Value; } group.Members.Add(leader); string iCalendarContent = string.Empty; // If unique schedule option was selected, but a schedule was not defined, set option to 'None' var scheduleType = rblScheduleSelect.SelectedValueAsEnum <ScheduleType>(ScheduleType.None); if (scheduleType == ScheduleType.Custom) { iCalendarContent = sbSchedule.iCalendarContent; var calEvent = ScheduleICalHelper.GetCalenderEvent(iCalendarContent); if (calEvent == null || calEvent.DTStart == null) { scheduleType = ScheduleType.None; } } if (scheduleType == ScheduleType.Weekly) { if (!dowWeekly.SelectedDayOfWeek.HasValue) { scheduleType = ScheduleType.None; } } int?oldScheduleId = hfUniqueScheduleId.Value.AsIntegerOrNull(); if (scheduleType == ScheduleType.Custom || scheduleType == ScheduleType.Weekly) { if (!oldScheduleId.HasValue || group.Schedule == null) { group.Schedule = new Schedule(); } if (scheduleType == ScheduleType.Custom) { group.Schedule.iCalendarContent = iCalendarContent; group.Schedule.WeeklyDayOfWeek = null; group.Schedule.WeeklyTimeOfDay = null; } else { group.Schedule.iCalendarContent = null; group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek; group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime; } } else { // If group did have a unique schedule, delete that schedule if (oldScheduleId.HasValue) { var schedule = scheduleService.Get(oldScheduleId.Value); if (schedule != null && string.IsNullOrEmpty(schedule.Name)) { scheduleService.Delete(schedule); } } if (scheduleType == ScheduleType.Named) { group.ScheduleId = spSchedule.SelectedValueAsId(); } else { group.ScheduleId = null; } } group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phGroupAttributes, group); group.GroupType = new GroupTypeService(rockContext).Get(group.GroupTypeId); if (group.ParentGroupId.HasValue) { group.ParentGroup = groupService.Get(group.ParentGroupId.Value); } if (!Page.IsValid) { return; } // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass. // So, make sure a message is displayed in the validation summary cvGroup.IsValid = group.IsValid; if (!cvGroup.IsValid) { cvGroup.ErrorMessage = group.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />"); return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction(() => { var adding = group.Id.Equals(0); if (adding) { groupService.Add(group); } rockContext.SaveChanges(); if (adding) { // add ADMINISTRATE to the person who added the group Rock.Security.Authorization.AllowPerson(group, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext); } group.SaveAttributeValues(rockContext); }); bool isNowSecurityRole = group.IsActive && (group.GroupTypeId == roleGroupTypeId); if (isNowSecurityRole) { // new security role, flush Rock.Security.Authorization.Flush(); } AttributeCache.FlushEntityAttributes(); pnlDetails.Visible = false; pnlSuccess.Visible = true; nbSuccess.Text = string.Format("Your group ({0}) has been created", group.Name); string linkedPage = LinkedPageRoute("RedirectPage"); int secondsBeforeRedirect = GetAttributeValue("SecondsBeforeRedirect").AsInteger() * 1000; ScriptManager.RegisterClientScriptBlock(upnlGroupDetail, typeof(UpdatePanel), "Redirect", string.Format("console.log('{0}'); setTimeout(function() {{ window.location.replace('{0}?GroupId={2}') }}, {1});", linkedPage, secondsBeforeRedirect, group.Id), true); } } }