/// <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> /// 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; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService( rockContext ); GroupService groupService = new GroupService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); GroupLocationService groupLocationService = new GroupLocationService( rockContext ); int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt(); var groupTypeUIList = new List<GroupType>(); foreach ( var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType<CheckinGroupTypeEditor>().ToList() ) { var groupType = checkinGroupTypeEditor.GetCheckinGroupType( rockContext ); 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 = FieldTypeCache.Read( Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid() ).Id; rockContext.WrapTransaction( () => { // delete in reverse order to get deepest child items first groupsToDelete.Reverse(); foreach ( var groupToDelete in groupsToDelete ) { groupService.Delete( groupToDelete ); } // delete in reverse order to get deepest child items first groupTypesToDelete.Reverse(); foreach ( var groupTypeToDelete in groupTypesToDelete ) { groupTypeService.Delete( groupTypeToDelete ); } rockContext.SaveChanges(); // 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.IsSystem = false; groupTypeDB.ShowInNavigation = false; groupTypeDB.ShowInGroupList = false; groupTypeDB.TakesAttendance = true; groupTypeDB.AttendanceRule = AttendanceRule.None; groupTypeDB.AttendancePrintTo = PrintTo.Default; groupTypeDB.AllowMultipleLocations = true; groupTypeDB.EnableLocationSchedules = true; } 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 ); } if ( !groupTypeDB.IsValid ) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid ); groupTypeEditor.Expanded = true; return; } rockContext.SaveChanges(); groupTypeDB.SaveAttributeValues( rockContext ); // 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.Attributes, rockContext ) ) { var attribute = attributeService.Get( labelAttributeDB.Value.Guid ); Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute ); } rockContext.SaveChanges(); foreach ( var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid] ) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add( new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL } ); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId( typeof( GroupType ) ); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupTypeDB.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.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.Expanded = true; return; } attributeService.Add( attribute ); } rockContext.SaveChanges(); } // 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 ) ) { groupLocationService.Delete( 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 ); } if ( !groupDB.IsValid ) { hasValidationErrors = true; hasValidationErrors = true; CheckinGroupEditor groupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupEditor>().First( a => a.GroupGuid == groupDB.Guid ); groupEditor.Expanded = true; return; } rockContext.SaveChanges(); groupDB.SaveAttributeValues(); } /* 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 ); } rockContext.SaveChanges(); // 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 ); } } rockContext.SaveChanges(); } ); if ( !hasValidationErrors ) { NavigateToParentPage(); } }
/// <summary> /// Saves a <see cref="Rock.Model.Person">Person's</see> user preference setting by key. /// </summary> /// <param name="person">The <see cref="Rock.Model.Person"/> who the preference value belongs to.</param> /// <param name="key">A <see cref="System.String"/> representing the key (name) of the preference setting.</param> /// <param name="value">The value.</param> public static void SaveUserPreference( Person person, string key, string value ) { int? PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id; using ( var rockContext = new RockContext() ) { var attributeService = new Model.AttributeService( rockContext ); var attribute = attributeService.Get( PersonEntityTypeId, string.Empty, string.Empty, key ); if ( attribute == null ) { var fieldTypeService = new Model.FieldTypeService( rockContext ); var fieldType = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ); attribute = new Model.Attribute(); attribute.IsSystem = false; attribute.EntityTypeId = PersonEntityTypeId; attribute.EntityTypeQualifierColumn = string.Empty; attribute.EntityTypeQualifierValue = string.Empty; attribute.Key = key; attribute.Name = key; attribute.IconCssClass = string.Empty; attribute.DefaultValue = string.Empty; attribute.IsMultiValue = false; attribute.IsRequired = false; attribute.Description = string.Empty; attribute.FieldTypeId = fieldType.Id; attribute.Order = 0; attributeService.Add( attribute ); rockContext.SaveChanges(); } var attributeValueService = new Model.AttributeValueService( rockContext ); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, person.Id ); if ( string.IsNullOrWhiteSpace( value ) ) { // Delete existing value if no existing value if ( attributeValue != null ) { attributeValueService.Delete( attributeValue ); } } else { if ( attributeValue == null ) { attributeValue = new Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = person.Id; attributeValueService.Add( attributeValue ); } attributeValue.Value = value; } rockContext.SaveChanges(); } }
/// <summary> /// Sets the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="saveValue">if set to <c>true</c> [save value].</param> /// <param name="rockContext">The rock context.</param> public void SetValue( string key, string value, bool saveValue, RockContext rockContext ) { AttributeCache attributeCache = null; if ( saveValue ) { // Save new value rockContext = rockContext ?? new RockContext(); var attributeValueService = new AttributeValueService( rockContext ); var attributeValue = attributeValueService.GetGlobalAttributeValue( key ); if ( attributeValue == null ) { var attributeService = new AttributeService( rockContext ); 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 ); rockContext.SaveChanges(); } attributeValue = new AttributeValue(); attributeValue.IsSystem = false; attributeValue.AttributeId = attribute.Id; attributeValueService.Add( attributeValue ); } attributeValue.Value = value; rockContext.SaveChanges(); } lock(_obj) { attributeIds = null; } AttributeValues.AddOrUpdate( key, value, ( k, v ) => value ); attributeCache = Attributes.FirstOrDefault( a => a.Key.Equals( key, StringComparison.OrdinalIgnoreCase ) ); if ( attributeCache != null ) { value = attributeCache.FieldType.Field.FormatValue( null, value, attributeCache.QualifierValues, false ); } AttributeValuesFormatted.AddOrUpdate( key, value, (k, v) => value); }
/// <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> /// Sets the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="saveValue">if set to <c>true</c> [save value].</param> /// <param name="rockContext">The rock context.</param> public void SetValue( string key, string value, bool saveValue, RockContext rockContext = null ) { if ( saveValue ) { if ( rockContext == null ) { rockContext = new RockContext(); } // Save new value var attributeValueService = new AttributeValueService( rockContext ); var attributeValue = attributeValueService.GetGlobalAttributeValue( key ); if ( attributeValue == null ) { var attributeService = new AttributeService( rockContext ); 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 ); rockContext.SaveChanges(); Attributes.Add( AttributeCache.Read( attribute.Id ) ); } attributeValue = new AttributeValue(); attributeValueService.Add( attributeValue ); 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; rockContext.SaveChanges(); } 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 ) ); } } }
/// <summary> /// Saves the attribute value. /// </summary> /// <param name="workflow">The workflow.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="fieldType">Type of the field.</param> /// <param name="rockContext">The rock context.</param> /// <param name="qualifiers">The qualifiers.</param> /// <returns></returns> private static bool SaveAttributeValue( Rock.Model.Workflow workflow, string key, string value, FieldTypeCache fieldType, RockContext rockContext, Dictionary<string, string> qualifiers = null ) { bool createdNewAttribute = false; if (workflow.Attributes.ContainsKey(key)) { workflow.SetAttributeValue( key, value ); } else { // Read the attribute var attributeService = new AttributeService( rockContext ); var attribute = attributeService .Get( workflow.TypeId, "WorkflowTypeId", workflow.WorkflowTypeId.ToString() ) .Where( a => a.Key == key ) .FirstOrDefault(); // If workflow attribute doesn't exist, create it // ( should only happen first time a background check is processed for given workflow type) if ( attribute == null ) { attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = workflow.TypeId; attribute.EntityTypeQualifierColumn = "WorkflowTypeId"; attribute.EntityTypeQualifierValue = workflow.WorkflowTypeId.ToString(); attribute.Name = key.SplitCase(); attribute.Key = key; attribute.FieldTypeId = fieldType.Id; attributeService.Add( attribute ); if ( qualifiers != null ) { foreach ( var keyVal in qualifiers ) { var qualifier = new Rock.Model.AttributeQualifier(); qualifier.Key = keyVal.Key; qualifier.Value = keyVal.Value; attribute.AttributeQualifiers.Add( qualifier ); } } createdNewAttribute = true; } // Set the value for this action's instance to the current time var attributeValue = new Rock.Model.AttributeValue(); attributeValue.Attribute = attribute; attributeValue.EntityId = workflow.Id; attributeValue.Value = value; new AttributeValueService( rockContext ).Add( attributeValue ); } return createdNewAttribute; }
/// <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(); }
protected void btnSave_Click( object sender, EventArgs e ) { hfAreaGroupClicked.Value = "true"; using ( var rockContext = new RockContext() ) { var attributeService = new AttributeService( rockContext ); if ( checkinArea.Visible ) { var groupTypeService = new GroupTypeService( rockContext ); var groupType = groupTypeService.Get( checkinArea.GroupTypeGuid ); if ( groupType != null ) { checkinArea.GetGroupTypeValues( groupType ); if ( groupType.IsValid ) { rockContext.SaveChanges(); groupType.SaveAttributeValues( rockContext ); bool AttributesUpdated = false; // rebuild the CheckinLabel attributes from the UI (brute-force) foreach ( var labelAttribute in CheckinArea.GetCheckinLabelAttributes( groupType.Attributes ) ) { var attribute = attributeService.Get( labelAttribute.Value.Guid ); Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute ); AttributesUpdated = true; } // Make sure default role is set if ( !groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any() ) { groupType.DefaultGroupRoleId = groupType.Roles.First().Id; } rockContext.SaveChanges(); int labelOrder = 0; int binaryFileFieldTypeID = FieldTypeCache.Read( Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid() ).Id; foreach ( var checkinLabelAttributeInfo in checkinArea.CheckinLabels ) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add( new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL } ); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId( typeof( GroupType ) ); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupType.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; attribute.Order = labelOrder++; if ( !attribute.IsValid ) { return; } attributeService.Add( attribute ); AttributesUpdated = true; } rockContext.SaveChanges(); GroupTypeCache.Flush( groupType.Id ); Rock.CheckIn.KioskDevice.FlushAll(); if ( AttributesUpdated ) { AttributeCache.FlushEntityAttributes(); } nbSaveSuccess.Visible = true; BuildRows(); } else { ShowInvalidResults( groupType.ValidationResults ); } } } if ( checkinGroup.Visible ) { var groupService = new GroupService( rockContext ); var groupLocationService = new GroupLocationService( rockContext ); var group = groupService.Get( checkinGroup.GroupGuid ); if ( group != null ) { group.LoadAttributes( rockContext ); checkinGroup.GetGroupValues( group ); // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later var newLocationIds = checkinGroup.Locations.Select( l => l.LocationId ).ToList(); foreach ( var groupLocation in group.GroupLocations.Where( l => !newLocationIds.Contains( l.LocationId ) ).ToList() ) { groupLocationService.Delete( groupLocation ); group.GroupLocations.Remove( groupLocation ); } var existingLocationIds = group.GroupLocations.Select( g => g.LocationId ).ToList(); foreach ( var item in checkinGroup.Locations.Where( l => !existingLocationIds.Contains( l.LocationId ) ).ToList() ) { var groupLocation = new GroupLocation(); groupLocation.LocationId = item.LocationId; group.GroupLocations.Add( groupLocation ); } // Set the new order foreach ( var item in checkinGroup.Locations.OrderBy( l => l.Order ).ToList() ) { var groupLocation = group.GroupLocations.FirstOrDefault( gl => gl.LocationId == item.LocationId ); groupLocation.Order = item.Order ?? 0; } if ( group.IsValid ) { rockContext.SaveChanges(); group.SaveAttributeValues( rockContext ); Rock.CheckIn.KioskDevice.FlushAll(); nbSaveSuccess.Visible = true; BuildRows(); } else { ShowInvalidResults( group.ValidationResults ); } } } } hfIsDirty.Value = "false"; }
/// <summary> /// Processes the confirmation. /// </summary> /// <param name="errorMessage">The error message.</param> /// <returns></returns> private bool ProcessConfirmation( out string errorMessage ) { var rockContext = new RockContext(); if ( string.IsNullOrWhiteSpace( TransactionCode ) ) { GatewayComponent gateway = null; var financialGateway = hfPaymentTab.Value == "ACH" ? _achGateway : _ccGateway; if ( financialGateway != null ) { gateway = financialGateway.GetGatewayComponent(); } if ( gateway == null ) { errorMessage = "There was a problem creating the payment gateway information"; return false; } Person person = GetPerson( true ); if ( person == null ) { errorMessage = "There was a problem creating the person information"; return false; } if ( !person.PrimaryAliasId.HasValue ) { errorMessage = "There was a problem creating the person's primary alias"; return false; } PaymentInfo paymentInfo = GetPaymentInfo(); if ( paymentInfo == null ) { errorMessage = "There was a problem creating the payment information"; return false; } else { paymentInfo.FirstName = person.FirstName; paymentInfo.LastName = person.LastName; } if ( paymentInfo.CreditCardTypeValue != null ) { CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id; } if ( _showCommmentEntry ) { paymentInfo.Comment1 = !string.IsNullOrWhiteSpace( GetAttributeValue( "PaymentComment" ) ) ? string.Format( "{0}: {1}", GetAttributeValue( "PaymentComment" ), txtCommentEntry.Text ) : txtCommentEntry.Text; } else { paymentInfo.Comment1 = GetAttributeValue( "PaymentComment" ); } PaymentSchedule schedule = GetSchedule(); if ( schedule != null ) { schedule.PersonId = person.Id; var scheduledTransaction = gateway.AddScheduledPayment( financialGateway, schedule, paymentInfo, out errorMessage ); if ( scheduledTransaction != null ) { scheduledTransaction.TransactionFrequencyValueId = schedule.TransactionFrequencyValue.Id; scheduledTransaction.AuthorizedPersonAliasId = person.PrimaryAliasId.Value; scheduledTransaction.FinancialGatewayId = financialGateway.Id; if ( scheduledTransaction.FinancialPaymentDetail == null ) { scheduledTransaction.FinancialPaymentDetail = new FinancialPaymentDetail(); } scheduledTransaction.FinancialPaymentDetail.SetFromPaymentInfo( paymentInfo, gateway, rockContext ); var changeSummary = new StringBuilder(); changeSummary.AppendFormat( "{0} starting {1}", schedule.TransactionFrequencyValue.Value, schedule.StartDate.ToShortDateString() ); changeSummary.AppendLine(); changeSummary.Append( paymentInfo.CurrencyTypeValue.Value ); if ( paymentInfo.CreditCardTypeValue != null ) { changeSummary.AppendFormat( " - {0}", paymentInfo.CreditCardTypeValue.Value ); } changeSummary.AppendFormat( " {0}", paymentInfo.MaskedNumber ); changeSummary.AppendLine(); foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) ) { var transactionDetail = new FinancialScheduledTransactionDetail(); transactionDetail.Amount = account.Amount; transactionDetail.AccountId = account.Id; scheduledTransaction.ScheduledTransactionDetails.Add( transactionDetail ); changeSummary.AppendFormat( "{0}: {1}", account.Name, account.Amount.FormatAsCurrency() ); changeSummary.AppendLine(); } var transactionService = new FinancialScheduledTransactionService( rockContext ); transactionService.Add( scheduledTransaction ); rockContext.SaveChanges(); // Add a note about the change var noteType = NoteTypeCache.Read( Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid() ); if ( noteType != null ) { var noteService = new NoteService( rockContext ); var note = new Note(); note.NoteTypeId = noteType.Id; note.EntityId = scheduledTransaction.Id; note.Caption = "Created Transaction"; note.Text = changeSummary.ToString(); noteService.Add( note ); } rockContext.SaveChanges(); ScheduleId = scheduledTransaction.GatewayScheduleId; TransactionCode = scheduledTransaction.TransactionCode; } else { return false; } } else { var transaction = gateway.Charge( financialGateway, paymentInfo, out errorMessage ); if ( transaction != null ) { var txnChanges = new List<string>(); txnChanges.Add( "Created Transaction" ); History.EvaluateChange( txnChanges, "Transaction Code", string.Empty, transaction.TransactionCode ); transaction.AuthorizedPersonAliasId = person.PrimaryAliasId; History.EvaluateChange( txnChanges, "Person", string.Empty, person.FullName ); transaction.TransactionDateTime = RockDateTime.Now; History.EvaluateChange( txnChanges, "Date/Time", null, transaction.TransactionDateTime ); transaction.FinancialGatewayId = financialGateway.Id; History.EvaluateChange( txnChanges, "Gateway", string.Empty, financialGateway.Name ); var txnType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ); transaction.TransactionTypeValueId = txnType.Id; History.EvaluateChange( txnChanges, "Type", string.Empty, txnType.Value ); if ( transaction.FinancialPaymentDetail == null ) { transaction.FinancialPaymentDetail = new FinancialPaymentDetail(); } transaction.FinancialPaymentDetail.SetFromPaymentInfo( paymentInfo, gateway, rockContext, txnChanges ); Guid sourceGuid = Guid.Empty; if ( Guid.TryParse( GetAttributeValue( "Source" ), out sourceGuid ) ) { var source = DefinedValueCache.Read( sourceGuid ); if ( source != null ) { transaction.SourceTypeValueId = source.Id; History.EvaluateChange( txnChanges, "Source", string.Empty, source.Value ); } } foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) ) { var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = account.Amount; transactionDetail.AccountId = account.Id; transaction.TransactionDetails.Add( transactionDetail ); History.EvaluateChange( txnChanges, account.Name, 0.0M.FormatAsCurrency(), transactionDetail.Amount.FormatAsCurrency() ); } var batchService = new FinancialBatchService( rockContext ); // Get the batch var batch = batchService.Get( GetAttributeValue( "BatchNamePrefix" ), paymentInfo.CurrencyTypeValue, paymentInfo.CreditCardTypeValue, transaction.TransactionDateTime.Value, financialGateway.GetBatchTimeOffset() ); var batchChanges = new List<string>(); if ( batch.Id == 0 ) { batchChanges.Add( "Generated the batch" ); History.EvaluateChange( batchChanges, "Batch Name", string.Empty, batch.Name ); History.EvaluateChange( batchChanges, "Status", null, batch.Status ); History.EvaluateChange( batchChanges, "Start Date/Time", null, batch.BatchStartDateTime ); History.EvaluateChange( batchChanges, "End Date/Time", null, batch.BatchEndDateTime ); } decimal newControlAmount = batch.ControlAmount + transaction.TotalAmount; History.EvaluateChange( batchChanges, "Control Amount", batch.ControlAmount.FormatAsCurrency(), newControlAmount.FormatAsCurrency() ); batch.ControlAmount = newControlAmount; transaction.BatchId = batch.Id; batch.Transactions.Add( transaction ); rockContext.SaveChanges(); HistoryService.SaveChanges( rockContext, typeof( FinancialBatch ), Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(), batch.Id, batchChanges ); HistoryService.SaveChanges( rockContext, typeof( FinancialBatch ), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), batch.Id, txnChanges, person.FullName, typeof( FinancialTransaction ), transaction.Id ); SendReceipt( transaction.Id ); TransactionCode = transaction.TransactionCode; } else { return false; } } tdTransactionCodeReceipt.Description = TransactionCode; tdTransactionCodeReceipt.Visible = !string.IsNullOrWhiteSpace( TransactionCode ); tdScheduleId.Description = ScheduleId; tdScheduleId.Visible = !string.IsNullOrWhiteSpace( ScheduleId ); tdNameReceipt.Description = paymentInfo.FullName; tdPhoneReceipt.Description = paymentInfo.Phone; tdEmailReceipt.Description = paymentInfo.Email; tdAddressReceipt.Description = string.Format( "{0} {1}, {2} {3}", paymentInfo.Street1, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode ); rptAccountListReceipt.DataSource = SelectedAccounts.Where( a => a.Amount != 0 ); rptAccountListReceipt.DataBind(); tdTotalReceipt.Description = paymentInfo.Amount.ToString( "C" ); tdPaymentMethodReceipt.Description = paymentInfo.CurrencyTypeValue.Description; tdAccountNumberReceipt.Description = paymentInfo.MaskedNumber; tdWhenReceipt.Description = schedule != null ? schedule.ToString() : "Today"; // If there was a transaction code returned and this was not already created from a previous saved account, // show the option to save the account. if ( !( paymentInfo is ReferencePaymentInfo ) && !string.IsNullOrWhiteSpace( TransactionCode ) && gateway.SupportsSavedAccount( paymentInfo.CurrencyTypeValue ) ) { cbSaveAccount.Visible = true; pnlSaveAccount.Visible = true; txtSaveAccount.Visible = true; // If current person does not have a login, have them create a username and password phCreateLogin.Visible = !new UserLoginService( rockContext ).GetByPersonId( person.Id ).Any(); } else if ( !new UserLoginService( rockContext ).GetByPersonId( person.Id ).Any() ) { pnlSaveAccount.Visible = true; phCreateLogin.Visible = true; cbSaveAccount.Visible = false; txtSaveAccount.Visible = false; } else { pnlSaveAccount.Visible = false; } if ( PageParameter( "argsd" ) == "1" ) { var rc = new RockContext(); var ats = new AttributeService( rc ); var argsd = ats.Queryable().Where( x => x.Key == "AutomatedRecurringGiftSetupDate" ).FirstOrDefault(); if ( argsd == null ) { argsd = new Rock.Model.Attribute(); argsd.FieldTypeId = 85; argsd.EntityTypeId = 15; argsd.Key = "AutomatedRecurringGiftSetupDate"; argsd.Name = "Automated Recurring Gift Setup Date"; argsd.Guid = Guid.NewGuid(); argsd.CreatedDateTime = argsd.ModifiedDateTime = DateTime.Now; ats.Add( argsd ); rc.SaveChanges(); rc = new RockContext(); ats = new AttributeService( rc ); argsd = ats.Queryable().Where( x => x.Key == "AutomatedRecurringGiftSetupDate" ).FirstOrDefault(); } if ( argsd != null ) { var atvs = new AttributeValueService( rc ); var argsdVal = atvs.Queryable().Where( x => x.AttributeId == argsd.Id && x.EntityId == person.Id ).FirstOrDefault(); if ( argsdVal == null ) { argsdVal = new Rock.Model.AttributeValue(); argsdVal.AttributeId = argsd.Id; argsdVal.EntityId = person.Id; argsdVal.Value = DateTime.Now.ToString( "o" ); argsdVal.Guid = Guid.NewGuid(); argsdVal.CreatedDateTime = argsdVal.ModifiedDateTime = DateTime.Now; atvs.Add( argsdVal ); rc.SaveChanges(); } else { argsdVal.Value = DateTime.Now.ToString( "o" ); rc.SaveChanges(); } } } return true; } else { pnlDupWarning.Visible = true; divActions.Visible = false; errorMessage = string.Empty; return false; } }
/// <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 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> /// Displays the edit list. /// </summary> private void DisplayEditList() { lEditHeader.Text = GetAttributeValue( "EditHeader" ); lEditFooter.Text = GetAttributeValue( "EditFooter" ); if ( _definedType != null ) { using ( var rockContext = new RockContext() ) { var entityType = EntityTypeCache.Read( "Rock.Model.DefinedValue"); var definedType = new DefinedTypeService( rockContext ).Get( _definedType.Id ); if ( definedType != null && entityType != null ) { var attributeService = new AttributeService( rockContext ); var attributes = new AttributeService( rockContext ) .Get( entityType.Id, "DefinedTypeId", definedType.Id.ToString() ) .ToList(); // Verify (and create if neccessary) the "Is Link" attribute if ( !attributes.Any( a => a.Key == "IsLink" ) ) { var fieldType = FieldTypeCache.Read( Rock.SystemGuid.FieldType.BOOLEAN ); if ( entityType != null && fieldType != null ) { var attribute = new Rock.Model.Attribute(); attributeService.Add( attribute ); attribute.EntityTypeId = entityType.Id; attribute.EntityTypeQualifierColumn = "DefinedTypeId"; attribute.EntityTypeQualifierValue = definedType.Id.ToString(); attribute.FieldTypeId = fieldType.Id; attribute.Name = "Is Link"; attribute.Key = "IsLink"; attribute.Description = "Flag indicating if value is a link (vs Header)"; attribute.IsGridColumn = true; attribute.DefaultValue = true.ToString(); var qualifier1 = new AttributeQualifier(); qualifier1.Key = "truetext"; qualifier1.Value = "Yes"; attribute.AttributeQualifiers.Add( qualifier1 ); var qualifier2 = new AttributeQualifier(); qualifier2.Key = "falsetext"; qualifier2.Value = "No"; attribute.AttributeQualifiers.Add( qualifier2 ); rockContext.SaveChanges(); DefinedTypeCache.Flush( definedType.Id ); foreach( var dv in definedType.DefinedValues ) { DefinedValueCache.Flush( dv.Id ); } } } } } BindGrid(); pnlView.Visible = false; pnlEdit.Visible = true; } }
/// <summary> /// Adds or Updates a <see cref="Rock.Model.Attribute" /> item for the attribute. /// </summary> /// <param name="property">The property.</param> /// <param name="entityTypeId">The entity type id.</param> /// <param name="entityQualifierColumn">The entity qualifier column.</param> /// <param name="entityQualifierValue">The entity qualifier value.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> private static bool UpdateAttribute( FieldAttribute property, int? entityTypeId, string entityQualifierColumn, string entityQualifierValue, RockContext rockContext = null ) { bool updated = false; rockContext = rockContext ?? new RockContext(); var attributeService = new AttributeService( rockContext ); var attributeQualifierService = new AttributeQualifierService( rockContext ); var fieldTypeService = new FieldTypeService(rockContext); var categoryService = new CategoryService( rockContext ); var propertyCategories = property.Category.SplitDelimitedValues( false ).ToList(); // Look for an existing attribute record based on the entity, entityQualifierColumn and entityQualifierValue Model.Attribute attribute = attributeService.Get( entityTypeId, entityQualifierColumn, entityQualifierValue, property.Key ); if ( attribute == null ) { // If an existing attribute record doesn't exist, create a new one updated = true; attribute = new Model.Attribute(); attribute.EntityTypeId = entityTypeId; attribute.EntityTypeQualifierColumn = entityQualifierColumn; attribute.EntityTypeQualifierValue = entityQualifierValue; attribute.Key = property.Key; attribute.IconCssClass = string.Empty; attribute.IsGridColumn = false; } else { // Check to see if the existing attribute record needs to be updated if ( attribute.Name != property.Name || attribute.DefaultValue != property.DefaultValue || attribute.Description != property.Description || attribute.Order != property.Order || attribute.FieldType.Assembly != property.FieldTypeAssembly || attribute.FieldType.Class != property.FieldTypeClass || attribute.IsRequired != property.IsRequired ) { updated = true; } // Check category else if ( attribute.Categories.Select( c => c.Name ).Except( propertyCategories ).Any() || propertyCategories.Except( attribute.Categories.Select( c => c.Name ) ).Any() ) { updated = true; } // Check the qualifier values else if ( attribute.AttributeQualifiers.Select( q => q.Key ).Except( property.FieldConfigurationValues.Select( c => c.Key ) ).Any() || property.FieldConfigurationValues.Select( c => c.Key ).Except( attribute.AttributeQualifiers.Select( q => q.Key ) ).Any() ) { updated = true; } else { foreach ( var attributeQualifier in attribute.AttributeQualifiers ) { if ( !property.FieldConfigurationValues.ContainsKey( attributeQualifier.Key ) || property.FieldConfigurationValues[attributeQualifier.Key].Value != attributeQualifier.Value ) { updated = true; break; } } } } if ( updated ) { // Update the attribute attribute.Name = property.Name; attribute.Description = property.Description; attribute.DefaultValue = property.DefaultValue; attribute.Order = property.Order; attribute.IsRequired = property.IsRequired; attribute.Categories.Clear(); if ( propertyCategories.Any() ) { foreach ( string propertyCategory in propertyCategories ) { int attributeEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id; var category = categoryService.Get( propertyCategory, attributeEntityTypeId, "EntityTypeId", entityTypeId.ToString() ).FirstOrDefault(); if ( category == null ) { category = new Category(); category.Name = propertyCategory; category.EntityTypeId = attributeEntityTypeId; category.EntityTypeQualifierColumn = "EntityTypeId"; category.EntityTypeQualifierValue = entityTypeId.ToString(); category.Order = 0; } attribute.Categories.Add( category ); } } foreach ( var qualifier in attribute.AttributeQualifiers.ToList() ) { attributeQualifierService.Delete( qualifier ); } attribute.AttributeQualifiers.Clear(); foreach ( var configValue in property.FieldConfigurationValues ) { var qualifier = new Model.AttributeQualifier(); qualifier.Key = configValue.Key; qualifier.Value = configValue.Value.Value; attribute.AttributeQualifiers.Add( qualifier ); } // Try to set the field type by searching for an existing field type with the same assembly and class name if ( attribute.FieldType == null || attribute.FieldType.Assembly != property.FieldTypeAssembly || attribute.FieldType.Class != property.FieldTypeClass ) { attribute.FieldType = fieldTypeService.Queryable().FirstOrDefault( f => f.Assembly == property.FieldTypeAssembly && f.Class == property.FieldTypeClass ); } // If this is a new attribute, add it, otherwise remove the exiting one from the cache if ( attribute.Id == 0 ) { attributeService.Add( attribute ); } else { AttributeCache.Flush( attribute.Id ); } rockContext.SaveChanges(); return true; } else { return false; } }
/// <summary> /// Sets the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetValue( string key, string value ) { var rockContext = new Rock.Data.RockContext(); var attributeService = new AttributeService( rockContext ); var attribute = attributeService.GetSystemSetting( key ); if ( attribute == null ) { attribute = new Rock.Model.Attribute(); attribute.FieldTypeId = FieldTypeCache.Read( new Guid( SystemGuid.FieldType.TEXT ) ).Id; attribute.EntityTypeQualifierColumn = Rock.Model.Attribute.SYSTEM_SETTING_QUALIFIER; attribute.EntityTypeQualifierValue = string.Empty; attribute.Key = key; attribute.Name = key.SplitCase(); attribute.DefaultValue = value; attributeService.Add( attribute ); } else { attribute.DefaultValue = value; } rockContext.SaveChanges(); AttributeCache.Flush( attribute.Id ); var settings = SystemSettings.Read(); var attributeCache = settings.Attributes.FirstOrDefault( a => a.Key.Equals( key, StringComparison.OrdinalIgnoreCase ) ); if ( attributeCache != null ) { attributeCache.DefaultValue = value; } else { settings.Attributes.Add( AttributeCache.Read( attribute.Id ) ); } }
/// <summary> /// Saves any attribute edits made to an attribute /// </summary> /// <param name="newAttribute">The new attribute.</param> /// <param name="entityTypeId">The entity type identifier.</param> /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param> /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static Rock.Model.Attribute SaveAttributeEdits( Rock.Model.Attribute newAttribute, int? entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null ) { rockContext = rockContext ?? new RockContext(); var internalAttributeService = new AttributeService( rockContext ); var attributeQualifierService = new AttributeQualifierService( rockContext ); var categoryService = new CategoryService( rockContext ); // If attribute is not valid, return null if (!newAttribute.IsValid) { return null; } // Create a attribute model that will be saved Rock.Model.Attribute attribute = null; // Check to see if this was an existing or new attribute if (newAttribute.Id > 0) { // If editing an existing attribute, remove all the old qualifiers in case they were changed foreach ( var oldQualifier in attributeQualifierService.GetByAttributeId( newAttribute.Id ).ToList() ) { attributeQualifierService.Delete( oldQualifier ); } rockContext.SaveChanges(); // Then re-load the existing attribute attribute = internalAttributeService.Get( newAttribute.Id ); } if ( attribute == null ) { // If the attribute didn't exist, create it attribute = new Rock.Model.Attribute(); internalAttributeService.Add( attribute ); } else { // If it did exist, set the new attribute ID and GUID since we're copying all properties in the next step newAttribute.Id = attribute.Id; newAttribute.Guid = attribute.Guid; } // Copy all the properties from the new attribute to the attribute model attribute.CopyPropertiesFrom( newAttribute ); // Add any qualifiers foreach ( var qualifier in newAttribute.AttributeQualifiers ) { attribute.AttributeQualifiers.Add( new AttributeQualifier { Key = qualifier.Key, Value = qualifier.Value, IsSystem = qualifier.IsSystem } ); } // Add any categories attribute.Categories.Clear(); foreach ( var category in newAttribute.Categories ) { attribute.Categories.Add( categoryService.Get( category.Id ) ); } attribute.EntityTypeId = entityTypeId; attribute.EntityTypeQualifierColumn = entityTypeQualifierColumn; attribute.EntityTypeQualifierValue = entityTypeQualifierValue; rockContext.SaveChanges(); if ( attribute != null ) { Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); // If this is a global attribute, flush all global attributes if ( !entityTypeId.HasValue && entityTypeQualifierColumn == string.Empty && entityTypeQualifierValue == string.Empty ) { Rock.Web.Cache.GlobalAttributesCache.Flush(); } } return attribute; }
/// <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> /// Maps the specified folder. /// </summary> /// <param name="folder">The folder.</param> /// <param name="ministryFileType">Type of the ministry file.</param> /// <param name="storageProvider">The storage provider.</param> public void Map( ZipArchive folder, BinaryFileType ministryFileType, ProviderComponent storageProvider ) { var lookupContext = new RockContext(); var personEntityTypeId = EntityTypeCache.GetId<Person>(); var fileFieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.FILE.AsGuid(), lookupContext ).Id; var existingAttributes = new AttributeService( lookupContext ).GetByFieldTypeId( fileFieldTypeId ) .Where( a => a.EntityTypeId == personEntityTypeId ) .ToDictionary( a => a.Key, a => a.Id ); var emptyJsonObject = "{}"; var newFileList = new List<DocumentKeys>(); int completed = 0; int totalRows = folder.Entries.Count; int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying files import ({0:N0} found.", totalRows ) ); foreach ( var file in folder.Entries ) { var fileExtension = Path.GetExtension( file.Name ); var fileMimeType = Extensions.GetMIMEType( file.Name ); if ( BinaryFileComponent.FileTypeBlackList.Contains( fileExtension ) ) { LogException( "Binary File Import", string.Format( "{0} filetype not allowed ({1})", fileExtension, file.Name ) ); continue; } else if ( fileMimeType == null ) { LogException( "Binary File Import", string.Format( "{0} filetype not recognized ({1})", fileExtension, file.Name ) ); continue; } string[] parsedFileName = file.Name.Split( '_' ); // Ministry docs should follow this pattern: // 0. Firstname // 1. Lastname // 2. ForeignId // 3. Filename var personForeignId = parsedFileName[2].AsType<int?>(); var personKeys = BinaryFileComponent.ImportedPeople.FirstOrDefault( p => p.IndividualId == personForeignId ); if ( personKeys != null ) { var rockFile = new Rock.Model.BinaryFile(); rockFile.IsSystem = false; rockFile.IsTemporary = false; rockFile.FileName = file.Name; rockFile.MimeType = fileMimeType; rockFile.BinaryFileTypeId = ministryFileType.Id; rockFile.CreatedDateTime = file.LastWriteTime.DateTime; rockFile.ModifiedDateTime = ImportDateTime; rockFile.Description = string.Format( "Imported as {0}", file.Name ); rockFile.SetStorageEntityTypeId( ministryFileType.StorageEntityTypeId ); rockFile.StorageEntitySettings = emptyJsonObject; if ( ministryFileType.AttributeValues.Any() ) { rockFile.StorageEntitySettings = ministryFileType.AttributeValues .ToDictionary( a => a.Key, v => v.Value.Value ).ToJson(); } // use base stream instead of file stream to keep the byte[] // NOTE: if byte[] converts to a string it will corrupt the stream using ( var fileContent = new StreamReader( file.Open() ) ) { rockFile.ContentStream = new MemoryStream( fileContent.BaseStream.ReadBytesToEnd() ); } var attributePattern = "[A-Za-z0-9-]+"; var attributeName = Regex.Match( parsedFileName[3].RemoveWhitespace(), attributePattern ); var attributeKey = attributeName.Value.RemoveWhitespace(); // change key to default key for Background Check Documents if ( attributeKey == "BackgroundCheck" ) { attributeKey = "BackgroundCheckDocument"; } if ( !existingAttributes.ContainsKey( attributeKey ) ) { var newAttribute = new Attribute(); newAttribute.FieldTypeId = fileFieldTypeId; newAttribute.EntityTypeId = personEntityTypeId; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.Key = attributeKey; newAttribute.Name = attributeName.Value; newAttribute.Description = attributeName.Value + " created by binary file import"; newAttribute.CreatedDateTime = ImportDateTime; newAttribute.ModifiedDateTime = ImportDateTime; newAttribute.IsGridColumn = false; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.AllowSearch = false; newAttribute.IsSystem = false; newAttribute.Order = 0; newAttribute.AttributeQualifiers.Add( new AttributeQualifier() { Key = "binaryFileType", Value = ministryFileType.Guid.ToString() } ); lookupContext.Attributes.Add( newAttribute ); lookupContext.SaveChanges(); existingAttributes.Add( newAttribute.Key, newAttribute.Id ); } newFileList.Add( new DocumentKeys() { PersonId = personKeys.PersonId, AttributeId = existingAttributes[attributeKey], File = rockFile } ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} files imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { SaveFiles( newFileList, storageProvider ); // Reset list newFileList.Clear(); ReportPartialProgress(); } } } if ( newFileList.Any() ) { SaveFiles( newFileList, storageProvider ); } ReportProgress( 100, string.Format( "Finished files import: {0:N0} addresses imported.", completed ) ); }
/// <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 ) ); }