/// <summary> /// Gets a list of all <see cref="Rock.Model.FieldType">FieldTypes</see> (all items that implement the <see cref="Rock.Field.IFieldType"/> interface) and registers the /// <see cref="Rock.Model.FieldType">FieldTypes</see> that have not been previously registered. /// </summary> /// <param name="physWebAppPath">A <see cref="System.String"/> representing the physical path of the web application.</param> public static void RegisterFieldTypes( string physWebAppPath ) { var fieldTypes = new Dictionary<string, EntityType>(); var rockContext = new RockContext(); var fieldTypeService = new FieldTypeService( rockContext ); var existingFieldTypes = fieldTypeService.Queryable().ToList(); foreach ( var type in Rock.Reflection.FindTypes( typeof( Rock.Field.IFieldType ) ) ) { string assemblyName = type.Value.Assembly.GetName().Name; string className = type.Value.FullName; if ( !existingFieldTypes.Where( f => f.Assembly == assemblyName && f.Class == className ).Any() ) { string fieldTypeName = type.Value.Name.SplitCase(); if (fieldTypeName.EndsWith(" Field Type")) { fieldTypeName = fieldTypeName.Substring( 0, fieldTypeName.Length - 11 ); } var fieldType = new FieldType(); fieldType.Name = fieldTypeName; fieldType.Assembly = assemblyName; fieldType.Class = className; fieldType.IsSystem = false; fieldTypeService.Add( fieldType ); } } rockContext.SaveChanges(); }
/// <summary> /// Loads the cache objects. /// </summary> private void LoadCacheObjects() { using (new Rock.Data.UnitOfWorkScope()) { // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached var qualifiers = new Dictionary <int, Dictionary <string, string> >(); foreach (var attributeQualifier in new Rock.Model.AttributeQualifierService().Queryable()) { if (!qualifiers.ContainsKey(attributeQualifier.AttributeId)) { qualifiers.Add(attributeQualifier.AttributeId, new Dictionary <string, string>()); } qualifiers[attributeQualifier.AttributeId].Add(attributeQualifier.Key, attributeQualifier.Value); } // Cache all the attributes. foreach (var attribute in new Rock.Model.AttributeService().Queryable().ToList()) { if (qualifiers.ContainsKey(attribute.Id)) { Rock.Web.Cache.AttributeCache.Read(attribute, qualifiers[attribute.Id]); } else { Rock.Web.Cache.AttributeCache.Read(attribute, new Dictionary <string, string>()); } } // Cache all the Field Types var fieldTypeService = new Rock.Model.FieldTypeService(); foreach (var fieldType in fieldTypeService.Queryable().ToList()) { fieldType.LoadAttributes(); Rock.Web.Cache.FieldTypeCache.Read(fieldType); } // DT: When running with production CCV Data, this is taking a considerable amount of time // Cache all tha Defined Types //var definedTypeService = new Rock.Model.DefinedTypeService(); //foreach ( var definedType in definedTypeService.Queryable().ToList() ) //{ // definedType.LoadAttributes(); // Rock.Web.Cache.DefinedTypeCache.Read( definedType ); //} // Cache all the Defined Values //var definedValueService = new Rock.Model.DefinedValueService(); //foreach ( var definedValue in definedValueService.Queryable().ToList() ) //{ // definedValue.LoadAttributes(); // Rock.Web.Cache.DefinedValueCache.Read( definedValue ); //} } }
/// <summary> /// Gets a list of all <see cref="Rock.Model.FieldType">FieldTypes</see> (all items that implement the <see cref="Rock.Field.IFieldType"/> interface) and registers the /// <see cref="Rock.Model.FieldType">FieldTypes</see> that have not been previously registered. /// </summary> /// <param name="physWebAppPath">A <see cref="System.String"/> representing the physical path of the web application.</param> public static void RegisterFieldTypes(string physWebAppPath) { var fieldTypes = new Dictionary <string, EntityType>(); using (var rockContext = new RockContext()) { var fieldTypeService = new FieldTypeService(rockContext); var existingFieldTypes = fieldTypeService.Queryable().ToList(); foreach (var type in Rock.Reflection.FindTypes(typeof(Rock.Field.IFieldType))) { string assemblyName = type.Value.Assembly.GetName().Name; string className = type.Value.FullName; if (!existingFieldTypes.Where(f => f.Assembly == assemblyName && f.Class == className).Any()) { string fieldTypeName = type.Value.Name.SplitCase(); if (fieldTypeName.EndsWith(" Field Type")) { fieldTypeName = fieldTypeName.Substring(0, fieldTypeName.Length - 11); } var fieldType = new FieldType(); fieldType.Name = fieldTypeName; fieldType.Assembly = assemblyName; fieldType.Class = className; fieldType.IsSystem = false; fieldTypeService.Add(fieldType); } } rockContext.SaveChanges(); } }
/// <summary> /// Loads the cache objects. /// </summary> private void LoadCacheObjects() { using ( new Rock.Data.UnitOfWorkScope() ) { // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached var qualifiers = new Dictionary<int, Dictionary<string, string>>(); foreach ( var attributeQualifier in new Rock.Model.AttributeQualifierService().Queryable() ) { if ( !qualifiers.ContainsKey( attributeQualifier.AttributeId ) ) qualifiers.Add( attributeQualifier.AttributeId, new Dictionary<string, string>() ); qualifiers[attributeQualifier.AttributeId].Add( attributeQualifier.Key, attributeQualifier.Value ); } // Cache all the attributes. foreach ( var attribute in new Rock.Model.AttributeService().Queryable().ToList() ) { if ( qualifiers.ContainsKey( attribute.Id ) ) Rock.Web.Cache.AttributeCache.Read( attribute, qualifiers[attribute.Id] ); else Rock.Web.Cache.AttributeCache.Read( attribute, new Dictionary<string, string>() ); } // Cache all the Field Types var fieldTypeService = new Rock.Model.FieldTypeService(); foreach ( var fieldType in fieldTypeService.Queryable().ToList() ) { fieldType.LoadAttributes(); Rock.Web.Cache.FieldTypeCache.Read( fieldType ); } // DT: When running with production CCV Data, this is taking a considerable amount of time // Cache all tha Defined Types //var definedTypeService = new Rock.Model.DefinedTypeService(); //foreach ( var definedType in definedTypeService.Queryable().ToList() ) //{ // definedType.LoadAttributes(); // Rock.Web.Cache.DefinedTypeCache.Read( definedType ); //} // Cache all the Defined Values //var definedValueService = new Rock.Model.DefinedValueService(); //foreach ( var definedValue in definedValueService.Queryable().ToList() ) //{ // definedValue.LoadAttributes(); // Rock.Web.Cache.DefinedValueCache.Read( definedValue ); //} } }
/// <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> /// Shows the edit. /// </summary> /// <param name="attributeId">The attribute id.</param> protected void ShowEdit( int attributeId ) { var attributeModel = new AttributeService().Get( attributeId ); if ( attributeModel != null ) { var attribute = AttributeCache.Read( attributeModel ); lActionTitle.Text = "Edit Attribute"; hfId.Value = attribute.Id.ToString(); tbKey.Text = attribute.Key; tbName.Text = attribute.Name; tbCategory.Text = attribute.Category; tbDescription.Text = attribute.Description; ddlFieldType.SelectedValue = attribute.FieldType.Id.ToString(); BuildConfigControls( attribute.QualifierValues ); tbDefaultValue.Text = attribute.DefaultValue; cbMultiValue.Checked = attribute.IsMultiValue; cbRequired.Checked = attribute.IsRequired; } else { lActionTitle.Text = "Add Attribute"; hfId.Value = string.Empty; tbKey.Text = string.Empty; tbName.Text = string.Empty; tbCategory.Text = ddlCategoryFilter.SelectedValue != "[All]" ? ddlCategoryFilter.SelectedValue : string.Empty; tbDescription.Text = string.Empty; FieldTypeService fieldTypeService = new FieldTypeService(); var fieldTypeModel = fieldTypeService.GetByName( "Text" ).FirstOrDefault(); if ( fieldTypeModel != null ) { ddlFieldType.SelectedValue = fieldTypeModel.Id.ToString(); } BuildConfigControls(); tbDefaultValue.Text = string.Empty; cbMultiValue.Checked = false; cbRequired.Checked = false; } pnlList.Visible = false; pnlDetails.Visible = true; }
/// <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> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); string entityTypeName = AttributeValue( "Entity" ); if ( string.IsNullOrWhiteSpace( entityTypeName ) ) { entityTypeName = PageParameter( "Entity" ); } _entityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( entityTypeName ); _entityQualifierColumn = AttributeValue( "EntityQualifierColumn" ); if ( string.IsNullOrWhiteSpace( _entityQualifierColumn ) ) { _entityQualifierColumn = PageParameter( "EntityQualifierColumn" ); } _entityQualifierValue = AttributeValue( "EntityQualifierValue" ); if ( string.IsNullOrWhiteSpace( _entityQualifierValue ) ) { _entityQualifierValue = PageParameter( "EntityQualifierValue" ); } _displayValueEdit = Convert.ToBoolean( AttributeValue( "SetValues" ) ); string entityIdString = AttributeValue( "EntityId" ); if ( string.IsNullOrWhiteSpace( entityIdString ) ) { entityIdString = PageParameter( "EntityId" ); } if ( !string.IsNullOrWhiteSpace( entityIdString ) ) { int entityIdint = 0; if ( int.TryParse( entityIdString, out entityIdint ) ) { _entityId = entityIdint; } } _canConfigure = CurrentPage.IsAuthorized( "Administrate", CurrentPerson ); BindFilter(); rFilter.ApplyFilterClick += rFilter_ApplyFilterClick; if ( _canConfigure ) { rGrid.DataKeyNames = new string[] { "id" }; rGrid.Actions.IsAddEnabled = true; rGrid.Actions.AddClick += rGrid_Add; rGrid.GridRebind += rGrid_GridRebind; rGrid.RowDataBound += rGrid_RowDataBound; rGrid.Columns[7].Visible = !_displayValueEdit; rGrid.Columns[8].Visible = _displayValueEdit; rGrid.Columns[9].Visible = _displayValueEdit; modalDetails.SaveClick += modalDetails_SaveClick; modalDetails.OnCancelScript = string.Format( "$('#{0}').val('');", hfIdValues.ClientID ); // Create the dropdown list for listing the available field types var fieldTypeService = new FieldTypeService(); var items = fieldTypeService. Queryable(). Select( f => new { f.Id, f.Name } ). OrderBy( f => f.Name ); ddlFieldType.AutoPostBack = true; ddlFieldType.SelectedIndexChanged += new EventHandler( ddlFieldType_SelectedIndexChanged ); ddlFieldType.Items.Clear(); foreach ( var item in items ) { ddlFieldType.Items.Add( new ListItem( item.Name, item.Id.ToString() ) ); } string editAttributeId = Request.Form[hfIdValues.UniqueID]; if ( Page.IsPostBack && editAttributeId != null && editAttributeId.Trim() != string.Empty ) { ShowEditValue( int.Parse( editAttributeId ), false ); } } else { nbMessage.Text = "You are not authorized to configure this page"; nbMessage.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 ) { 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> /// Maps the authorizations to an attribute. /// </summary> /// <param name="tableData">The table data.</param> private void MapAuthorizations( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); var rockContext = new RockContext(); var categoryService = new CategoryService( lookupContext ); var personService = new PersonService( lookupContext ); var noteList = new List<Note>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying Authorization import ({0:N0} found).", totalRows ) ); var attributeList = new AttributeService( lookupContext ).Queryable().ToList(); int authorizationAttributeId = 0; if ( attributeList.Find( a => a.Key == "PickupAuthorization" ) != null ) { authorizationAttributeId = attributeList.Find( a => a.Key == "PickupAuthorization" ).Id; } var authorizationAttributeValueList = new List<AttributeValue>(); authorizationAttributeValueList = new AttributeValueService( rockContext ).Queryable().Where( av => av.AttributeId == authorizationAttributeId ).ToList(); int f1HouseholdIdAttributeId = attributeList.Find( a => a.Key == "F1HouseholdId" ).Id; //places all household attributes in a dictionary where the key is the personId and the houshold is the value. var householdDictionary = new AttributeValueService( lookupContext ).Queryable() .Where( av => av.AttributeId == f1HouseholdIdAttributeId ) .Select( av => new { PersonId = av.EntityId, HouseholdId = av.Value } ) .ToDictionary( t => t.PersonId, t => t.HouseholdId ); foreach ( var row in tableData ) { //var rockContext = new RockContext(); var categoryList = new CategoryService( rockContext ).Queryable().ToList(); //check if category exists //If it doesn't (though it should), it will create a new category called Authorization if ( categoryList.Find( c => c.Name == "Childhood Information" ) == null ) { var entityType = new EntityTypeService( rockContext ); //creates if category doesn't exist var newCategory = new Category(); newCategory.IsSystem = false; newCategory.EntityTypeId = entityType.Queryable().Where( e => e.Name == "Rock.Model.Attribute" ).Select( e => e.Id ).FirstOrDefault(); newCategory.EntityTypeQualifierColumn = "EntityTypeId"; newCategory.EntityTypeQualifierValue = Convert.ToString( PersonEntityTypeId ); newCategory.Name = "Authorization"; newCategory.Description = "Contains the pickup authorization"; //var newCategoryContext = new RockContext(); //newCategoryContext.WrapTransaction( () => //{ // newCategoryContext.Configuration.AutoDetectChangesEnabled = false; // newCategoryContext.Categories.Add( newCategory ); // newCategoryContext.SaveChanges( DisableAudit ); //} ); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Categories.Add( newCategory ); rockContext.SaveChanges( DisableAudit ); } ); } attributeList = new AttributeService( lookupContext ).Queryable().ToList(); //Check if Attribute exists //If it doesn't it creates the attribute if ( attributeList.Find( a => a.Key == "PickupAuthorization" ) == null ) { var fieldType = new FieldTypeService( rockContext ); //var newAttributeList = new List<Rock.Model.Attribute>(); var fieldTypeId = fieldType.Queryable().Where( e => e.Name == "Memo" ).FirstOrDefault().Id; var category2 = new CategoryService( rockContext ).Queryable().Where( gt => gt.Name == "Childhood Information" ).FirstOrDefault(); var category3 = new CategoryService( rockContext ).Queryable().Where( gt => gt.Name == "Authorization" ).FirstOrDefault(); //Creates if attribute doesn't exist //The attribute is a memo attribute var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "PickupAuthorization"; newAttribute.Name = "Pickup Authorization"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Lists who is authorized to pickup this child along with their current phone number."; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; if ( categoryList.Find( c => c.Name == "Childhood Information" ) != null ) { newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); } //If authorization category was create, this is where the attribute is set to that category. else { newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category3 ); //Sets to Authorization Attribute Category. } //saves the attribute rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attributes.Add( newAttribute ); rockContext.SaveChanges( DisableAudit ); } ); } //Adding to the person's attributes int? householdId = row["HouseholdID"] as int?; string personName = row["PersonName"] as string; DateTime? authorizationDate = row["AuthorizationDate"] as DateTime?; attributeList = new AttributeService( rockContext ).Queryable().ToList(); //Gets the Attribute Id for Pickup Authorization. authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id; //since F1 authorization applies to the household id and not individual I have to apply it to all members in that household. //Value in F1 is a text entry and not a person select. Discuss with staff that we need to break away from this and start using known relationships for authorization foreach ( var household in householdDictionary.Where( h => h.Value == Convert.ToString( householdId ) ) ) { //checks if a record already exists in the list if ( authorizationAttributeValueList.Find( a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key ) == null ) { var person = new PersonService( rockContext ).Queryable().Where( p => p.Id == household.Key ).FirstOrDefault(); //trying to keep from adding this attribute to adult records if ( person != null && (person.Age <= 18 || person.Age == null) ) { //creates new attribute record if it does not exist. var newAuthorizationAttribute = new AttributeValue(); newAuthorizationAttribute.IsSystem = false; newAuthorizationAttribute.AttributeId = authorizationAttributeId; newAuthorizationAttribute.EntityId = household.Key; //the key is the person ID newAuthorizationAttribute.Value = personName + ", "; //text field newAuthorizationAttribute.CreatedDateTime = authorizationDate; //adds the new record to the list authorizationAttributeValueList.Add( newAuthorizationAttribute ); } } //if a record already exists else { //adds to the current value. authorizationAttributeValueList.Find( a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key ).Value = personName + ", "; } } completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} authorizations imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { //rockContext.WrapTransaction( () => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.AttributeValues.AddRange( authorizationAttributeValueList ); // rockContext.SaveChanges( DisableAudit ); //I get can't insert duplicate entry error // } ); ReportPartialProgress(); } } if ( authorizationAttributeValueList.Any() ) { //var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.AttributeValues.AddRange( authorizationAttributeValueList ); rockContext.SaveChanges( DisableAudit ); } ); } ReportProgress( 100, string.Format( "Finished authorization import: {0:N0} notes imported.", completed ) ); }
/// <summary> /// Maps the Giftedness Program. /// </summary> /// <param name="tableData">The table data.</param> private void MapGiftednessProgram( IQueryable<Row> tableData ) { int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying Giftedness Program import ({0:N0} found).", totalRows ) ); foreach ( var row in tableData ) { var rockContext = new RockContext(); var categoryList = new CategoryService( rockContext ).Queryable().ToList(); var attributeList = new AttributeService( rockContext ).Queryable().ToList(); var definedTypeList = new DefinedTypeService( rockContext ).Queryable().ToList(); var definedValueList = new DefinedValueService( rockContext ).Queryable().ToList(); //check if category exists string category = row["CategoryName"] as string; if ( categoryList.Find( c => c.Name == category ) == null ) { var entityType = new EntityTypeService( rockContext ); //creates if category doesn't exist var newCategory = new Category(); newCategory.IsSystem = false; newCategory.EntityTypeId = entityType.Queryable().Where( e => e.Name == "Rock.Model.Attribute" ).Select( e => e.Id ).FirstOrDefault(); newCategory.EntityTypeQualifierColumn = "EntityTypeId"; newCategory.EntityTypeQualifierValue = Convert.ToString( PersonEntityTypeId ); //Convert.ToString(entityType.Queryable().Where( e => e.Name == "Rock.Model.Person" ).Select( e => e.Id ).FirstOrDefault()); newCategory.Name = category; newCategory.Description = "Contains the spiritual gifts attributes"; //var newCategoryContext = new RockContext(); //newCategoryContext.WrapTransaction( () => //{ // newCategoryContext.Configuration.AutoDetectChangesEnabled = false; // newCategoryContext.Categories.Add( newCategory ); // newCategoryContext.SaveChanges( DisableAudit ); //} ); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Categories.Add( newCategory ); rockContext.SaveChanges( DisableAudit ); } ); } //Check if Attribute exists if ( attributeList.Find( a => a.Key == "Rank1" ) == null || attributeList.Find( a => a.Key == "Rank2" ) == null || attributeList.Find( a => a.Key == "Rank3" ) == null || attributeList.Find( a => a.Key == "Rank4" ) == null ) { var fieldType = new FieldTypeService( rockContext ); var newAttributeList = new List<Rock.Model.Attribute>(); var fieldTypeId = fieldType.Queryable().Where( e => e.Name == "Defined Value" ).FirstOrDefault().Id; var category2 = new CategoryService( rockContext ).Queryable().Where( gt => gt.Name == "Spiritual Gifts" ).FirstOrDefault(); if ( attributeList.Find( a => a.Key == "Rank1" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank1"; newAttribute.Name = "Rank 1"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 1"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( attributeList.Find( a => a.Key == "Rank2" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank2"; newAttribute.Name = "Rank 2"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 2"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( attributeList.Find( a => a.Key == "Rank3" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank3"; newAttribute.Name = "Rank 3"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 3"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( attributeList.Find( a => a.Key == "Rank4" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank4"; newAttribute.Name = "Rank 4"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 4"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( newAttributeList.Any() ) { //var newAttributeContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attributes.AddRange( newAttributeList ); rockContext.SaveChanges( DisableAudit ); newAttributeList.Clear(); } ); } } //checks if Defined Type exists if ( definedTypeList.Find( d => d.Name == "Spiritual Gifts" ) == null ) { var fieldTypeService = new FieldTypeService( rockContext ); //creates Defined Type var newDefinedType = new DefinedType(); newDefinedType.IsSystem = false; newDefinedType.FieldTypeId = fieldTypeService.Queryable().Where( f => f.Name == "Text" ).Select( f => f.Id ).FirstOrDefault(); newDefinedType.Name = "Spiritual Gifts"; newDefinedType.Description = "Defined Type for Spiritual Gifts values"; newDefinedType.CategoryId = categoryList.Find( c => c.Name == "Person" ).Id; //var newDTContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.DefinedTypes.Add( newDefinedType ); rockContext.SaveChanges( DisableAudit ); } ); } //checks if Defined Value exists var spiritualGiftsDefineType = new DefinedTypeService( rockContext ).Queryable().Where( d => d.Name == "Spiritual Gifts" ).FirstOrDefault(); string attributeName = row["AttributeName"] as string; int? giftAttributeId = row["GiftAttributeID"] as int?; if ( definedValueList.Find( d => d.DefinedTypeId == spiritualGiftsDefineType.Id && d.Value == attributeName ) == null ) { var definedTypeService = new DefinedTypeService( rockContext ); //creates Defined Value var newDefinedValue = new DefinedValue(); newDefinedValue.IsSystem = false; newDefinedValue.DefinedTypeId = definedTypeService.Queryable().Where( d => d.Name == "Spiritual Gifts" ).Select( d => d.Id ).FirstOrDefault(); newDefinedValue.Value = attributeName; newDefinedValue.Description = "Spiritual Gift attribute value: " + attributeName; newDefinedValue.ForeignId = Convert.ToString(giftAttributeId); //var newDVContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.DefinedValues.Add( newDefinedValue ); rockContext.SaveChanges( DisableAudit ); } ); } completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} spiritual gifts attributes imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { ReportPartialProgress(); } } ReportProgress( 100, string.Format( "Finished spiritual gifts import: {0:N0} spiritual gifts attributes imported.", completed ) ); }
/// <summary> /// Loads the drop downs. /// </summary> private void LoadDropDowns() { ddlDateRangeType.BindToEnum( typeof( DateRangeTypeEnum ) ); FieldTypeService fieldTypeService = new FieldTypeService(); List<FieldType> fieldTypes = fieldTypeService.Queryable().OrderBy( a => a.Name ).ToList(); ddlAttributeFieldType.DataSource = fieldTypes; ddlAttributeFieldType.DataBind(); }