/// <summary> /// Handles the RowDataBound event of the gGroupLocationSchedule control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param> protected void gGroupLocationSchedule_RowDataBound(object sender, GridViewRowEventArgs e) { // add tooltip to header columns if (e.Row.RowType == DataControlRowType.Header) { var scheduleService = new ScheduleService(new RockContext()); foreach (var cell in e.Row.Cells.OfType <DataControlFieldCell>()) { if (cell.ContainingField is CheckBoxEditableField) { CheckBoxEditableField checkBoxEditableField = cell.ContainingField as CheckBoxEditableField; int scheduleId = int.Parse(checkBoxEditableField.DataField.Replace("scheduleField_", string.Empty)); var schedule = scheduleService.Get(scheduleId); if (schedule != null) { cell.Attributes["title"] = schedule.ToString(); } } } } else { if (e.Row.DataItem != null) { var dataRow = e.Row.DataItem as System.Data.DataRowView; Literal lGroupName = e.Row.FindControl("lGroupName") as Literal; if (lGroupName != null) { lGroupName.Text = string.Format("{0}<br /><small>{1}</small>", dataRow["GroupName"] as string, dataRow["GroupPath"] as string); } Literal lLocationName = e.Row.FindControl("lLocationName") as Literal; if (lLocationName != null) { lLocationName.Text = string.Format("{0}<br /><small>{1}</small>", dataRow["LocationName"] as string, dataRow["LocationPath"] as string); } } } }
/// <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(); }
public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var scheduleGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "ScheduleAttribute").AsGuid()).AsGuid(); ScheduleService scheduleService = new ScheduleService(rockContext); var schedule = scheduleService.Get(scheduleGuid); if (schedule != null) { // Now store the target attribute var targetAttribute = AttributeCache.Get(GetActionAttributeValue(action, "DateTimeAttribute").AsGuid(), rockContext); if (targetAttribute.EntityTypeId == new Rock.Model.Workflow().TypeId) { action.Activity.Workflow.SetAttributeValue(targetAttribute.Key, schedule.GetNextStartDateTime(Rock.RockDateTime.Now).ToString()); } else if (targetAttribute.EntityTypeId == new WorkflowActivity().TypeId) { action.Activity.SetAttributeValue(targetAttribute.Key, schedule.GetNextStartDateTime(Rock.RockDateTime.Now).ToString()); } } return(true); }
/// <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 btnCancel 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 btnCancel_Click(object sender, EventArgs e) { if (hfScheduleId.Value.Equals("0")) { // Cancelling on Add. Return to tree view with parent category selected var qryParams = new Dictionary <string, string>(); string parentCategoryId = PageParameter("parentCategoryId"); if (!string.IsNullOrWhiteSpace(parentCategoryId)) { qryParams["CategoryId"] = parentCategoryId; } NavigateToPage(this.CurrentPage.Guid, qryParams); } else { // Cancelling on Edit. Return to Details var service = new ScheduleService(); var item = service.Get(int.Parse(hfScheduleId.Value)); ShowReadonlyDetails(item); } }
private void HydrateStatus(CheckInStatus status) { RockContext rockContext = new RockContext(); GroupService groupService = new GroupService(rockContext); PersonService personService = new PersonService(rockContext); LocationService locationService = new LocationService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); foreach (var family in status.Families) { family.Group = groupService.Get(family.Group.Id); family.Group.LoadAttributes(); foreach (var person in family.People) { person.Person = personService.Get(person.Person.Id); person.Person.LoadAttributes(); foreach (var grouptype in person.GroupTypes) { //We left the cached items in group type foreach (var group in grouptype.Groups) { group.Group = groupService.Get(group.Group.Id); group.Group.LoadAttributes(); foreach (var location in group.Locations) { location.Location = locationService.Get(location.Location.Id); location.Location.LoadAttributes(); foreach (var schedule in location.Schedules) { schedule.Schedule = scheduleService.Get(schedule.Schedule.Id); schedule.Schedule.LoadAttributes(); } } } } } } }
/// <summary> /// Handles the RowDataBound event of the gGroupLocationSchedule control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param> protected void gGroupLocationSchedule_RowDataBound(object sender, GridViewRowEventArgs e) { // add tooltip to header columns if (e.Row.RowType == DataControlRowType.Header) { var scheduleService = new ScheduleService(new RockContext()); foreach (var cell in e.Row.Cells.OfType <DataControlFieldCell>()) { if (cell.ContainingField is CheckBoxEditableField) { CheckBoxEditableField checkBoxEditableField = cell.ContainingField as CheckBoxEditableField; int scheduleId = int.Parse(checkBoxEditableField.DataField.Replace("scheduleField_", string.Empty)); var schedule = scheduleService.Get(scheduleId); if (schedule != null) { cell.Attributes["title"] = schedule.ToString(); } } } } }
public void EventItemOccurrence_ModifiedWithInactiveSchedule_HasNullNextDate() { var rockContext = new RockContext(); // Get existing schedules. var scheduleService = new ScheduleService(rockContext); var scheduleSat1630 = scheduleService.Get(ScheduleSat1630Guid.AsGuid()); // Set the schedule to inactive. scheduleSat1630.IsActive = false; rockContext.SaveChanges(); // Add an event occurrence with the inactive schedule var financeEvent1 = EventItemOccurrenceAddOrUpdateInstance(rockContext, ScheduleSat1630Guid.AsGuid(), deleteExistingInstance: true); rockContext.SaveChanges(); // Verify that the NextDateTime is correctly set. Assert.IsNull(financeEvent1.NextStartDateTime); // Set the schedule to active. scheduleSat1630.IsActive = true; rockContext.SaveChanges(); }
/// <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); } } }
private List <StatisticRow> GetDataForDateRange(DateTime startDate, DateTime endDate) { var entityTypeGroupGuid = Rock.SystemGuid.EntityType.GROUP.AsGuid(); var groupEntityType = EntityTypeCache.Read(entityTypeGroupGuid); int entityTypeScheduleEntityId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.SCHEDULE.AsGuid()).Id; var rockContext = new RockContext(); rockContext.Database.CommandTimeout = 2600; var metricService = new MetricService(rockContext); var metricValueService = new MetricValueService(rockContext); var scheduleService = new ScheduleService(rockContext); var groupService = new GroupService(rockContext); var attendanceService = new AttendanceService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var metricCategoryGuidList = GetAttributeValue("Metrics").SplitDelimitedValues().AsGuidList(); var attendanceGroupGuidList = GetAttributeValue("AttendanceGroups").SplitDelimitedValues().AsGuidList(); var parentMetricVolunteerGroupGuids = GetAttributeValue("ServiceVolunteerGroups").SplitDelimitedValues().AsGuidList(); var attendanceGroups = groupService.GetByGuids(attendanceGroupGuidList); var parentMetricVolunteerGroups = groupService.GetByGuids(parentMetricVolunteerGroupGuids); var metrics = metricService.GetByGuids(metricCategoryGuidList).Distinct().ToList(); var datasource = new List <StatisticRow>(); var metricVolunteerGroups = new List <Group>(); foreach (var parentMetricVolunteerGroup in parentMetricVolunteerGroups) { metricVolunteerGroups.Add(parentMetricVolunteerGroup); metricVolunteerGroups.AddRange(groupService.GetAllDescendents(parentMetricVolunteerGroup.Id)); } var metricVolunteerGroupIds = metricVolunteerGroups.Select(g => g.Id).ToList(); var metricVolunteerAttendanceData = attendanceService.Queryable().Where(a => a.GroupId.HasValue && metricVolunteerGroupIds.Contains(a.GroupId.Value) && a.StartDateTime >= startDate && a.StartDateTime <= endDate); foreach (var metric in metrics) { var metricData = metricValueService.Queryable("MetricValuePartitions").Where(mv => mv.MetricValueDateTime >= startDate && mv.MetricValueDateTime <= endDate && mv.MetricId == metric.Id && mv.MetricValuePartitions.FirstOrDefault( mvp => mvp.MetricPartition.EntityTypeId == entityTypeScheduleEntityId).EntityId.HasValue ) .GroupBy( mv => mv.MetricValuePartitions.FirstOrDefault( mvp => mvp.MetricPartition.EntityTypeId == entityTypeScheduleEntityId).EntityId.Value) .ToList() .Select(mv => { var service = scheduleService.Get(mv.Key); return(new StatisticRow { ScheduleDateRanges = GetScheduleDateRanges(service, startDate, endDate), RowId = metric.Id + "-" + mv.Key, SortValue = 0, IsTotal = false, Area = metric.Title, Subarea = "Head Count", StartTime = service.WeeklyTimeOfDay ?? service.StartTimeOfDay, DayOfWeek = service.WeeklyDayOfWeek ?? GetLastDayOfWeek(service, startDate, endDate), Service = service.Name, Count = mv.Sum(a => a.YValue).HasValue ? decimal.ToInt32(mv.Sum(a => a.YValue).Value) : 0, MetricNote = mv.Max(a => a.Note), Value = mv }); }) .ToList(); foreach (var row in metricData) { int volunteers = 0; int total = row.Value.Sum(a => a.YValue).HasValue ? decimal.ToInt32(row.Value.Sum(a => a.YValue).Value) : 0; if (metricVolunteerAttendanceData.Any()) { volunteers += row.ScheduleDateRanges.Sum(dateRange => metricVolunteerAttendanceData.Count(a => (a.DidAttend == null || a.DidAttend.Value) && a.StartDateTime >= dateRange.Start && a.StartDateTime <= dateRange.End)); row.Total = total + volunteers; row.Volunteers = volunteers; } } datasource.AddRange(metricData); if (metricData.Count > 1) { var subTotalRow = new StatisticRow { RowId = metric.Id.ToString(), SortValue = 0, IsTotal = true, Area = metric.Title, Subarea = "Head Count", Service = "Sub-Total", Count = metricData.Sum(mv => mv.Count), Volunteers = metricData.Sum(mv => mv.Volunteers), Total = metricData.Sum(mv => mv.Total) }; datasource.Add(subTotalRow); } } var totalRow = new StatisticRow { RowId = "HeadcountTotal", SortValue = 1, IsTotal = true, Area = "Head Count Total", Subarea = "Head Count", Service = "Total", Count = datasource.Where(row => !row.IsTotal).Sum(row => row.Count), Volunteers = datasource.Where(row => !row.IsTotal).Sum(mv => mv.Volunteers), Total = datasource.Where(row => !row.IsTotal).Sum(mv => mv.Total) }; datasource.Add(totalRow); string attributeKeyString = GetAttributeValue("VolunteerGroupAttributeKey"); var volunteerGroupAttributeIdList = attributeService.Queryable() .Where(a => a.Key == attributeKeyString && a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeId == groupEntityType.Id).Select(a => a.Id); if (volunteerGroupAttributeIdList.Any()) { // Find the groups that attribute values that have the maaping between group (the entityId) and the place they should be grouped with attending (value) var volunteerGroupMappingList = attributeValueService.Queryable().Where(av => volunteerGroupAttributeIdList.Contains(av.AttributeId) && av.Value != null) .ToList() .Select(av => new { VolunteerAttendanceGroupGuid = av.Value.AsGuid(), VolunteerGroupId = av.EntityId }).ToList(); foreach (var attendanceGroup in attendanceGroups) { foreach (var attendanceChildGroup in attendanceGroup.Groups) { var attendanceChildDescendantGroups = groupService.GetAllDescendents(attendanceChildGroup.Id).ToList(); // Include child group in for cases where attendance needs to be mapped to an area not a specific group (production team isn't for a specific children's group -- it's associated with TC kids as a whole) attendanceChildDescendantGroups.Add(attendanceChildGroup); var attendanceChildDescendantGroupIds = attendanceChildDescendantGroups.Select(g => g.Id); var volunteerGroupIds = volunteerGroupMappingList .Where(vgm => attendanceChildDescendantGroups.Any(g => g.Guid == vgm.VolunteerAttendanceGroupGuid)) .Select(vgm => vgm.VolunteerGroupId).ToList(); var volunteerGroupAttendance = attendanceService.Queryable() .Where(a => volunteerGroupIds.Any(id => id != null && id == a.Group.Id) && a.StartDateTime >= startDate && a.StartDateTime <= endDate) .ToList(); var acg = attendanceChildGroup; var childGroupAttendance = attendanceService.Queryable().Where(a => a.GroupId != null && a.StartDateTime >= startDate && a.StartDateTime <= endDate && (a.GroupId == acg.Id || attendanceChildDescendantGroupIds.Any(id => id == a.GroupId)) && (a.DidAttend == null || a.DidAttend.Value)) .GroupBy(a => a.ScheduleId) .ToList(); // ag is created to prevent a warn "Access to foreach variable in closure." var ag = attendanceGroup; var statisticRows = childGroupAttendance.Select(a => { var attendance = a.FirstOrDefault(); var scheduleDateRanges = GetScheduleDateRanges(attendance.Schedule, startDate, endDate); var row = new StatisticRow(); row.RowId = acg.Id + "-" + a.Key; row.SortValue = 2; row.IsTotal = false; row.Area = ag.Name; row.Subarea = acg.Name; row.Service = attendance.Schedule.Name; row.StartTime = attendance.Schedule.WeeklyTimeOfDay ?? attendance.Schedule.StartTimeOfDay; row.DayOfWeek = attendance.Schedule.WeeklyDayOfWeek ?? GetLastDayOfWeek(attendance.Schedule, startDate, endDate); row.Count = a.Count(); row.Volunteers = volunteerGroupAttendance.Count(b => scheduleDateRanges.Any(s => b.StartDateTime >= s.Start && b.StartDateTime <= s.End)); row.Total = a.Count() + volunteerGroupAttendance.Count(b => scheduleDateRanges.Any(s => b.StartDateTime >= s.Start && b.StartDateTime <= s.End)); return(row); }).ToList(); datasource.AddRange(statisticRows); if (statisticRows.Count > 1) { var subTotalRow = new StatisticRow { RowId = attendanceChildGroup.Id.ToString(), SortValue = 2, IsTotal = true, Area = attendanceGroup.Name, Subarea = attendanceChildGroup.Name, Service = "Sub-Total", Count = statisticRows.Sum(cg => cg.Count), Volunteers = statisticRows.Sum(cg => cg.Volunteers), Total = statisticRows.Sum(cg => cg.Total) }; datasource.Add(subTotalRow); } } } } datasource.Add(new StatisticRow { RowId = "Total", SortValue = 3, IsTotal = true, Area = "Grand Total", Subarea = "Total", Service = "Total", Count = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Count), Volunteers = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Volunteers), Total = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Total) }); return(datasource); }
public void RockCleanup_Execute_ShouldUpdateEventItemOccurrences() { var referenceDate = new DateTime(2020, 1, 1); // Get the sample data schedule for Saturday 4:30pm. var rockContext = new RockContext(); var scheduleService = new ScheduleService(rockContext); var schedule = scheduleService.Get(TestGuids.Schedules.ScheduleSat1630Guid.AsGuid()); // Create a new inactive schedule. var scheduleInactive = scheduleService.Get(testScheduleGuid); if (scheduleInactive == null) { scheduleInactive = new Schedule(); scheduleService.Add(scheduleInactive); } scheduleInactive.Name = "Test Schedule"; scheduleInactive.Guid = testScheduleGuid; scheduleInactive.IsActive = false; rockContext.SaveChanges(); // Create the Test Events. var eventItemService = new EventItemService(rockContext); // Test Event 1 (active) var testEvent1 = eventItemService.Get(testEvent1Guid); if (testEvent1 != null) { eventItemService.Delete(testEvent1); rockContext.SaveChanges(); } testEvent1 = new EventItem(); testEvent1.Guid = testEvent1Guid; testEvent1.Name = "Test Event 1"; eventItemService.Add(testEvent1); // Add an occurrence with a future schedule and no NextDateTime value. // When the cleanup task executes, this should be updated to the next occurrence after the reference date. var testOccurrence11 = new EventItemOccurrence(); testOccurrence11.ScheduleId = schedule.Id; testOccurrence11.Guid = testEventOccurrence11Guid; testOccurrence11.NextStartDateTime = null; testEvent1.EventItemOccurrences.Add(testOccurrence11); // Add an occurrence with a NextDateTime that is prior to the reference date. // When the cleanup task executes, this should be updated to the next occurrence after the reference date. var testOccurrence12 = new EventItemOccurrence(); testOccurrence12.ScheduleId = schedule.Id; testOccurrence12.Guid = testEventOccurrence12Guid; testOccurrence12.NextStartDateTime = referenceDate.AddDays(-1); testEvent1.EventItemOccurrences.Add(testOccurrence12); // Add an occurrence with a NextDateTime and an inactive Schedule. // When the cleanup task executes, the NextDateTime should be set to null. var testOccurrence13 = new EventItemOccurrence(); testOccurrence13.ScheduleId = scheduleInactive.Id; testOccurrence13.Guid = testEventOccurrence13Guid; testOccurrence13.NextStartDateTime = referenceDate.AddDays(7); testEvent1.EventItemOccurrences.Add(testOccurrence13); // Test Event 2 (inactive) var testEvent2 = eventItemService.Get(testEvent2Guid); if (testEvent2 != null) { eventItemService.Delete(testEvent2); rockContext.SaveChanges(); } testEvent2 = new EventItem(); testEvent2.Guid = testEvent2Guid; testEvent2.Name = "Test Event 2"; testEvent2.IsActive = false; eventItemService.Add(testEvent2); // Add an occurrence with a future schedule and a NextDateTime value. // When the cleanup task executes, the NextDateTime should be set to null. var testOccurrence21 = new EventItemOccurrence(); testOccurrence21.ScheduleId = schedule.Id; testOccurrence21.Guid = testEventOccurrence21Guid; testOccurrence21.NextStartDateTime = referenceDate; testEvent2.EventItemOccurrences.Add(testOccurrence21); // Save changes without triggering the pre-save, to avoid updating the NextEventDate field. rockContext.SaveChanges(new SaveChangesArgs { DisablePrePostProcessing = true }); // Run the cleanup task to verify the results for the reference date. RunRockCleanupTaskUpdateEventNextOccurrenceDatesAndVerify(referenceDate); // Re-run the task to verify that the results are adjusted for the current date. RunRockCleanupTaskUpdateEventNextOccurrenceDatesAndVerify(RockDateTime.Now); }
private void BindGrid() { gReport.Visible = false; nbNotification.Visible = false; RockContext rockContext = new RockContext(); AttendanceOccurrenceService attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext); AttendanceService attendanceService = new AttendanceService(rockContext); LocationService locationService = new LocationService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); var location = lpLocation.Location; if (location == null || dpDate.SelectedDate == null) { return; } //Set the name of the export List <string> locationNameList = new List <string>(); var locationForExport = location; while (true) { if (locationForExport == null) { break; } locationNameList.Add(locationForExport.Name); locationForExport = locationForExport.ParentLocation; } locationNameList.Reverse(); gReport.ExportTitleName = dpDate.SelectedDate.Value.ToString("MM/dd/yyyy") + " -- "; if (tgChildLocations.Checked) { gReport.ExportTitleName += " Child Locations of: "; } gReport.ExportTitleName += string.Join(" > ", locationNameList); var schedule = scheduleService.Get(spSchedule.SelectedValueAsId() ?? 0); if (schedule != null) { gReport.ExportTitleName += " (" + schedule.Name + ")"; } var fileName = dpDate.SelectedDate.Value.ToString("MM.dd.yyyy") + (tgChildLocations.Checked ? "_ChildLocationsOf_" : "_") + location.Name; if (schedule != null) { fileName += "_" + schedule.Name; } gReport.ExportFilename = fileName; //Get child locations if needed var locationIds = new List <int> { location.Id }; if (tgChildLocations.Checked) { List <Location> childLocations = GetChildLocations(location); locationIds.AddRange(childLocations.Select(l => l.Id)); } var attendanceOccurrencesQry = attendanceOccurrenceService .Queryable() .Where(ao => ao.OccurrenceDate == (dpDate.SelectedDate ?? RockDateTime.Now)) .Where(ao => locationIds.Contains(ao.LocationId ?? 0)) .Where(ao => ao.Group != null && ao.Schedule != null); var scheduleId = spSchedule.SelectedValueAsId(); if (scheduleId != null) { attendanceOccurrencesQry = attendanceOccurrencesQry.Where(ao => ao.ScheduleId == scheduleId); } var attendanceOccurrences = attendanceOccurrencesQry .Select(ao => ao.Id) .ToList(); var attendances = attendanceService.Queryable("PersonAlias, PersonAlias.Person, Occurrence, Occurrence.Group, Occurrence.Location, Occurrence.Schedule, Device") .Where(a => attendanceOccurrences.Contains(a.OccurrenceId)) .ToList(); if (!attendances.Any()) { nbNotification.Visible = true; nbNotification.Text = "Could not find any attendances with these parameters"; return; } var records = new List <AttendanceRecord>(); var volunteerGroupIds = KioskCountUtility.GetVolunteerGroupIds(); foreach (var attendance in attendances) { var record = new AttendanceRecord { PersonId = attendance.PersonAlias.Person.Id, PersonName = attendance.PersonAlias.Person.FullNameReversed, Age = attendance.PersonAlias.Person.Age, Schedule = attendance.Occurrence.Schedule.Name, Location = attendance.Occurrence.Location.Name, Group = attendance.Occurrence.Group.Name, CheckInTime = attendance.CreatedDateTime, EntryTime = attendance.StartDateTime, ExitTime = attendance.EndDateTime, DidAttend = attendance.DidAttend, IsVolunteer = volunteerGroupIds.Contains(attendance.Occurrence.GroupId ?? 0), Device = attendance.Device != null ? attendance.Device.Name : "Room Scanner" }; if (attendance.ForeignId != null) { var subLocation = locationService.Get(attendance.ForeignId ?? 0); if (subLocation != null) { record.SubLocation = subLocation.Name; } } if (record.CheckInTime >= record.EntryTime && record.Device != "Room Scanner") { record.EntryTime = null; } records.Add(record); } records = records .OrderBy(r => r.CheckInTime) .ToList(); gReport.Visible = true; gReport.DataSource = records; gReport.DataBind(); }
/// <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); } } }
/// <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); }
private void LoadSettings() { using (var context = new RockContext()) { GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(context); ScheduleService scheduleService = new ScheduleService(context); if (Settings.SignupPage() != null) { ppSignupPage.SetValue(Settings.SignupPage().Id); } // Load all the partition settings if (Settings.EntityGuid != Guid.Empty) { pnlPartitions.Visible = true; } rptPartions.DataSource = Settings.Partitions; rptPartions.DataBind(); // Remove all existing dynamic columns while (gCounts.Columns.Count > 1) { gCounts.Columns.RemoveAt(0); } DataTable dt = new DataTable(); dt.Columns.Add("RowId"); foreach (var partition in Settings.Partitions) { DataTable dtTmp = dt.Copy(); dt.Clear(); String column = partition.PartitionType; if (partition.PartitionType == "DefinedType") { var definedType = Rock.Web.Cache.DefinedTypeCache.Read(partition.PartitionValue.AsGuid()); if (definedType == null) { break; } column = definedType.Name; } var boundField = new BoundField() { HeaderText = column, DataField = column + partition.Guid }; gCounts.Columns.Insert(gCounts.Columns.Count - 1, boundField); dt.Columns.Add(column + partition.Guid); switch (partition.PartitionType) { case "DefinedType": var definedType = Rock.Web.Cache.DefinedTypeCache.Read(partition.PartitionValue.AsGuid()); foreach (var value in definedType.DefinedValues) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, value.Guid, value.Value); } break; case "Campus": if (partition.PartitionValue != null) { var selectedCampuses = partition.PartitionValue.Split(','); foreach (string campusGuid in selectedCampuses) { var campus = CampusCache.Read(campusGuid.AsGuid()); if (campus != null) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, campus.Guid, campus.Name); } } } break; case "Schedule": if (partition.PartitionValue != null) { var selectedSchedules = partition.PartitionValue.Split(','); foreach (string scheduleGuid in selectedSchedules) { var schedule = scheduleService.Get(scheduleGuid.AsGuid()); if (schedule != null) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, schedule.Guid, schedule.Name); } } } break; case "Role": if (partition.PartitionValue != null) { var selectedRoles = partition.PartitionValue.Split(','); List <GroupTypeRole> roles = new List <GroupTypeRole>(); foreach (string roleGuid in selectedRoles) { GroupTypeRole role = groupTypeRoleService.Get(roleGuid.AsGuid()); if (role != null) { roles.Add(role); } } roles.OrderBy(r => r.GroupTypeId).ThenBy(r => r.Order); foreach (GroupTypeRole role in roles) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, role.Guid, role.Name); } } break; } } if (Settings.Partitions.Count > 0 && dt.Rows.Count > 0) { var dv = dt.AsEnumerable(); var dvOrdered = dv.OrderBy(r => r.Field <String>(dt.Columns.Cast <DataColumn>().Select(c => c.ColumnName).Skip(1).FirstOrDefault())); foreach (var column in dt.Columns.Cast <DataColumn>().Select(c => c.ColumnName).Skip(2)) { dvOrdered = dvOrdered.ThenBy(r => r.Field <String>(column)); break; } dt = dvOrdered.CopyToDataTable(); gCounts.DataSource = dt; gCounts.DataBind(); } } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { if (!Page.IsPostBack) { var output = RockCache.Get("TimedContentChannel_" + this.BlockId.ToString()); if (output != null) { ltOutput.Text = output as string; return; } RockContext rockContext = new RockContext(); ContentChannelService contentChannelService = new ContentChannelService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); var cacheLength = GetAttributeValue("MaximumCache").AsDouble(); var contentChannelGuid = GetAttributeValue("ContentChannel").AsGuid(); var contentChannel = contentChannelService.Get(contentChannelGuid); if (contentChannel == null) { return; } var contentChannelItems = contentChannel.Items.OrderBy(i => i.Order).ToList(); List <ContentChannelItem> mergeItems = new List <ContentChannelItem>(); var scheduleKey = GetAttributeValue("TimerAttributeKey"); foreach (var item in contentChannelItems) { item.LoadAttributes(); var scheduleValue = item.GetAttributeValue(scheduleKey); if (scheduleValue.IsNotNullOrWhiteSpace()) { var schedule = scheduleService.Get(scheduleValue.AsGuid()); if (schedule == null) { continue; } if (schedule.WasScheduleActive(Rock.RockDateTime.Now)) { mergeItems.Add(item); var end = schedule.GetCalendarEvent().DTEnd.TimeOfDay; var endMinutes = (end - Rock.RockDateTime.Now.TimeOfDay).TotalSeconds; cacheLength = Math.Min(cacheLength, endMinutes); } else { var nextTime = schedule.GetNextStartDateTime(Rock.RockDateTime.Now); if (nextTime.HasValue) { var time = nextTime.Value - Rock.RockDateTime.Now; var minutes = time.TotalSeconds; cacheLength = Math.Min(cacheLength, minutes); } } } else { mergeItems.Add(item); } } var lava = GetAttributeValue("Lava"); var mergefields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson); mergefields.Add("ContentChannelItems", mergeItems); lava = lava.ResolveMergeFields(mergefields, CurrentPerson, GetAttributeValue("EnabledLavaCommands")); ltOutput.Text = lava; if (cacheLength > 5) //the time could be low enough to throw an error { RockCache.AddOrUpdate("TimedContentChannel_" + this.BlockId.ToString(), "", lava, Rock.RockDateTime.Now.AddSeconds(cacheLength)); } } }
public ActionResult <List <Schedule> > Get() => _scheduleService.Get();
/// <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) { Schedule schedule; var rockContext = new RockContext(); ScheduleService scheduleService = new ScheduleService(rockContext); int scheduleId = int.Parse(hfScheduleId.Value); if (scheduleId == 0) { schedule = new Schedule(); scheduleService.Add(schedule); } else { schedule = scheduleService.Get(scheduleId); } schedule.Name = tbScheduleName.Text; schedule.IsActive = cbIsActive.Checked; schedule.AutoInactivateWhenComplete = cbAutoComplete.Checked; schedule.Description = tbScheduleDescription.Text; schedule.iCalendarContent = sbSchedule.iCalendarContent; schedule.CategoryId = cpCategory.SelectedValueAsInt(); int offsetMins = int.MinValue; if (int.TryParse(nbStartOffset.Text, out offsetMins)) { schedule.CheckInStartOffsetMinutes = offsetMins; } else { schedule.CheckInStartOffsetMinutes = null; } offsetMins = int.MinValue; if (int.TryParse(nbEndOffset.Text, out offsetMins)) { schedule.CheckInEndOffsetMinutes = offsetMins; } else { schedule.CheckInEndOffsetMinutes = null; } schedule.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phAttributes, schedule); if (!schedule.IsValid) { // Controls will render the error messages return; } rockContext.SaveChanges(); schedule.SaveAttributeValues(rockContext); Rock.CheckIn.KioskDevice.Clear(); var qryParams = new Dictionary <string, string>(); qryParams["ScheduleId"] = schedule.Id.ToString(); qryParams["ExpandedIds"] = PageParameter("ExpandedIds"); NavigateToPage(RockPage.Guid, qryParams); }
public SlidesResponse GetSlides(string id) { var rockContext = new RockContext(); var deviceService = new DeviceService(rockContext); var scheduleService = new ScheduleService(rockContext); var contentChannelService = new ContentChannelService(rockContext); var response = new SlidesResponse(); Device device = deviceService.Get(id.AsInteger()); if (device != null) { var campuses = device.Locations.Select(l => l.CampusId).Where(c => c.HasValue && c.Value != 0).Select(c => c.Value).ToList(); device.LoadAttributes(rockContext); var definedValueGuids = device.GetAttributeValue("com_shepherdchurch_ContentSchedules").SplitDelimitedValues().AsGuidList(); List <DefinedValueCache> definedValues = new List <DefinedValueCache>(); // // Build a list of the cached defined values so we can then sort by Order. // foreach (var definedValueGuid in definedValueGuids) { var definedValue = DefinedValueCache.Get(definedValueGuid); if (definedValue != null) { definedValues.Add(definedValue); } } // // Check each defined value they have selected on this device and look for the // first one that is active. // foreach (var definedValue in definedValues.OrderBy(d => d.Order)) { var contentChannel = contentChannelService.Get(definedValue.GetAttributeValue("com_shepherdchurch_ContentChannel").AsGuid()); if (contentChannel != null) { var schedules = definedValue.GetAttributeValues("com_shepherdchurch_Schedules").AsGuidList(); bool scheduleActive = false; // // Check if either no schedules (match by default) or any single schedule // is currently active. // if (!schedules.Any()) { scheduleActive = true; } else { foreach (var guid in schedules) { var schedule = scheduleService.Get(guid); if (schedule.WasScheduleActive(RockDateTime.Now)) { scheduleActive = true; break; } } } // // If the schedule is active, then this is the content channel we are going // to work with. Build our list of image URLs and audio URLs. // if (scheduleActive) { response.Contents = GetContentChannelItems(campuses, contentChannel, rockContext); break; } } } response.GenerateHash(); } return(response); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> /// <param name="parentCategoryId">The parent category id.</param> public void ShowDetail(string itemKey, int itemKeyValue, int?parentCategoryId) { pnlDetails.Visible = false; if (itemKey != "ScheduleId") { return; } var scheduleService = new ScheduleService(new RockContext()); Schedule schedule = null; if (!itemKeyValue.Equals(0)) { schedule = scheduleService.Get(itemKeyValue); } else { schedule = new Schedule { Id = 0, CategoryId = parentCategoryId }; } if (schedule == null) { return; } pnlDetails.Visible = true; hfScheduleId.Value = schedule.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if (!IsUserAuthorized(Authorization.EDIT)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Schedule.FriendlyTypeName); } if (readOnly) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails(schedule); } else { btnEdit.Visible = true; string errorMessage = string.Empty; btnDelete.Visible = scheduleService.CanDelete(schedule, out errorMessage); if (schedule.Id > 0) { ShowReadonlyDetails(schedule); } else { ShowEditDetails(schedule); } } }
/// <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) { using (var rockContext = new RockContext()) { GroupLocationService groupLocationService = new GroupLocationService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); bool schedulesChanged = false; var gridViewRows = gGroupLocationSchedule.Rows; foreach (GridViewRow row in gridViewRows.OfType <GridViewRow>()) { int groupLocationId = int.Parse(gGroupLocationSchedule.DataKeys[row.RowIndex].Value as string); GroupLocation groupLocation = groupLocationService.Get(groupLocationId); if (groupLocation != null) { foreach (var fieldCell in row.Cells.OfType <DataControlFieldCell>()) { var checkBoxTemplateField = fieldCell.ContainingField as CheckBoxEditableField; if (checkBoxTemplateField != null) { CheckBox checkBox = fieldCell.Controls[0] as CheckBox; string dataField = (fieldCell.ContainingField as CheckBoxEditableField).DataField; int scheduleId = int.Parse(dataField.Replace("scheduleField_", string.Empty)); // update GroupLocationSchedule depending on if the Schedule is Checked or not if (checkBox.Checked) { // This schedule is selected, so if GroupLocationSchedule doesn't already have this schedule, add it if (!groupLocation.Schedules.Any(a => a.Id == scheduleId)) { var schedule = scheduleService.Get(scheduleId); groupLocation.Schedules.Add(schedule); schedulesChanged = true; } } else { // This schedule is not selected, so if GroupLocationSchedule has this schedule, delete it if (groupLocation.Schedules.Any(a => a.Id == scheduleId)) { groupLocation.Schedules.Remove(groupLocation.Schedules.FirstOrDefault(a => a.Id == scheduleId)); schedulesChanged = true; } } } } } } if (schedulesChanged) { rockContext.SaveChanges(); if (this.CurrentKioskId.HasValue) { KioskDevice.Flush(this.CurrentKioskId.Value); } } } NavigateToHomePage(); }