/// <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> /// Shows the detail. /// </summary> /// <param name="scheduleId">The schedule identifier.</param> /// <param name="parentCategoryId">The parent category id.</param> public void ShowDetail( int scheduleId, int? parentCategoryId ) { pnlDetails.Visible = false; var scheduleService = new ScheduleService( new RockContext() ); Schedule schedule = null; if ( !scheduleId.Equals( 0 ) ) { schedule = scheduleService.Get( scheduleId ); pdAuditDetails.SetEntity( schedule, ResolveRockUrl( "~" ) ); } if ( schedule == null ) { schedule = new Schedule { Id = 0, CategoryId = parentCategoryId }; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } 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 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> /// Method that will be called on an entity immediately before the item is saved by context /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="entry">The database entity entry.</param> public override void PreSaveChanges(Data.DbContext dbContext, DbEntityEntry entry) { // Set the NextDateTime field to the datetime of the next occurrence, or null if there is no future occurrence. if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { var rockContext = ( RockContext )dbContext; DateTime?nextDate = null; // If the event has a schedule and both the schedule and the event are active, get the next occurrence date. if (ScheduleId != null) { if (Schedule == null) { var scheduleService = new ScheduleService(rockContext); Schedule = scheduleService.Get(ScheduleId.Value); } if (Schedule != null && Schedule.IsActive) { if (EventItem == null) { var eventService = new EventItemService(rockContext); EventItem = eventService.Get(EventItemId); } if (EventItem.IsActive) { nextDate = Schedule.GetNextStartDateTime(RockDateTime.Now); } } } entry.CurrentValues[nameof(NextStartDateTime)] = nextDate; } base.PreSaveChanges(dbContext, entry); }
/// <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 adding groups from the given XML element snippet. /// </summary> /// <param name="elemGroups">The elem groups.</param> /// <param name="rockContext">The rock context.</param> /// <exception cref="System.NotSupportedException"></exception> private void AddGroups( XElement elemGroups, RockContext rockContext ) { // Add groups if ( elemGroups == null ) { return; } GroupService groupService = new GroupService( rockContext ); DefinedTypeCache smallGroupTopicType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.SMALL_GROUP_TOPIC.AsGuid() ); // Next create the group along with its members. foreach ( var elemGroup in elemGroups.Elements( "group" ) ) { Guid guid = elemGroup.Attribute( "guid" ).Value.Trim().AsGuid(); string type = elemGroup.Attribute( "type" ).Value; Group group = new Group() { Guid = guid, Name = elemGroup.Attribute( "name" ).Value.Trim(), IsActive = true, IsPublic = true }; // skip any where there is no group type given -- they are invalid entries. if ( string.IsNullOrEmpty( elemGroup.Attribute( "type" ).Value.Trim() ) ) { return; } int? roleId; GroupTypeCache groupType; switch ( elemGroup.Attribute( "type" ).Value.Trim() ) { case "serving": groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SERVING_TEAM.AsGuid() ); group.GroupTypeId = groupType.Id; roleId = groupType.DefaultGroupRoleId; break; case "smallgroup": groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SMALL_GROUP.AsGuid() ); group.GroupTypeId = groupType.Id; roleId = groupType.DefaultGroupRoleId; break; default: throw new NotSupportedException( string.Format( "unknown group type {0}", elemGroup.Attribute( "type" ).Value.Trim() ) ); } if ( elemGroup.Attribute( "description" ) != null ) { group.Description = elemGroup.Attribute( "description" ).Value; } if ( elemGroup.Attribute( "parentGroupGuid" ) != null ) { var parentGroup = groupService.Get( elemGroup.Attribute( "parentGroupGuid" ).Value.AsGuid() ); if ( parentGroup != null ) { group.ParentGroupId = parentGroup.Id; } } // Set the group's meeting location if ( elemGroup.Attribute( "meetsAtHomeOfFamily" ) != null ) { int meetingLocationValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION.AsGuid() ).Id; var groupLocation = new GroupLocation() { IsMappedLocation = false, IsMailingLocation = false, GroupLocationTypeValueId = meetingLocationValueId, LocationId = _familyLocationDictionary[elemGroup.Attribute( "meetsAtHomeOfFamily" ).Value.AsGuid()], }; // Set the group location's GroupMemberPersonId if given (required?) if ( elemGroup.Attribute( "meetsAtHomeOfPerson" ) != null ) { groupLocation.GroupMemberPersonAliasId = _peopleAliasDictionary[elemGroup.Attribute( "meetsAtHomeOfPerson" ).Value.AsGuid()]; } group.GroupLocations.Add( groupLocation ); } group.LoadAttributes( rockContext ); // Set the study topic if ( elemGroup.Attribute( "studyTopic" ) != null ) { var topic = elemGroup.Attribute( "studyTopic" ).Value; DefinedValue smallGroupTopicDefinedValue = _smallGroupTopicDefinedType.DefinedValues.FirstOrDefault( a => a.Value == topic ); // add it as new if we didn't find it. if ( smallGroupTopicDefinedValue == null ) { smallGroupTopicDefinedValue = AddDefinedTypeValue( topic, _smallGroupTopicDefinedType, rockContext ); } group.SetAttributeValue( "Topic", smallGroupTopicDefinedValue.Guid.ToString() ); } // Set the schedule and meeting time if ( elemGroup.Attribute( "groupSchedule" ) != null ) { string[] schedule = elemGroup.Attribute( "groupSchedule" ).Value.SplitDelimitedValues( whitespace: false ); if ( schedule[0] == "weekly" ) { var dow = schedule[1]; var time = schedule[2]; AddWeeklySchedule( group, dow, time ); } } // Add each person as a member foreach ( var elemPerson in elemGroup.Elements( "person" ) ) { Guid personGuid = elemPerson.Attribute( "guid" ).Value.Trim().AsGuid(); GroupMember groupMember = new GroupMember(); groupMember.GroupMemberStatus = GroupMemberStatus.Active; if ( elemPerson.Attribute( "isLeader" ) != null ) { bool isLeader = elemPerson.Attribute( "isLeader" ).Value.Trim().AsBoolean(); if ( isLeader ) { var gtLeaderRole = groupType.Roles.Where( r => r.IsLeader ).FirstOrDefault(); if ( gtLeaderRole != null ) { groupMember.GroupRoleId = gtLeaderRole.Id; } } } else { groupMember.GroupRoleId = roleId ?? -1; } groupMember.PersonId = _peopleDictionary[personGuid]; group.Members.Add( groupMember ); } groupService.Add( group ); // Now we have to save changes in order for the attributes to be saved correctly. rockContext.SaveChanges(); group.SaveAttributeValues( rockContext ); if ( !_groupDictionary.ContainsKey( group.Guid ) ) { _groupDictionary.Add( group.Guid, group.Id ); } // Now add any group location schedules LocationService locationService = new LocationService( rockContext ); ScheduleService scheduleService = new ScheduleService( rockContext ); Guid locationTypeMeetingLocationGuid = new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION ); var locationTypeMeetingLocationId = Rock.Web.Cache.DefinedValueCache.Read( locationTypeMeetingLocationGuid ).Id; foreach ( var elemLocation in elemGroup.Elements( "location" ) ) { Guid locationGuid = elemLocation.Attribute( "guid" ).Value.Trim().AsGuid(); Location location = locationService.Get( locationGuid ); GroupLocation groupLocation = new GroupLocation(); groupLocation.Location = location; groupLocation.GroupLocationTypeValueId = locationTypeMeetingLocationId; group.GroupLocations.Add( groupLocation ); foreach ( var elemSchedule in elemLocation.Elements( "schedule" ) ) { try { Guid scheduleGuid = elemSchedule.Attribute( "guid" ).Value.Trim().AsGuid(); Schedule schedule = scheduleService.Get( scheduleGuid ); groupLocation.Schedules.Add( schedule ); } catch { } } TimeSpan ts = _stopwatch.Elapsed; AppendFormat( "{0:00}:{1:00}.{2:00} group location schedules added<br/>", ts.Minutes, ts.Seconds, ts.Milliseconds / 10 ); } } }
/// <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.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; } if ( !schedule.IsValid ) { // Controls will render the error messages return; } rockContext.SaveChanges(); var qryParams = new Dictionary<string, string>(); qryParams["ScheduleId"] = schedule.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the btnEdit 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 btnEdit_Click( object sender, EventArgs e ) { var service = new ScheduleService( new RockContext() ); var item = service.Get( int.Parse( hfScheduleId.Value ) ); ShowEditDetails( item ); }
/// <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 rockContext = new RockContext(); var service = new ScheduleService( rockContext ); 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 ); rockContext.SaveChanges(); // reload page, selecting the deleted data view's parent var qryParams = new Dictionary<string, string>(); if ( categoryId != null ) { qryParams["CategoryId"] = categoryId.ToString(); } 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 ) { Group group; bool wasSecurityRole = false; bool triggersUpdated = false; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); GroupLocationService groupLocationService = new GroupLocationService( rockContext ); GroupRequirementService groupRequirementService = new GroupRequirementService( rockContext ); GroupMemberWorkflowTriggerService groupMemberWorkflowTriggerService = new GroupMemberWorkflowTriggerService( rockContext ); ScheduleService scheduleService = new ScheduleService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext ); CategoryService categoryService = new CategoryService( rockContext ); var roleGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ); int roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : int.MinValue; if ( CurrentGroupTypeId == 0 ) { ddlGroupType.ShowErrorMessage( Rock.Constants.WarningMessage.CannotBeBlank( GroupType.FriendlyTypeName ) ); return; } int groupId = hfGroupId.Value.AsInteger(); if ( groupId == 0 ) { group = new Group(); group.IsSystem = false; group.Name = string.Empty; } else { group = groupService.Queryable( "Schedule,GroupLocations.Schedules" ).Where( g => g.Id == groupId ).FirstOrDefault(); wasSecurityRole = group.IsActive && ( group.IsSecurityRole || group.GroupTypeId == roleGroupTypeId ); // remove any locations that removed in the UI var selectedLocations = GroupLocationsState.Select( l => l.Guid ); foreach ( var groupLocation in group.GroupLocations.Where( l => !selectedLocations.Contains( l.Guid ) ).ToList() ) { group.GroupLocations.Remove( groupLocation ); groupLocationService.Delete( groupLocation ); } // remove any group requirements that removed in the UI var selectedGroupRequirements = GroupRequirementsState.Select( a => a.Guid ); foreach ( var groupRequirement in group.GroupRequirements.Where( a => !selectedGroupRequirements.Contains( a.Guid ) ).ToList() ) { group.GroupRequirements.Remove( groupRequirement ); groupRequirementService.Delete( groupRequirement ); } // Remove any triggers that were removed in the UI var selectedTriggerGuids = MemberWorkflowTriggersState.Select( r => r.Guid ); foreach ( var trigger in group.GroupMemberWorkflowTriggers.Where( r => !selectedTriggerGuids.Contains( r.Guid ) ).ToList() ) { group.GroupMemberWorkflowTriggers.Remove( trigger ); groupMemberWorkflowTriggerService.Delete( trigger ); triggersUpdated = true; } } // add/update any group requirements that were added or changed in the UI (we already removed the ones that were removed above) foreach ( var groupRequirementState in GroupRequirementsState ) { GroupRequirement groupRequirement = group.GroupRequirements.Where( a => a.Guid == groupRequirementState.Guid ).FirstOrDefault(); if ( groupRequirement == null ) { groupRequirement = new GroupRequirement(); group.GroupRequirements.Add( groupRequirement ); } groupRequirement.CopyPropertiesFrom( groupRequirementState ); } // 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 ); } } } foreach ( var triggerState in MemberWorkflowTriggersState ) { GroupMemberWorkflowTrigger trigger = group.GroupMemberWorkflowTriggers.Where( r => r.Guid == triggerState.Guid ).FirstOrDefault(); if ( trigger == null ) { trigger = new GroupMemberWorkflowTrigger(); group.GroupMemberWorkflowTriggers.Add( trigger ); } else { triggerState.Id = trigger.Id; triggerState.Guid = trigger.Guid; } trigger.CopyPropertiesFrom( triggerState ); triggersUpdated = true; } group.Name = tbName.Text; group.Description = tbDescription.Text; group.CampusId = ddlCampus.SelectedValueAsInt(); group.GroupTypeId = CurrentGroupTypeId; group.ParentGroupId = gpParentGroup.SelectedValueAsInt(); group.GroupCapacity = nbGroupCapacity.Text.AsIntegerOrNull(); group.RequiredSignatureDocumentTemplateId = ddlSignatureDocumentTemplate.SelectedValueAsInt(); group.IsSecurityRole = cbIsSecurityRole.Checked; group.IsActive = cbIsActive.Checked; group.IsPublic = cbIsPublic.Checked; group.MustMeetRequirementsToAddMember = cbMembersMustMeetRequirementsOnAdd.Checked; // save sync settings group.SyncDataViewId = dvpSyncDataview.SelectedValue.AsIntegerOrNull(); group.WelcomeSystemEmailId = ddlWelcomeEmail.SelectedValue.AsIntegerOrNull(); group.ExitSystemEmailId = ddlExitEmail.SelectedValue.AsIntegerOrNull(); group.AddUserAccountsDuringSync = rbCreateLoginDuringSync.Checked; 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 ) ) { // Make sure this is the only group trying to use this schedule. if ( !groupService.Queryable().Where( g => g.ScheduleId == schedule.Id && g.Id != group.Id ).Any() ) { scheduleService.Delete( schedule ); } } } if ( scheduleType == ScheduleType.Named ) { group.ScheduleId = spSchedule.SelectedValueAsId(); } else { group.ScheduleId = null; } } if ( group.ParentGroupId == group.Id ) { gpParentGroup.ShowErrorMessage( "Group cannot be a Parent Group of itself." ); return; } 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 ); } // Check to see if group type is allowed as a child of new parent group. if ( group.ParentGroup != null ) { var allowedGroupTypeIds = GetAllowedGroupTypes( group.ParentGroup, rockContext ).Select( t => t.Id ).ToList(); if ( !allowedGroupTypeIds.Contains( group.GroupTypeId ) ) { var groupType = CurrentGroupTypeCache; nbInvalidParentGroup.Text = string.Format( "The '{0}' group does not allow child groups with a '{1}' group type.", group.ParentGroup.Name, groupType != null ? groupType.Name : string.Empty ); nbInvalidParentGroup.Visible = true; return; } } // Check to see if user is still allowed to edit with selected group type and parent group if ( !group.IsAuthorized( Authorization.EDIT, CurrentPerson ) ) { nbNotAllowedToEdit.Visible = true; return; } 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 ); /* Take care of Group Member Attributes */ var entityTypeId = EntityTypeCache.Read( typeof( GroupMember ) ).Id; string qualifierColumn = "GroupId"; string qualifierValue = group.Id.ToString(); // Get the existing attributes for this entity type and qualifier value var attributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue ); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = GroupMemberAttributesState.Select( a => a.Guid ); foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) ) { Rock.Web.Cache.AttributeCache.Flush( attr.Id ); attributeService.Delete( attr ); } // Update the Attributes that were assigned in the UI foreach ( var attributeState in GroupMemberAttributesState ) { Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext ); } rockContext.SaveChanges(); if ( group.IsActive == false && cbInactivateChildGroups.Checked ) { var allActiveChildGroupsId = groupService.GetAllDescendents( group.Id ).Where( a => a.IsActive ).Select( a => a.Id ).ToList(); var allActiveChildGroups = groupService.GetByIds( allActiveChildGroupsId ); foreach ( var childGroup in allActiveChildGroups ) { if ( childGroup.IsActive ) { childGroup.IsActive = false; } } rockContext.SaveChanges(); } } ); bool isNowSecurityRole = group.IsActive && ( group.IsSecurityRole || group.GroupTypeId == roleGroupTypeId ); if ( group != null && wasSecurityRole ) { if ( !isNowSecurityRole ) { // if this group was a SecurityRole, but no longer is, flush Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } else { if ( isNowSecurityRole ) { // new security role, flush Rock.Security.Authorization.Flush(); } } AttributeCache.FlushEntityAttributes(); if ( triggersUpdated ) { GroupMemberWorkflowTriggerService.FlushCachedTriggers(); } var qryParams = new Dictionary<string, string>(); qryParams["GroupId"] = group.Id.ToString(); 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 ); MetricValueService metricValueService = new MetricValueService( rockContext ); MetricPartitionService metricPartitionService = new MetricPartitionService( rockContext ); int metricId = hfMetricId.Value.AsInteger(); if ( metricId == 0 ) { metric = new Metric(); } else { metric = metricService.Get( metricId ); // remove any metricPartitions that were removed in the UI var selectedMetricPartitionGuids = MetricPartitionsState.Select( r => r.Guid ); foreach ( var item in metric.MetricPartitions.Where( r => !selectedMetricPartitionGuids.Contains( r.Guid ) ).ToList() ) { metric.MetricPartitions.Remove( item ); metricPartitionService.Delete( item ); } } metric.MetricPartitions = metric.MetricPartitions ?? new List<MetricPartition>(); if ( MetricPartitionsState.Count() > 1 && MetricPartitionsState.Any(a => !a.EntityTypeId.HasValue )) { mdMetricPartitionsEntityTypeWarning.Text = "If multiple partitions are defined for a metric, all the partitions must have an EntityType assigned"; mdMetricPartitionsEntityTypeWarning.Visible = true; pwMetricPartitions.Expanded = true; return; } mdMetricPartitionsEntityTypeWarning.Visible = false; foreach ( var metricPartitionState in MetricPartitionsState ) { MetricPartition metricPartition = metric.MetricPartitions.Where( r => r.Guid == metricPartitionState.Guid ).FirstOrDefault(); if ( metricPartition == null ) { metricPartition = new MetricPartition(); metric.MetricPartitions.Add( metricPartition ); } else { metricPartitionState.Id = metricPartition.Id; metricPartitionState.Guid = metricPartition.Guid; } metricPartition.CopyPropertiesFrom( metricPartitionState ); } // ensure there is at least one partition if ( !metric.MetricPartitions.Any() ) { var metricPartition = new MetricPartition(); metricPartition.EntityTypeId = null; metricPartition.IsRequired = true; metricPartition.Order = 0; metric.MetricPartitions.Add( metricPartition ); } metric.Title = tbTitle.Text; metric.Subtitle = tbSubtitle.Text; metric.Description = tbDescription.Text; metric.IconCssClass = tbIconCssClass.Text; metric.SourceValueTypeId = ddlSourceType.SelectedValueAsId(); metric.YAxisLabel = tbYAxisLabel.Text; metric.IsCumulative = cbIsCumulative.Checked; 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 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 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( RockPage.Guid, qryParams ); } else { // Cancelling on Edit. Return to Details var service = new ScheduleService(); var item = service.Get( int.Parse( hfScheduleId.Value ) ); ShowReadonlyDetails( item ); } }
/// <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 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 ) { Group group; bool wasSecurityRole = false; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); GroupLocationService groupLocationService = new GroupLocationService( rockContext ); ScheduleService scheduleService = new ScheduleService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext ); CategoryService categoryService = new CategoryService( rockContext ); if ( ( ddlGroupType.SelectedValueAsInt() ?? 0 ) == 0 ) { ddlGroupType.ShowErrorMessage( Rock.Constants.WarningMessage.CannotBeBlank( GroupType.FriendlyTypeName ) ); return; } int groupId = int.Parse( hfGroupId.Value ); if ( groupId == 0 ) { group = new Group(); group.IsSystem = false; group.Name = string.Empty; } else { group = groupService.Queryable( "Schedule,GroupLocations.Schedules" ).Where( g => g.Id == groupId ).FirstOrDefault(); wasSecurityRole = group.IsSecurityRole; var selectedLocations = GroupLocationsState.Select( l => l.Guid ); foreach ( var groupLocation in group.GroupLocations.Where( l => !selectedLocations.Contains( l.Guid ) ).ToList() ) { group.GroupLocations.Remove( groupLocation ); groupLocationService.Delete( groupLocation ); } } 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 ); } } } group.Name = tbName.Text; group.Description = tbDescription.Text; group.CampusId = ddlCampus.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlCampus.SelectedValue ); group.GroupTypeId = int.Parse( ddlGroupType.SelectedValue ); group.ParentGroupId = gpParentGroup.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( gpParentGroup.SelectedValue ); group.IsSecurityRole = cbIsSecurityRole.Checked; group.IsActive = cbIsActive.Checked; 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; } } if ( group.ParentGroupId == group.Id ) { gpParentGroup.ShowErrorMessage( "Group cannot be a Parent Group of itself." ); return; } 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 ); } // Check to see if user is still allowed to edit with selected group type and parent group if ( !group.IsAuthorized( Authorization.EDIT, CurrentPerson )) { nbNotAllowedToEdit.Visible = true; return; } if ( !Page.IsValid ) { return; } if ( !group.IsValid ) { // Controls will render the error messages 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 ); /* Take care of Group Member Attributes */ var entityTypeId = EntityTypeCache.Read( typeof( GroupMember ) ).Id; string qualifierColumn = "GroupId"; string qualifierValue = group.Id.ToString(); // Get the existing attributes for this entity type and qualifier value var attributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue ); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = GroupMemberAttributesState.Select( a => a.Guid ); foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) ) { Rock.Web.Cache.AttributeCache.Flush( attr.Id ); attributeService.Delete( attr ); } // Update the Attributes that were assigned in the UI foreach ( var attributeState in GroupMemberAttributesState ) { Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext ); } rockContext.SaveChanges(); } ); if ( group != null && wasSecurityRole ) { if ( !group.IsSecurityRole ) { // if this group was a SecurityRole, but no longer is, flush Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } else { if ( group.IsSecurityRole ) { // new security role, flush Rock.Security.Authorization.Flush(); } } var qryParams = new Dictionary<string, string>(); qryParams["GroupId"] = group.Id.ToString(); qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" ); NavigateToPage( RockPage.Guid, qryParams ); }
/// <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? parentGroupId = null; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); AuthService authService = new AuthService( rockContext ); Group group = groupService.Get( int.Parse( hfGroupId.Value ) ); if ( group != null ) { if ( !group.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { mdDeleteWarning.Show( "You are not authorized to delete this group.", ModalAlertType.Information ); return; } parentGroupId = group.ParentGroupId; string errorMessage; if ( !groupService.CanDelete( group, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } bool isSecurityRoleGroup = group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ); if ( isSecurityRoleGroup ) { Rock.Security.Role.Flush( group.Id ); foreach ( var auth in authService.Queryable().Where( a => a.GroupId == group.Id ).ToList() ) { authService.Delete( auth ); } } // If group has a non-named schedule, delete the schedule record. if ( group.ScheduleId.HasValue ) { var scheduleService = new ScheduleService( rockContext ); var schedule = scheduleService.Get( group.ScheduleId.Value ); if ( schedule != null && schedule.ScheduleType != ScheduleType.Named ) { scheduleService.Delete(schedule); } } groupService.Delete( group ); rockContext.SaveChanges(); if ( isSecurityRoleGroup ) { Rock.Security.Authorization.Flush(); } } // reload page, selecting the deleted group's parent var qryParams = new Dictionary<string, string>(); if ( parentGroupId != null ) { qryParams["GroupId"] = parentGroupId.ToString(); } 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 adding groups from the given XML element snippet. /// </summary> /// <param name="elemGroups">The elem groups.</param> /// <param name="rockContext">The rock context.</param> /// <exception cref="System.NotSupportedException"></exception> private void AddGroups( XElement elemGroups, RockContext rockContext ) { // Add groups if ( elemGroups == null ) { return; } GroupService groupService = new GroupService( rockContext ); // Next create the group along with its members. foreach ( var elemGroup in elemGroups.Elements( "group" ) ) { Guid guid = elemGroup.Attribute( "guid" ).Value.Trim().AsGuid(); string type = elemGroup.Attribute( "type" ).Value; Group group = new Group() { Guid = guid, Name = elemGroup.Attribute( "name" ).Value.Trim() }; // skip any where there is no group type given -- they are invalid entries. if ( string.IsNullOrEmpty( elemGroup.Attribute( "type" ).Value.Trim() ) ) { return; } int? roleId; GroupTypeCache groupType; switch ( elemGroup.Attribute( "type" ).Value.Trim() ) { case "serving": groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SERVING_TEAM.AsGuid() ); group.GroupTypeId = groupType.Id; roleId = groupType.DefaultGroupRoleId; break; case "smallgroup": groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SMALL_GROUP.AsGuid() ); group.GroupTypeId = groupType.Id; roleId = groupType.DefaultGroupRoleId; break; default: throw new NotSupportedException( string.Format( "unknown group type {0}", elemGroup.Attribute( "type" ).Value.Trim() ) ); } if ( elemGroup.Attribute( "description" ) != null ) { group.Description = elemGroup.Attribute( "description" ).Value; } if ( elemGroup.Attribute( "parentGroupGuid" ) != null ) { var parentGroup = groupService.Get( elemGroup.Attribute( "parentGroupGuid" ).Value.AsGuid() ); group.ParentGroupId = parentGroup.Id; } // Set the group's meeting location if ( elemGroup.Attribute( "meetsAtHomeOfFamily" ) != null ) { int meetingLocationValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION.AsGuid() ).Id; var groupLocation = new GroupLocation() { IsMappedLocation = false, IsMailingLocation = false, GroupLocationTypeValueId = meetingLocationValueId, LocationId = _familyLocationDictionary[elemGroup.Attribute( "meetsAtHomeOfFamily" ).Value.AsGuid()], }; // Set the group location's GroupMemberPersonId if given (required?) if ( elemGroup.Attribute( "meetsAtHomeOfPerson" ) != null ) { groupLocation.GroupMemberPersonId = _peopleDictionary[elemGroup.Attribute( "meetsAtHomeOfPerson" ).Value.AsGuid()]; } group.GroupLocations.Add( groupLocation ); } group.LoadAttributes( rockContext ); // Set the study topic if ( elemGroup.Attribute( "studyTopic" ) != null ) { group.SetAttributeValue( "StudyTopic", elemGroup.Attribute( "studyTopic" ).Value ); } // Set the meeting time if ( elemGroup.Attribute( "meetingTime" ) != null ) { group.SetAttributeValue( "MeetingTime", elemGroup.Attribute( "meetingTime" ).Value ); } // Add each person as a member foreach ( var elemPerson in elemGroup.Elements( "person" ) ) { Guid personGuid = elemPerson.Attribute( "guid" ).Value.Trim().AsGuid(); GroupMember groupMember = new GroupMember(); groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMember.GroupRoleId = roleId ?? -1; groupMember.PersonId = _peopleDictionary[personGuid]; group.Members.Add( groupMember ); } groupService.Add( group ); // Now we have to save changes in order for the attributes to be saved correctly. rockContext.SaveChanges(); group.SaveAttributeValues( rockContext ); // Now add any group location schedules LocationService locationService = new LocationService( rockContext ); ScheduleService scheduleService = new ScheduleService( rockContext ); Guid locationTypeMeetingLocationGuid = new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION ); var locationTypeMeetingLocationId = Rock.Web.Cache.DefinedValueCache.Read( locationTypeMeetingLocationGuid ).Id; foreach ( var elemLocation in elemGroup.Elements( "location" ) ) { Guid locationGuid = elemLocation.Attribute( "guid" ).Value.Trim().AsGuid(); Location location = locationService.Get( locationGuid ); GroupLocation groupLocation = new GroupLocation(); groupLocation.Location = location; groupLocation.GroupLocationTypeValueId = locationTypeMeetingLocationId; group.GroupLocations.Add( groupLocation ); foreach ( var elemSchedule in elemLocation.Elements( "schedule" ) ) { try { Guid scheduleGuid = elemSchedule.Attribute( "guid" ).Value.Trim().AsGuid(); Schedule schedule = scheduleService.Get( scheduleGuid ); groupLocation.Schedules.Add( schedule ); } catch { } } TimeSpan ts = _stopwatch.Elapsed; _sb.AppendFormat( "{0:00}:{1:00}.{2:00} group location schedules added<br/>", ts.Minutes, ts.Seconds, ts.Milliseconds / 10 ); } } }
/// <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 ( new UnitOfWorkScope() ) { GroupLocationService groupLocationService = new GroupLocationService(); ScheduleService scheduleService = new ScheduleService(); RockTransactionScope.WrapTransaction( () => { 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>() ) { CheckBoxEditableField 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 ); } } 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 ) ); } } } } groupLocationService.Save( groupLocation, this.CurrentPersonId ); } } } ); } NavigateToParentPage(); }
/// <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 ); } } }
/// <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(); } } } } }
/// <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 ) { Group group; bool wasSecurityRole = false; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); GroupLocationService groupLocationService = new GroupLocationService( rockContext ); ScheduleService scheduleService = new ScheduleService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext ); CategoryService categoryService = new CategoryService( rockContext ); if ( ( ddlGroupType.SelectedValueAsInt() ?? 0 ) == 0 ) { ddlGroupType.ShowErrorMessage( Rock.Constants.WarningMessage.CannotBeBlank( GroupType.FriendlyTypeName ) ); return; } int groupId = int.Parse( hfGroupId.Value ); if ( groupId == 0 ) { group = new Group(); group.IsSystem = false; group.Name = string.Empty; } else { group = groupService.Queryable( "GroupLocations.Schedules" ).Where( g => g.Id == groupId ).FirstOrDefault(); wasSecurityRole = group.IsSecurityRole; var selectedLocations = GroupLocationsState.Select( l => l.Guid ); foreach ( var groupLocation in group.GroupLocations.Where( l => !selectedLocations.Contains( l.Guid ) ).ToList() ) { group.GroupLocations.Remove( groupLocation ); groupLocationService.Delete( groupLocation ); } } 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 ); } } } group.Name = tbName.Text; group.Description = tbDescription.Text; group.CampusId = ddlCampus.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlCampus.SelectedValue ); group.GroupTypeId = int.Parse( ddlGroupType.SelectedValue ); group.ParentGroupId = gpParentGroup.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( gpParentGroup.SelectedValue ); group.IsSecurityRole = cbIsSecurityRole.Checked; group.IsActive = cbIsActive.Checked; if ( group.ParentGroupId == group.Id ) { gpParentGroup.ShowErrorMessage( "Group cannot be a Parent Group of itself." ); return; } group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phGroupAttributes, group ); if ( !Page.IsValid ) { return; } if ( !group.IsValid ) { // Controls will render the error messages return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction( () => { if ( group.Id.Equals( 0 ) ) { groupService.Add( group ); } rockContext.SaveChanges(); group.SaveAttributeValues( rockContext ); /* Take care of Group Member Attributes */ var entityTypeId = EntityTypeCache.Read( typeof( GroupMember ) ).Id; string qualifierColumn = "GroupId"; string qualifierValue = group.Id.ToString(); // Get the existing attributes for this entity type and qualifier value var attributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue ); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = GroupMemberAttributesState.Select( a => a.Guid ); foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) ) { Rock.Web.Cache.AttributeCache.Flush( attr.Id ); attributeService.Delete( attr ); } // Update the Attributes that were assigned in the UI foreach ( var attributeState in GroupMemberAttributesState ) { Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext ); } rockContext.SaveChanges(); } ); if ( group != null && wasSecurityRole ) { if ( !group.IsSecurityRole ) { // if this group was a SecurityRole, but no longer is, flush Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } else { if ( group.IsSecurityRole ) { // new security role, flush Rock.Security.Authorization.Flush(); } } var qryParams = new Dictionary<string, string>(); qryParams["GroupId"] = group.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); }
/// <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 ) { 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(); }
/// <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" ) ) { int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull(); if ( parentCategoryId.HasValue ) { // Cancelling on Add, and we know the parentCategoryId, so we are probably in treeview mode, so navigate to the current page var qryParams = new Dictionary<string, string>(); qryParams["CategoryId"] = parentCategoryId.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } else { // Cancelling on Add. Return to Grid NavigateToParentPage(); } } else { // Cancelling on Edit. Return to Details var service = new ScheduleService( new RockContext() ); var item = service.Get( int.Parse( hfScheduleId.Value ) ); ShowReadonlyDetails( item ); } }