/// <summary> /// Handles the Delete event of the rGrid 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 rGrid_Delete(object sender, RowEventArgs e) { var attributeService = new Rock.Model.AttributeService(); Rock.Model.Attribute attribute = attributeService.Get((int)rGrid.DataKeys[e.RowIndex]["id"]); if (attribute != null) { Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute, CurrentPersonId); attributeService.Save(attribute, CurrentPersonId); } BindGrid(); }
/// <summary> /// Maps the activity ministry. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapActivityMinistry( IQueryable<Row> tableData ) { int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id; var attributeService = new AttributeService(); // Add an Attribute for the unique F1 Ministry Id var ministryAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == groupEntityTypeId && a.Key == "F1MinistryId" ).Select( a => a.Id ).FirstOrDefault(); if ( ministryAttributeId == 0 ) { var newMinistryAttribute = new Rock.Model.Attribute(); newMinistryAttribute.Key = "F1MinistryId"; newMinistryAttribute.Name = "F1 Ministry Id"; newMinistryAttribute.FieldTypeId = IntegerFieldTypeId; newMinistryAttribute.EntityTypeId = groupEntityTypeId; newMinistryAttribute.EntityTypeQualifierValue = string.Empty; newMinistryAttribute.EntityTypeQualifierColumn = string.Empty; newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported"; newMinistryAttribute.DefaultValue = string.Empty; newMinistryAttribute.IsMultiValue = false; newMinistryAttribute.IsRequired = false; newMinistryAttribute.Order = 0; attributeService.Add( newMinistryAttribute, ImportPersonAlias ); attributeService.Save( newMinistryAttribute, ImportPersonAlias ); ministryAttributeId = newMinistryAttribute.Id; } // Get previously imported Ministries var importedMinistries = new AttributeValueService().GetByAttributeId( ministryAttributeId ) .Select( av => new { RLCId = av.Value.AsType<int?>(), LocationId = av.EntityId } ) .ToDictionary( t => t.RLCId, t => t.LocationId ); foreach ( var row in tableData ) { int? ministryId = row["Ministry_ID"] as int?; if ( ministryId != null && !importedMinistries.ContainsKey( ministryId ) ) { // Activity_ID // Ministry_Name // Activity_Name // Ministry_Active // Activity_Active } } }
/// <summary> /// Maps the RLC data to rooms, locations & classes /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapRLC( IQueryable<Row> tableData ) { int locationEntityTypeId = EntityTypeCache.Read( "Rock.Model.Location" ).Id; int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id; var attributeService = new AttributeService(); // Add an Attribute for the unique F1 RLC Id var rlcAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == locationEntityTypeId && a.Key == "F1RLCId" ).Select( a => a.Id ).FirstOrDefault(); if ( rlcAttributeId == 0 ) { var newRLCAttribute = new Rock.Model.Attribute(); newRLCAttribute.Key = "F1RLCId"; newRLCAttribute.Name = "F1 RLC Id"; newRLCAttribute.FieldTypeId = IntegerFieldTypeId; newRLCAttribute.EntityTypeId = locationEntityTypeId; newRLCAttribute.EntityTypeQualifierValue = string.Empty; newRLCAttribute.EntityTypeQualifierColumn = string.Empty; newRLCAttribute.Description = "The FellowshipOne identifier for the RLC (Room/Location/Class) that was imported"; newRLCAttribute.DefaultValue = string.Empty; newRLCAttribute.IsMultiValue = false; newRLCAttribute.IsRequired = false; newRLCAttribute.Order = 0; attributeService.Add( newRLCAttribute, ImportPersonAlias ); attributeService.Save( newRLCAttribute, ImportPersonAlias ); rlcAttributeId = newRLCAttribute.Id; } // Add an Attribute for the unique F1 Activity Id var activityAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == locationEntityTypeId && a.Key == "F1ActivityId" ).Select( a => a.Id ).FirstOrDefault(); if ( rlcAttributeId == 0 ) { var newActivityAttribute = new Rock.Model.Attribute(); newActivityAttribute.Key = "F1ActivityId"; newActivityAttribute.Name = "F1 Activity Id"; newActivityAttribute.FieldTypeId = IntegerFieldTypeId; newActivityAttribute.EntityTypeId = locationEntityTypeId; newActivityAttribute.EntityTypeQualifierValue = string.Empty; newActivityAttribute.EntityTypeQualifierColumn = string.Empty; newActivityAttribute.Description = "The FellowshipOne identifier for the activity that was imported"; newActivityAttribute.DefaultValue = string.Empty; newActivityAttribute.IsMultiValue = false; newActivityAttribute.IsRequired = false; newActivityAttribute.Order = 0; attributeService.Add( newActivityAttribute, ImportPersonAlias ); attributeService.Save( newActivityAttribute, ImportPersonAlias ); activityAttributeId = newActivityAttribute.Id; } var rlcAttribute = AttributeCache.Read( rlcAttributeId ); var activityAttribute = AttributeCache.Read( activityAttributeId ); // Get any previously imported RLCs var importedRLC = new AttributeValueService().GetByAttributeId( rlcAttributeId ) .Select( av => new { RLCId = av.Value.AsType<int?>(), LocationId = av.EntityId } ) .ToDictionary( t => t.RLCId, t => t.LocationId ); ImportedActivities = new AttributeValueService().GetByAttributeId( activityAttributeId ) .Select( av => new { ActivityId = av.Value.AsType<int?>(), GroupId = av.EntityId } ) .ToDictionary( t => t.ActivityId, t => t.GroupId ); foreach ( var row in tableData ) { int? rlcId = row["RLC_ID"] as int?; if ( rlcId != null && !importedRLC.ContainsKey( rlcId ) ) { // Activity_ID // RLC_Name // Activity_Group_ID // Start_Age_Date // End_Age_Date // Is_Active // Room_Code // Room_Desc // Room_Name // Max_Capacity // Building_Name } } }
/// <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() ) { MarketingCampaignAdType marketingCampaignAdType; MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService(); int marketingCampaignAdTypeId = int.Parse( hfMarketingCampaignAdTypeId.Value ); if ( marketingCampaignAdTypeId == 0 ) { marketingCampaignAdType = new MarketingCampaignAdType(); marketingCampaignAdTypeService.Add( marketingCampaignAdType, CurrentPersonId ); } else { marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdTypeId ); } marketingCampaignAdType.Name = tbName.Text; marketingCampaignAdType.DateRangeType = (DateRangeTypeEnum)int.Parse( ddlDateRangeType.SelectedValue ); if ( !marketingCampaignAdType.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { AttributeService attributeService = new AttributeService(); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(); CategoryService categoryService = new CategoryService(); marketingCampaignAdTypeService.Save( marketingCampaignAdType, CurrentPersonId ); // get it back to make sure we have a good Id for it for the Attributes marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdType.Guid ); var entityTypeId = EntityTypeCache.Read(typeof(MarketingCampaignAd)).Id; string qualifierColumn = "MarketingCampaignAdTypeId"; string qualifierValue = marketingCampaignAdType.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 = AttributesState.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, CurrentPersonId ); attributeService.Save( attr, CurrentPersonId ); } // Update the Attributes that were assigned in the UI foreach ( var attributeState in AttributesState ) { Rock.Attribute.Helper.SaveAttributeEdits( attributeState, attributeService, attributeQualifierService, categoryService, entityTypeId, qualifierColumn, qualifierValue, 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 ) { Group group; bool wasSecurityRole = false; using ( new UnitOfWorkScope() ) { GroupService groupService = new GroupService(); GroupLocationService groupLocationService = new GroupLocationService(); AttributeService attributeService = new AttributeService(); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(); CategoryService categoryService = new CategoryService(); 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.Get( groupId ); 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, CurrentPersonId ); } } 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; } groupLocation.CopyPropertiesFrom( groupLocationState ); } 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; } RockTransactionScope.WrapTransaction( () => { if ( group.Id.Equals( 0 ) ) { groupService.Add( group, CurrentPersonId ); } groupService.Save( group, CurrentPersonId ); Rock.Attribute.Helper.SaveAttributeValues( group, CurrentPersonId ); /* 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, CurrentPersonId ); attributeService.Save( attr, CurrentPersonId ); } // Update the Attributes that were assigned in the UI foreach ( var attributeState in GroupMemberAttributesState ) { Rock.Attribute.Helper.SaveAttributeEdits( attributeState, attributeService, attributeQualifierService, categoryService, entityTypeId, qualifierColumn, qualifierValue, CurrentPersonId ); } } ); } 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 gDefinedTypeAttributes 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 gDefinedTypeAttributes_Delete( object sender, RowEventArgs e ) { Guid attributeGuid = (Guid)e.RowKeyValue; AttributeService attributeService = new AttributeService(); Attribute attribute = attributeService.Get( attributeGuid ); if ( attribute != null ) { string errorMessage; if ( !attributeService.CanDelete( attribute, out errorMessage ) ) { mdGridWarningAttributes.Show( errorMessage, ModalAlertType.Information ); return; } AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute, CurrentPersonId ); attributeService.Save( attribute, CurrentPersonId ); } BindDefinedTypeAttributesGrid(); }
/// <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() ) { var attributeService = new AttributeService(); var attributeQualifierService = new AttributeQualifierService(); Rock.Model.Attribute attribute; int attributeId = 0; if ( hfId.Value != string.Empty && !int.TryParse( hfId.Value, out attributeId ) ) { attributeId = 0; } if ( attributeId == 0 ) { attribute = new Rock.Model.Attribute(); attribute.IsSystem = false; attribute.EntityTypeId = _entityTypeId; attribute.EntityTypeQualifierColumn = _entityQualifierColumn; attribute.EntityTypeQualifierValue = _entityQualifierValue; attributeService.Add( attribute, CurrentPersonId ); } else { AttributeCache.Flush( attributeId ); attribute = attributeService.Get( attributeId ); } attribute.Key = tbKey.Text; attribute.Name = tbName.Text; attribute.Category = tbCategory.Text; attribute.Description = tbDescription.Text; attribute.FieldTypeId = int.Parse( ddlFieldType.SelectedValue ); var fieldType = FieldTypeCache.Read( attribute.FieldTypeId ); foreach ( var oldQualifier in attribute.AttributeQualifiers.ToList() ) { attributeQualifierService.Delete( oldQualifier, CurrentPersonId ); } attribute.AttributeQualifiers.Clear(); List<Control> configControls = new List<Control>(); foreach ( var key in fieldType.Field.ConfigurationKeys() ) { configControls.Add( phFieldTypeQualifiers.FindControl( "configControl_" + key ) ); } foreach ( var configValue in fieldType.Field.ConfigurationValues( configControls ) ) { AttributeQualifier qualifier = new AttributeQualifier(); qualifier.IsSystem = false; qualifier.Key = configValue.Key; qualifier.Value = configValue.Value.Value ?? string.Empty; attribute.AttributeQualifiers.Add( qualifier ); } attribute.DefaultValue = tbDefaultValue.Text; attribute.IsMultiValue = cbMultiValue.Checked; attribute.IsRequired = cbRequired.Checked; attributeService.Save( attribute, CurrentPersonId ); } BindGrid(); pnlDetails.Visible = false; pnlList.Visible = 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 ) { MarketingCampaignAdType marketingCampaignAdType; MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService(); int marketingCampaignAdTypeId = int.Parse( hfMarketingCampaignAdTypeId.Value ); if ( marketingCampaignAdTypeId == 0 ) { marketingCampaignAdType = new MarketingCampaignAdType(); marketingCampaignAdTypeService.Add( marketingCampaignAdType, CurrentPersonId ); } else { marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdTypeId ); } marketingCampaignAdType.Name = tbName.Text; marketingCampaignAdType.DateRangeType = (DateRangeTypeEnum)int.Parse( ddlDateRangeType.SelectedValue ); // check for duplicates if ( marketingCampaignAdTypeService.Queryable().Count( a => a.Name.Equals( marketingCampaignAdType.Name, StringComparison.OrdinalIgnoreCase ) && !a.Id.Equals( marketingCampaignAdType.Id ) ) > 0 ) { tbName.ShowErrorMessage( WarningMessage.DuplicateFoundMessage( "name", MarketingCampaignAdType.FriendlyTypeName ) ); return; } if ( !marketingCampaignAdType.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { marketingCampaignAdTypeService.Save( marketingCampaignAdType, CurrentPersonId ); // get it back to make sure we have a good Id for it for the Attributes marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdType.Guid ); // delete AdTypeAttributes that are no longer configured in the UI AttributeService attributeService = new AttributeService(); var qry = attributeService.GetByEntityTypeId( new MarketingCampaignAd().TypeId ).AsQueryable() .Where( a => a.EntityTypeQualifierColumn.Equals( "MarketingCampaignAdTypeId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( marketingCampaignAdType.Id.ToString() ) ); var deletedAttributes = from attr in qry where !( from d in AttributesState select d.Guid ).Contains( attr.Guid ) select attr; deletedAttributes.ToList().ForEach( a => { var attr = attributeService.Get( a.Guid ); attributeService.Delete( attr, CurrentPersonId ); attributeService.Save( attr, CurrentPersonId ); } ); // add/update the AdTypes that are assigned in the UI foreach ( var attributeState in AttributesState ) { Attribute attribute = qry.FirstOrDefault( a => a.Guid.Equals( attributeState.Guid ) ); if ( attribute == null ) { attribute = attributeState.ToModel(); attributeService.Add( attribute, CurrentPersonId ); } else { attributeState.Id = attribute.Id; attributeState.CopyToModel( attribute ); } attribute.EntityTypeQualifierColumn = "MarketingCampaignAdTypeId"; attribute.EntityTypeQualifierValue = marketingCampaignAdType.Id.ToString(); attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( new MarketingCampaignAd().TypeName ).Id; attributeService.Save( attribute, CurrentPersonId ); } } ); BindGrid(); pnlDetails.Visible = false; pnlList.Visible = true; }
/// <summary> /// Sets the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="currentPersonId">The current person id.</param> /// <param name="saveValue">if set to <c>true</c> [save value].</param> public void SetValue( string key, string value, int? currentPersonId, bool saveValue ) { if ( saveValue ) { using (new Rock.Data.UnitOfWorkScope()) { // Save new value var attributeValueService = new AttributeValueService(); var attributeValue = attributeValueService.GetGlobalAttributeValue( key ); if ( attributeValue == null ) { var attributeService = new AttributeService(); var attribute = attributeService.GetGlobalAttribute( key ); if ( attribute == null ) { attribute = new Rock.Model.Attribute(); attribute.FieldTypeId = FieldTypeCache.Read(new Guid(SystemGuid.FieldType.TEXT)).Id; attribute.EntityTypeQualifierColumn = string.Empty; attribute.EntityTypeQualifierValue = string.Empty; attribute.Key = key; attribute.Name = key.SplitCase(); attributeService.Add(attribute, currentPersonId); attributeService.Save(attribute, currentPersonId); Attributes.Add( AttributeCache.Read( attribute.Id ) ); } attributeValue = new AttributeValue(); attributeValueService.Add( attributeValue, currentPersonId ); attributeValue.IsSystem = false; attributeValue.AttributeId = attribute.Id; if ( !AttributeValues.Keys.Contains( key ) ) { AttributeValues.Add( key, new KeyValuePair<string, string>( attribute.Name, value ) ); } } attributeValue.Value = value; attributeValueService.Save( attributeValue, currentPersonId ); } } var attributeCache = Attributes.FirstOrDefault( a => a.Key.Equals( key, StringComparison.OrdinalIgnoreCase ) ); if ( attributeCache != null ) // (Should never be null) { if ( AttributeValues.Keys.Contains( key ) ) { AttributeValues[key] = new KeyValuePair<string, string>( attributeCache.Name, value ); } else { AttributeValues.Add( key, new KeyValuePair<string, string>( attributeCache.Name, value ) ); } } }
private void SaveAttributes( int entityTypeId, string qualifierColumn, string qualifierValue, ViewStateList<Attribute> viewStateAttributes, AttributeService attributeService, AttributeQualifierService qualifierService, CategoryService categoryService ) { // 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 = viewStateAttributes.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, CurrentPersonId ); attributeService.Save( attr, CurrentPersonId ); } // Update the Attributes that were assigned in the UI foreach ( var attributeState in viewStateAttributes ) { Helper.SaveAttributeEdits( attributeState, attributeService, qualifierService, categoryService, entityTypeId, qualifierColumn, qualifierValue, CurrentPersonId ); } }
/// <summary> /// Loads Rock data that's used globally by the transform /// </summary> private void LoadExistingRockData() { var attributeValueService = new AttributeValueService(); var attributeService = new AttributeService(); IntegerFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.INTEGER ) ).Id; TextFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ) ).Id; PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id; BatchEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialBatch" ).Id; var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList(); var householdAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1HouseholdId" ); if ( householdAttribute == null ) { householdAttribute = new Rock.Model.Attribute(); householdAttribute.Key = "F1HouseholdId"; householdAttribute.Name = "F1 Household Id"; householdAttribute.FieldTypeId = IntegerFieldTypeId; householdAttribute.EntityTypeId = PersonEntityTypeId; householdAttribute.EntityTypeQualifierValue = string.Empty; householdAttribute.EntityTypeQualifierColumn = string.Empty; householdAttribute.Description = "The FellowshipOne household identifier for the person that was imported"; householdAttribute.DefaultValue = string.Empty; householdAttribute.IsMultiValue = false; householdAttribute.IsRequired = false; householdAttribute.Order = 0; attributeService.Add( householdAttribute, ImportPersonAlias ); attributeService.Save( householdAttribute, ImportPersonAlias ); personAttributes.Add( householdAttribute ); } var individualAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1IndividualId" ); if ( individualAttribute == null ) { individualAttribute = new Rock.Model.Attribute(); individualAttribute.Key = "F1IndividualId"; individualAttribute.Name = "F1 Individual Id"; individualAttribute.FieldTypeId = IntegerFieldTypeId; individualAttribute.EntityTypeId = PersonEntityTypeId; individualAttribute.EntityTypeQualifierValue = string.Empty; individualAttribute.EntityTypeQualifierColumn = string.Empty; individualAttribute.Description = "The FellowshipOne individual identifier for the person that was imported"; individualAttribute.DefaultValue = string.Empty; individualAttribute.IsMultiValue = false; individualAttribute.IsRequired = false; individualAttribute.Order = 0; attributeService.Add( individualAttribute, ImportPersonAlias ); attributeService.Save( individualAttribute, ImportPersonAlias ); personAttributes.Add( individualAttribute ); } IndividualAttributeId = individualAttribute.Id; HouseholdAttributeId = householdAttribute.Id; ReportProgress( 0, "Checking for existing people..." ); var listHouseholdId = attributeValueService.GetByAttributeId( householdAttribute.Id ).Select( av => new { PersonId = av.EntityId, HouseholdId = av.Value } ).ToList(); var listIndividualId = attributeValueService.GetByAttributeId( individualAttribute.Id ).Select( av => new { PersonId = av.EntityId, IndividualId = av.Value } ).ToList(); ImportedPeople = listHouseholdId.GroupJoin( listIndividualId, household => household.PersonId, individual => individual.PersonId, ( household, individual ) => new ImportedPerson { PersonId = household.PersonId, HouseholdId = household.HouseholdId.AsType<int?>(), IndividualId = individual.Select( i => i.IndividualId.AsType<int?>() ).FirstOrDefault() } ).ToList(); var batchAttribute = attributeService.Queryable().FirstOrDefault( a => a.EntityTypeId == BatchEntityTypeId && a.Key == "F1BatchId" ); if ( batchAttribute == null ) { batchAttribute = new Rock.Model.Attribute(); batchAttribute.Key = "F1BatchId"; batchAttribute.Name = "F1 Batch Id"; batchAttribute.FieldTypeId = IntegerFieldTypeId; batchAttribute.EntityTypeId = BatchEntityTypeId; batchAttribute.EntityTypeQualifierValue = string.Empty; batchAttribute.EntityTypeQualifierColumn = string.Empty; batchAttribute.Description = "The FellowshipOne identifier for the batch that was imported"; batchAttribute.DefaultValue = string.Empty; batchAttribute.IsMultiValue = false; batchAttribute.IsRequired = false; batchAttribute.Order = 0; attributeService.Add( batchAttribute, ImportPersonAlias ); attributeService.Save( batchAttribute, ImportPersonAlias ); } BatchAttributeId = batchAttribute.Id; ReportProgress( 0, "Checking for existing contributions..." ); ImportedBatches = new AttributeValueService().GetByAttributeId( batchAttribute.Id ) .Select( av => new { F1BatchId = av.Value.AsType<int?>(), RockBatchId = av.EntityId } ) .ToDictionary( t => t.F1BatchId, t => t.RockBatchId ); CampusList = new CampusService().Queryable().ToList(); }
/// <summary> /// Handles the Delete event of the gWorkflowTypeAttributes 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 gWorkflowTypeAttributes_Delete( object sender, RowEventArgs e ) { Guid attributeGuid = (Guid)e.RowKeyValue; AttributeService attributeService = new AttributeService(); Attribute attribute = attributeService.Get( attributeGuid ); if ( attribute != null ) { string errorMessage; if ( !attributeService.CanDelete( attribute, out errorMessage ) ) { mdGridWarningAttributes.Show( errorMessage, ModalAlertType.Information ); return; } Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute, CurrentPersonId ); attributeService.Save( attribute, CurrentPersonId ); } // reload page so that other blocks respond to any data that was changed var qryParams = new Dictionary<string, string>(); qryParams["workflowTypeId"] = hfWorkflowTypeId.Value; NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="selectedColumns">The selected columns.</param> private void MapContribution( IQueryable<Row> tableData, List<string> selectedColumns = null ) { int transactionEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialTransaction" ).Id; var accountService = new FinancialAccountService(); var attributeService = new AttributeService(); var transactionTypeContributionId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ).Id; int currencyTypeACH = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH ) ).Id; int currencyTypeCash = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH ) ).Id; int currencyTypeCheck = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK ) ).Id; int currencyTypeCreditCard = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ).Id; List<DefinedValue> refundReasons = new DefinedValueService().Queryable().Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON ) ).ToList(); List<FinancialPledge> pledgeList = new FinancialPledgeService().Queryable().ToList(); List<FinancialAccount> accountList = accountService.Queryable().ToList(); // Add an Attribute for the unique F1 Contribution Id int contributionAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == transactionEntityTypeId && a.Key == "F1ContributionId" ).Select( a => a.Id ).FirstOrDefault(); if ( contributionAttributeId == 0 ) { var newContributionAttribute = new Rock.Model.Attribute(); newContributionAttribute.Key = "F1ContributionId"; newContributionAttribute.Name = "F1 Contribution Id"; newContributionAttribute.FieldTypeId = IntegerFieldTypeId; newContributionAttribute.EntityTypeId = transactionEntityTypeId; newContributionAttribute.EntityTypeQualifierValue = string.Empty; newContributionAttribute.EntityTypeQualifierColumn = string.Empty; newContributionAttribute.Description = "The FellowshipOne identifier for the contribution that was imported"; newContributionAttribute.DefaultValue = string.Empty; newContributionAttribute.IsMultiValue = false; newContributionAttribute.IsRequired = false; newContributionAttribute.Order = 0; attributeService.Add( newContributionAttribute, ImportPersonAlias ); attributeService.Save( newContributionAttribute, ImportPersonAlias ); contributionAttributeId = newContributionAttribute.Id; } var contributionAttribute = AttributeCache.Read( contributionAttributeId ); // Get all imported contributions var importedContributions = new AttributeValueService().GetByAttributeId( contributionAttributeId ) .Select( av => new { ContributionId = av.Value.AsType<int?>(), TransactionId = av.EntityId } ) .ToDictionary( t => t.ContributionId, t => t.TransactionId ); // List for batching new contributions var newTransactions = new List<FinancialTransaction>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Checking contribution import ({0:N0} found, {1:N0} already exist).", totalRows, importedContributions.Count() ) ); foreach ( var row in tableData ) { int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; int? contributionId = row["ContributionID"] as int?; if ( contributionId != null && !importedContributions.ContainsKey( contributionId ) ) { var transaction = new FinancialTransaction(); transaction.TransactionTypeValueId = transactionTypeContributionId; transaction.AuthorizedPersonId = GetPersonId( individualId, householdId ); transaction.CreatedByPersonAliasId = ImportPersonAlias.Id; transaction.AuthorizedPersonId = GetPersonId( individualId, householdId ); string summary = row["Memo"] as string; if ( summary != null ) { transaction.Summary = summary; } int? batchId = row["BatchID"] as int?; if ( batchId != null && ImportedBatches.Any( b => b.Key == batchId ) ) { transaction.BatchId = ImportedBatches.FirstOrDefault( b => b.Key == batchId ).Value; } DateTime? receivedDate = row["Received_Date"] as DateTime?; if ( receivedDate != null ) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; } bool isTypeNonCash = false; string contributionType = row["Contribution_Type_Name"] as string; if ( contributionType != null ) { if ( contributionType == "ACH" ) { transaction.CurrencyTypeValueId = currencyTypeACH; } else if ( contributionType == "Cash" ) { transaction.CurrencyTypeValueId = currencyTypeCash; } else if ( contributionType == "Check" ) { transaction.CurrencyTypeValueId = currencyTypeCheck; } else if ( contributionType == "Credit Card" ) { transaction.CurrencyTypeValueId = currencyTypeCreditCard; } else { isTypeNonCash = true; } } string checkNumber = row["Check_Number"] as string; if ( checkNumber != null && checkNumber.AsType<int?>() != null ) { // routing & account set to zero transaction.CheckMicrEncrypted = Encryption.EncryptString( string.Format( "{0}_{1}_{2}", 0, 0, checkNumber ) ); } string fundName = row["Fund_Name"] as string; string subFund = row["Sub_Fund_Name"] as string; decimal? amount = row["Amount"] as decimal?; if ( fundName != null & amount != null ) { FinancialAccount matchingAccount = null; fundName = fundName.Trim(); int? fundCampusId = null; if ( subFund != null ) { subFund = subFund.Trim(); fundCampusId = CampusList.Where( c => c.Name.StartsWith( subFund ) || c.ShortCode == subFund ) .Select( c => (int?)c.Id ).FirstOrDefault(); if ( fundCampusId != null ) { matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.CampusId != null && a.CampusId.Equals( fundCampusId ) ); } else { matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.Name.StartsWith( subFund ) ); } } else { matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.CampusId == null ); } if ( matchingAccount == null ) { matchingAccount = new FinancialAccount(); matchingAccount.Name = fundName; matchingAccount.PublicName = fundName; matchingAccount.IsTaxDeductible = true; matchingAccount.IsActive = true; matchingAccount.CampusId = fundCampusId; matchingAccount.CreatedByPersonAliasId = ImportPersonAlias.Id; accountService.Add( matchingAccount ); accountService.Save( matchingAccount ); accountList.Add( matchingAccount ); } var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = (decimal)amount; transactionDetail.CreatedDateTime = receivedDate; transactionDetail.AccountId = matchingAccount.Id; transactionDetail.IsNonCash = isTypeNonCash; transaction.TransactionDetails.Add( transactionDetail ); if ( amount < 0 ) { var transactionRefund = new FinancialTransactionRefund(); transactionRefund.CreatedDateTime = receivedDate; transactionRefund.RefundReasonSummary = summary; transactionRefund.RefundReasonValueId = refundReasons.Where( dv => summary != null && dv.Name.Contains( summary ) ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); transaction.Refund = transactionRefund; } } // Other Attributes to create: // Pledge_Drive_Name // Stated_Value // True_Value // Liquidation_cost transaction.Attributes = new Dictionary<string, AttributeCache>(); transaction.AttributeValues = new Dictionary<string, List<AttributeValue>>(); transaction.Attributes.Add( contributionAttribute.Key, contributionAttribute ); transaction.AttributeValues.Add( contributionAttribute.Key, new List<AttributeValue>() ); transaction.AttributeValues[contributionAttribute.Key].Add( new AttributeValue() { AttributeId = contributionAttribute.Id, Value = contributionId.ToString(), Order = 0 } ); newTransactions.Add( transaction ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} contributions imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { RockTransactionScope.WrapTransaction( () => { var transactionService = new FinancialTransactionService(); transactionService.RockContext.FinancialTransactions.AddRange( newTransactions ); transactionService.RockContext.SaveChanges(); var attributeValueService = new AttributeValueService(); foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) ) { var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault(); if ( attributeValue != null ) { attributeValue.EntityId = contribution.Id; attributeValueService.RockContext.AttributeValues.Add( attributeValue ); } } attributeValueService.RockContext.SaveChanges(); } ); newTransactions.Clear(); ReportPartialProgress(); } } } if ( newTransactions.Any() ) { RockTransactionScope.WrapTransaction( () => { var transactionService = new FinancialTransactionService(); transactionService.RockContext.FinancialTransactions.AddRange( newTransactions ); transactionService.RockContext.SaveChanges(); var attributeValueService = new AttributeValueService(); foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) ) { var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault(); if ( attributeValue != null ) { attributeValue.EntityId = contribution.Id; attributeValueService.RockContext.AttributeValues.Add( attributeValue ); } } attributeValueService.RockContext.SaveChanges(); } ); } ReportProgress( 100, string.Format( "Finished contribution import: {0:N0} contributions imported.", completed ) ); }
/// <summary> /// Handles the Click event of the btnSaveAttribute 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 btnSaveAttribute_Click( object sender, EventArgs e ) { using ( new Rock.Data.UnitOfWorkScope() ) { var attributeService = new AttributeService(); var attributeQualifierService = new AttributeQualifierService(); Rock.Model.Attribute attribute; int attributeId = ( ( hfIdAttribute.Value ) != null && hfIdAttribute.Value != String.Empty ) ? Int32.Parse( hfIdAttribute.Value ) : 0; if ( attributeId == 0 ) { attribute = new Rock.Model.Attribute(); attribute.IsSystem = false; attribute.EntityTypeId = _entityTypeId; attribute.EntityTypeQualifierColumn = _entityQualifier; attribute.EntityTypeQualifierValue = hfIdType.Value; attributeService.Add( attribute, CurrentPersonId ); } else { Rock.Web.Cache.AttributeCache.Flush( attributeId ); attribute = attributeService.Get( attributeId ); } attribute.Key = tbAttributeKey.Text; attribute.Name = tbAttributeName.Text; attribute.Category = tbAttributeCategory.Text; attribute.Description = tbAttributeDescription.Text; attribute.FieldTypeId = Int32.Parse( ddlAttributeFieldType.SelectedValue ); attribute.DefaultValue = tbAttributeDefaultValue.Text; attribute.IsGridColumn = cbAttributeGridColumn.Checked; attribute.IsRequired = cbAttributeRequired.Checked; attributeService.Save( attribute, CurrentPersonId ); } rGridAttribute_Bind( hfIdType.Value ); modalAttributes.Hide(); }
/// <summary> /// Handles the Delete event of the rGridAttribute 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 rGridAttribute_Delete( object sender, RowEventArgs e ) { var attributeService = new AttributeService(); Rock.Model.Attribute attribute = attributeService.Get( (int)rGridAttribute.DataKeys[e.RowIndex]["id"] ); if ( attribute != null ) { attributeService.Delete( attribute, CurrentPersonId ); attributeService.Save( attribute, CurrentPersonId ); } rGridAttribute_Bind( hfIdType.Value ); }
/// <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() ) { BinaryFileType binaryFileType; BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(); AttributeService attributeService = new AttributeService(); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(); CategoryService categoryService = new CategoryService(); int binaryFileTypeId = int.Parse( hfBinaryFileTypeId.Value ); if ( binaryFileTypeId == 0 ) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add( binaryFileType, CurrentPersonId ); } else { binaryFileType = binaryFileTypeService.Get( binaryFileTypeId ); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.AllowCaching = cbAllowCaching.Checked; if ( !string.IsNullOrWhiteSpace( cpStorageType.SelectedValue ) ) { var entityTypeService = new EntityTypeService(); var storageEntityType = entityTypeService.Get( new Guid( cpStorageType.SelectedValue ) ); if ( storageEntityType != null ) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } binaryFileType.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, binaryFileType ); if ( !binaryFileType.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { binaryFileTypeService.Save( binaryFileType, CurrentPersonId ); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get( binaryFileType.Guid ); /* Take care of Binary File Attributes */ var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( typeof( BinaryFile ) ).Id; // delete BinaryFileAttributes that are no longer configured in the UI var attributes = attributeService.Get( entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString() ); var selectedAttributeGuids = BinaryFileAttributesState.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, CurrentPersonId ); attributeService.Save( attr, CurrentPersonId ); } // add/update the BinaryFileAttributes that are assigned in the UI foreach ( var attributeState in BinaryFileAttributesState ) { Rock.Attribute.Helper.SaveAttributeEdits( attributeState, attributeService, attributeQualifierService, categoryService, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), CurrentPersonId ); } // SaveAttributeValues for the BinaryFileType Rock.Attribute.Helper.SaveAttributeValues( binaryFileType, 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 ) { bool hasValidationErrors = false; using ( new UnitOfWorkScope() ) { GroupTypeService groupTypeService = new GroupTypeService(); GroupService groupService = new GroupService(); AttributeService attributeService = new AttributeService(); int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt(); var groupTypeUIList = new List<GroupType>(); foreach ( var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType<CheckinGroupTypeEditor>().ToList() ) { var groupType = checkinGroupTypeEditor.GetCheckinGroupType(); groupTypeUIList.Add( groupType ); } var groupTypeDBList = new List<GroupType>(); var groupTypesToDelete = new List<GroupType>(); var groupsToDelete = new List<Group>(); var groupTypesToAddUpdate = new List<GroupType>(); var groupsToAddUpdate = new List<Group>(); GroupType parentGroupTypeDB = groupTypeService.Get( parentGroupTypeId ); GroupType parentGroupTypeUI = parentGroupTypeDB.Clone( false ); parentGroupTypeUI.ChildGroupTypes = groupTypeUIList; PopulateDeleteLists( groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI ); PopulateAddUpdateLists( groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI ); int binaryFileFieldTypeID = new FieldTypeService().Get( new Guid( Rock.SystemGuid.FieldType.BINARY_FILE ) ).Id; int binaryFileTypeId = new BinaryFileTypeService().Get( new Guid( Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL ) ).Id; RockTransactionScope.WrapTransaction( () => { // delete in reverse order to get deepest child items first groupsToDelete.Reverse(); foreach ( var groupToDelete in groupsToDelete ) { groupService.Delete( groupToDelete, this.CurrentPersonId ); groupService.Save( groupToDelete, this.CurrentPersonId ); } // delete in reverse order to get deepest child items first groupTypesToDelete.Reverse(); foreach ( var groupTypeToDelete in groupTypesToDelete ) { groupTypeService.Delete( groupTypeToDelete, this.CurrentPersonId ); groupTypeService.Save( groupTypeToDelete, this.CurrentPersonId ); } // Add/Update grouptypes and groups that are in the UI // Note: We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes // since the ChildGroupTypes may not exist in the database yet foreach ( GroupType groupTypeUI in groupTypesToAddUpdate ) { GroupType groupTypeDB = groupTypeService.Get( groupTypeUI.Guid ); if ( groupTypeDB == null ) { groupTypeDB = new GroupType(); groupTypeDB.Id = 0; groupTypeDB.Guid = groupTypeUI.Guid; } groupTypeDB.Name = groupTypeUI.Name; groupTypeDB.Order = groupTypeUI.Order; groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId; groupTypeDB.Attributes = groupTypeUI.Attributes; groupTypeDB.AttributeValues = groupTypeUI.AttributeValues; if ( groupTypeDB.Id == 0 ) { groupTypeService.Add( groupTypeDB, this.CurrentPersonId ); } if ( !groupTypeDB.IsValid ) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid ); groupTypeEditor.ForceContentVisible = true; return; } groupTypeService.Save( groupTypeDB, this.CurrentPersonId ); Rock.Attribute.Helper.SaveAttributeValues( groupTypeDB, this.CurrentPersonId ); // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes groupTypeDB = groupTypeService.Get( groupTypeDB.Guid ); // rebuild the CheckinLabel attributes from the UI (brute-force) foreach ( var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes( groupTypeDB ) ) { var attribute = attributeService.Get( labelAttributeDB.Value.Guid ); Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute, this.CurrentPersonId ); } foreach ( var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid] ) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add( new AttributeQualifier { Key = "binaryFileType", Value = binaryFileTypeId.ToString() } ); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId( typeof( GroupType ) ); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupTypeDB.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileId.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; if ( !attribute.IsValid ) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid ); groupTypeEditor.ForceContentVisible = true; return; } attributeService.Add( attribute, this.CurrentPersonId ); attributeService.Save( attribute, this.CurrentPersonId ); } } // Add/Update Groups foreach ( var groupUI in groupsToAddUpdate ) { Group groupDB = groupService.Get( groupUI.Guid ); if ( groupDB == null ) { groupDB = new Group(); groupDB.Guid = groupUI.Guid; } groupDB.Name = groupUI.Name; // delete any GroupLocations that were removed in the UI foreach ( var groupLocationDB in groupDB.GroupLocations.ToList() ) { if ( !groupUI.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationDB.LocationId ) ) { groupDB.GroupLocations.Remove( groupLocationDB ); } } // add any GroupLocations that were added in the UI foreach ( var groupLocationUI in groupUI.GroupLocations ) { if ( !groupDB.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationUI.LocationId ) ) { GroupLocation groupLocationDB = new GroupLocation { LocationId = groupLocationUI.LocationId }; groupDB.GroupLocations.Add( groupLocationDB ); } } groupDB.Order = groupUI.Order; // get GroupTypeId from database in case the groupType is new groupDB.GroupTypeId = groupTypeService.Get( groupUI.GroupType.Guid ).Id; groupDB.Attributes = groupUI.Attributes; groupDB.AttributeValues = groupUI.AttributeValues; if ( groupDB.Id == 0 ) { groupService.Add( groupDB, this.CurrentPersonId ); } if ( !groupDB.IsValid ) { hasValidationErrors = true; hasValidationErrors = true; CheckinGroupEditor groupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupEditor>().First( a => a.GroupGuid == groupDB.Guid ); groupEditor.ForceContentVisible = true; return; } groupService.Save( groupDB, this.CurrentPersonId ); Rock.Attribute.Helper.SaveAttributeValues( groupDB, this.CurrentPersonId ); } /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */ // save main parentGroupType with current UI ChildGroupTypes parentGroupTypeDB.ChildGroupTypes = new List<GroupType>(); parentGroupTypeDB.ChildGroupTypes.Clear(); foreach ( var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes ) { var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid ); parentGroupTypeDB.ChildGroupTypes.Add( childGroupTypeDB ); } groupTypeService.Save( parentGroupTypeDB, this.CurrentPersonId ); // loop thru all the other GroupTypes in the UI and save their childgrouptypes foreach ( var groupTypeUI in groupTypesToAddUpdate ) { var groupTypeDB = groupTypeService.Get( groupTypeUI.Guid ); groupTypeDB.ChildGroupTypes = new List<GroupType>(); groupTypeDB.ChildGroupTypes.Clear(); foreach ( var childGroupTypeUI in groupTypeUI.ChildGroupTypes ) { var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid ); groupTypeDB.ChildGroupTypes.Add( childGroupTypeDB ); } groupTypeService.Save( groupTypeDB, this.CurrentPersonId ); } } ); } if ( !hasValidationErrors ) { NavigateToParentPage(); } }
/// <summary> /// Handles the Delete event of the rGrid 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 rGrid_Delete( object sender, RowEventArgs e ) { var attributeService = new Rock.Model.AttributeService(); Rock.Model.Attribute attribute = attributeService.Get( (int)rGrid.DataKeys[e.RowIndex]["id"] ); if ( attribute != null ) { Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute, CurrentPersonId ); attributeService.Save( attribute, CurrentPersonId ); } BindGrid(); }
/// <summary> /// Maps the communication data. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapCommunication( IQueryable<Row> tableData ) { var categoryService = new CategoryService(); var personService = new PersonService(); List<DefinedValue> numberTypeValues = new DefinedValueService().Queryable() .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ).ToList(); // Add a Social Media category if it doesn't exist int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id; int socialMediaCategoryId = categoryService.Queryable().Where( c => c.EntityType.Id == attributeEntityTypeId && c.Name == "Social Media" ).Select( c => c.Id ).FirstOrDefault(); if ( socialMediaCategoryId == 0 ) { var socialMediaCategory = new Category(); socialMediaCategory.IsSystem = false; socialMediaCategory.Name = "Social Media"; socialMediaCategory.IconCssClass = "fa fa-twitter"; socialMediaCategory.EntityTypeId = attributeEntityTypeId; socialMediaCategory.EntityTypeQualifierColumn = "EntityTypeId"; socialMediaCategory.EntityTypeQualifierValue = PersonEntityTypeId.ToString(); socialMediaCategory.Order = 0; categoryService.Add( socialMediaCategory, ImportPersonAlias ); categoryService.Save( socialMediaCategory, ImportPersonAlias ); socialMediaCategoryId = socialMediaCategory.Id; } int visitInfoCategoryId = categoryService.Queryable().Where( c => c.EntityTypeId == attributeEntityTypeId && c.Name == "Visit Information" ).Select( c => c.Id ).FirstOrDefault(); // Look up additional Person attributes (existing) var personAttributes = new AttributeService().GetByEntityTypeId( PersonEntityTypeId ).ToList(); // Add an Attribute for the secondary email int secondaryEmailAttributeId = personAttributes.Where( a => a.Key == "SecondaryEmail" ).Select( a => a.Id ).FirstOrDefault(); if ( secondaryEmailAttributeId == 0 ) { var newSecondaryEmailAttribute = new Rock.Model.Attribute(); newSecondaryEmailAttribute.Key = "SecondaryEmail"; newSecondaryEmailAttribute.Name = "Secondary Email"; newSecondaryEmailAttribute.FieldTypeId = TextFieldTypeId; newSecondaryEmailAttribute.EntityTypeId = PersonEntityTypeId; newSecondaryEmailAttribute.EntityTypeQualifierValue = string.Empty; newSecondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty; newSecondaryEmailAttribute.Description = "The secondary email for this person"; newSecondaryEmailAttribute.DefaultValue = string.Empty; newSecondaryEmailAttribute.IsMultiValue = false; newSecondaryEmailAttribute.IsRequired = false; newSecondaryEmailAttribute.Order = 0; using ( new UnitOfWorkScope() ) { var attributeService = new AttributeService(); attributeService.Add( newSecondaryEmailAttribute ); var visitInfoCategory = new CategoryService().Get( visitInfoCategoryId ); newSecondaryEmailAttribute.Categories.Add( visitInfoCategory ); attributeService.Save( newSecondaryEmailAttribute ); secondaryEmailAttributeId = newSecondaryEmailAttribute.Id; } } // Add an Attribute for Twitter int twitterAttributeId = personAttributes.Where( a => a.Key == "TwitterUsername" ).Select( a => a.Id ).FirstOrDefault(); if ( twitterAttributeId == 0 ) { var newTwitterAttribute = new Rock.Model.Attribute(); newTwitterAttribute.Key = "TwitterUsername"; newTwitterAttribute.Name = "Twitter Username"; newTwitterAttribute.FieldTypeId = TextFieldTypeId; newTwitterAttribute.EntityTypeId = PersonEntityTypeId; newTwitterAttribute.EntityTypeQualifierValue = string.Empty; newTwitterAttribute.EntityTypeQualifierColumn = string.Empty; newTwitterAttribute.Description = "The Twitter username (or link) for this person"; newTwitterAttribute.DefaultValue = string.Empty; newTwitterAttribute.IsMultiValue = false; newTwitterAttribute.IsRequired = false; newTwitterAttribute.Order = 0; using ( new UnitOfWorkScope() ) { var attributeService = new AttributeService(); attributeService.Add( newTwitterAttribute ); var socialMediaCategory = new CategoryService().Get( socialMediaCategoryId ); newTwitterAttribute.Categories.Add( socialMediaCategory ); attributeService.Save( newTwitterAttribute ); twitterAttributeId = newTwitterAttribute.Id; } } // Add an Attribute for Facebook var facebookAttributeId = personAttributes.Where( a => a.Key == "FacebookUsername" ).Select( a => a.Id ).FirstOrDefault(); if ( facebookAttributeId == 0 ) { var newFacebookAttribute = new Rock.Model.Attribute(); newFacebookAttribute.Key = "FacebookUsername"; newFacebookAttribute.Name = "Facebook Username"; newFacebookAttribute.FieldTypeId = TextFieldTypeId; newFacebookAttribute.EntityTypeId = PersonEntityTypeId; newFacebookAttribute.EntityTypeQualifierValue = string.Empty; newFacebookAttribute.EntityTypeQualifierColumn = string.Empty; newFacebookAttribute.Description = "The Facebook username (or link) for this person"; newFacebookAttribute.DefaultValue = string.Empty; newFacebookAttribute.IsMultiValue = false; newFacebookAttribute.IsRequired = false; newFacebookAttribute.Order = 0; using ( new UnitOfWorkScope() ) { var attributeService = new AttributeService(); attributeService.Add( newFacebookAttribute ); var socialMediaCategory = new CategoryService().Get( socialMediaCategoryId ); newFacebookAttribute.Categories.Add( socialMediaCategory ); attributeService.Save( newFacebookAttribute ); facebookAttributeId = newFacebookAttribute.Id; } } var secondaryEmailAttribute = AttributeCache.Read( secondaryEmailAttributeId ); var twitterUsernameAttribute = AttributeCache.Read( twitterAttributeId ); var facebookUsernameAttribute = AttributeCache.Read( facebookAttributeId ); var existingNumbers = new PhoneNumberService().Queryable().ToList(); var newNumberList = new List<PhoneNumber>(); var updatedPersonList = new List<Person>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Checking communication import ({0:N0} found).", totalRows ) ); foreach ( var row in tableData ) { string value = row["Communication_Value"] as string; int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; int? personId = GetPersonId( individualId, householdId ); if ( personId != null && !string.IsNullOrWhiteSpace( value ) ) { DateTime? lastUpdated = row["LastUpdatedDate"] as DateTime?; string communicationComment = row["Communication_Comment"] as string; string type = row["Communication_Type"] as string; bool isListed = (bool)row["Listed"]; if ( type.Contains( "Phone" ) || type.Contains( "Mobile" ) ) { var extension = string.Empty; int extensionIndex = value.LastIndexOf( 'x' ); if ( extensionIndex > 0 ) { extension = value.Substring( extensionIndex ).AsNumeric(); value = value.Substring( 0, extensionIndex ).AsNumeric(); } else { value = value.AsNumeric(); } if ( !string.IsNullOrWhiteSpace( value ) ) { bool numberExists = existingNumbers.Any( n => n.PersonId == (int)personId && n.Number.Equals( value ) ); if ( !numberExists ) { var newNumber = new PhoneNumber(); newNumber.CreatedByPersonAliasId = ImportPersonAlias.Id; newNumber.ModifiedDateTime = lastUpdated; newNumber.PersonId = (int)personId; newNumber.IsMessagingEnabled = false; newNumber.IsUnlisted = !isListed; newNumber.Extension = extension.Left( 20 ); newNumber.Number = value.Left( 20 ); newNumber.Description = communicationComment; newNumber.NumberTypeValueId = numberTypeValues.Where( v => type.StartsWith( v.Name ) ) .Select( v => (int?)v.Id ).FirstOrDefault(); newNumberList.Add( newNumber ); completed++; } } } else { var person = personService.Get( (int)personId ); person.Attributes = new Dictionary<string, AttributeCache>(); person.AttributeValues = new Dictionary<string, List<AttributeValue>>(); if ( value.IsValidEmail() ) { string secondaryEmail = string.Empty; if ( string.IsNullOrWhiteSpace( person.Email ) || ( isListed && person.IsEmailActive == false ) ) { secondaryEmail = person.Email; person.Email = value.Left( 75 ); person.IsEmailActive = isListed; person.DoNotEmail = !isListed; person.ModifiedDateTime = lastUpdated; person.EmailNote = communicationComment; } else if ( !person.Email.Equals( value ) ) { secondaryEmail = value; } if ( !string.IsNullOrWhiteSpace( secondaryEmail ) ) { person.Attributes.Add( "SecondaryEmail", secondaryEmailAttribute ); person.AttributeValues.Add( "SecondaryEmail", new List<AttributeValue>() ); person.AttributeValues["SecondaryEmail"].Add( new AttributeValue() { AttributeId = secondaryEmailAttribute.Id, Value = secondaryEmail, Order = 0 } ); } } else if ( type.Contains( "Twitter" ) ) { person.Attributes.Add( "TwitterUsername", twitterUsernameAttribute ); person.AttributeValues.Add( "TwitterUsername", new List<AttributeValue>() ); person.AttributeValues["TwitterUsername"].Add( new AttributeValue() { AttributeId = twitterUsernameAttribute.Id, Value = value, Order = 0 } ); } else if ( type.Contains( "Facebook" ) ) { person.Attributes.Add( "FacebookUsername", facebookUsernameAttribute ); person.AttributeValues.Add( "FacebookUsername", new List<AttributeValue>() ); person.AttributeValues["FacebookUsername"].Add( new AttributeValue() { AttributeId = facebookUsernameAttribute.Id, Value = value, Order = 0 } ); } updatedPersonList.Add( person ); completed++; } if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} records imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { RockTransactionScope.WrapTransaction( () => { var numberService = new PhoneNumberService(); numberService.RockContext.PhoneNumbers.AddRange( newNumberList ); numberService.RockContext.SaveChanges(); // don't add updatedPeople, they're already tracked with current context personService.RockContext.SaveChanges(); var attributeValueService = new AttributeValueService(); foreach ( var updatedPerson in updatedPersonList.Where( p => p.Attributes.Any() ) ) { foreach ( var attributeCache in updatedPerson.Attributes.Select( a => a.Value ) ) { var newValue = updatedPerson.AttributeValues[attributeCache.Key].FirstOrDefault(); if ( newValue != null ) { newValue.EntityId = updatedPerson.Id; attributeValueService.RockContext.AttributeValues.Add( newValue ); } } } attributeValueService.RockContext.SaveChanges(); } ); // reset the person context so it doesn't bloat if ( updatedPersonList.Any() ) { personService = new PersonService(); updatedPersonList.Clear(); } newNumberList.Clear(); ReportPartialProgress(); } } } RockTransactionScope.WrapTransaction( () => { var numberService = new PhoneNumberService(); numberService.RockContext.PhoneNumbers.AddRange( newNumberList ); numberService.RockContext.SaveChanges(); personService.RockContext.SaveChanges(); var attributeValueService = new AttributeValueService(); foreach ( var updatedPerson in updatedPersonList.Where( p => p.Attributes.Any() ) ) { foreach ( var attributeCache in updatedPerson.Attributes.Select( a => a.Value ) ) { var newValue = updatedPerson.AttributeValues[attributeCache.Key].FirstOrDefault(); if ( newValue != null ) { newValue.EntityId = updatedPerson.Id; attributeValueService.RockContext.AttributeValues.Add( newValue ); } } } attributeValueService.RockContext.SaveChanges(); } ); ReportProgress( 100, string.Format( "Finished communication import: {0:N0} records imported.", completed ) ); }