/// <summary>
        /// Gets a list of ISecured and IEntity entities (all models) that have not yet been registered and adds them
        /// as an <see cref="Rock.Model.EntityType"/>.
        /// </summary>
        /// <param name="physWebAppPath">A <see cref="System.String"/> that represents the physical path of the web application</param>
        public static void RegisterEntityTypes( string physWebAppPath )
        {
            var entityTypes = new Dictionary<string, EntityType>();

            foreach ( var type in Rock.Reflection.FindTypes( typeof( Rock.Data.IEntity ) ) )
            {
                var entityType = new EntityType();
                entityType.Name = type.Key;
                entityType.FriendlyName = type.Value.Name.SplitCase();
                entityType.AssemblyName = type.Value.AssemblyQualifiedName;
                entityType.IsEntity = !type.Value.GetCustomAttributes( typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute), false ).Any();
                entityType.IsSecured = false;
                entityTypes.Add( type.Key.ToLower(), entityType );
            }

            foreach ( var type in Rock.Reflection.FindTypes( typeof( Rock.Security.ISecured ) ) )
            {
                string key = type.Key.ToLower();

                if ( entityTypes.ContainsKey( key ) )
                {
                    entityTypes[key].IsSecured = true;
                }
                else
                {
                    var entityType = new EntityType();
                    entityType.Name = type.Key;
                    entityType.FriendlyName = type.Value.Name.SplitCase();
                    entityType.AssemblyName = type.Value.AssemblyQualifiedName;
                    entityType.IsEntity = false;
                    entityType.IsSecured = true;
                    entityTypes.Add( key, entityType );
                }
            }

            using ( var rockContext = new RockContext() )
            {
                var entityTypeService = new EntityTypeService( rockContext );

                // Find any existing EntityTypes marked as an entity or secured that are no longer an entity or secured
                foreach ( var oldEntityType in entityTypeService.Queryable()
                    .Where( e => e.IsEntity || e.IsSecured )
                    .ToList() )
                {
                    if ( !entityTypes.Keys.Contains( oldEntityType.Name.ToLower() ) )
                    {
                        oldEntityType.IsSecured = false;
                        oldEntityType.IsEntity = false;
                        oldEntityType.AssemblyName = null;
                        EntityTypeCache.Flush( oldEntityType.Id );
                    }
                }

                // Update any existing entities
                foreach ( var existingEntityType in entityTypeService.Queryable()
                    .Where( e => entityTypes.Keys.Contains( e.Name ) )
                    .ToList() )
                {
                    var key = existingEntityType.Name.ToLower();

                    var entityType = entityTypes[key];

                    if ( existingEntityType.Name != entityType.Name ||
                        existingEntityType.IsEntity != entityType.IsEntity ||
                        existingEntityType.IsSecured != entityType.IsSecured ||
                        existingEntityType.FriendlyName != ( existingEntityType.FriendlyName ?? entityType.FriendlyName ) ||
                        existingEntityType.AssemblyName != entityType.AssemblyName )
                    {
                        existingEntityType.Name = entityType.Name;
                        existingEntityType.IsEntity = entityType.IsEntity;
                        existingEntityType.IsSecured = entityType.IsSecured;
                        existingEntityType.FriendlyName = existingEntityType.FriendlyName ?? entityType.FriendlyName;
                        existingEntityType.AssemblyName = entityType.AssemblyName;
                        EntityTypeCache.Flush( existingEntityType.Id );
                    }
                    entityTypes.Remove( key );
                }

                // Add the newly discovered entities
                foreach ( var entityTypeInfo in entityTypes )
                {
                    // Don't add the EntityType entity as it will probably have been automatically
                    // added by the audit on a previous save in this method.
                    if ( entityTypeInfo.Value.Name != "Rock.Model.EntityType" )
                    {
                        entityTypeService.Add( entityTypeInfo.Value );
                    }
                }

                rockContext.SaveChanges();

                // make sure the EntityTypeCache is synced up with any changes that were made
                foreach (var entityTypeModel in entityTypeService.Queryable())
                {
                    EntityTypeCache.Read( entityTypeModel );
                }
            }
        }
        /// <summary>
        /// Gets a list of ISecured and IEntity entities (all models) that have not yet been registered and adds them
        /// as an <see cref="Rock.Model.EntityType"/>.
        /// </summary>
        /// <param name="physWebAppPath">A <see cref="System.String"/> that represents the physical path of the web application</param>
        public static void RegisterEntityTypes(string physWebAppPath)
        {
            var entityTypes = new Dictionary <string, EntityType>();

            foreach (var type in Rock.Reflection.FindTypes(typeof(Rock.Data.IEntity)))
            {
                var entityType = new EntityType();
                entityType.Name         = type.Key;
                entityType.FriendlyName = type.Value.Name.SplitCase();
                entityType.AssemblyName = type.Value.AssemblyQualifiedName;
                entityType.IsEntity     = !type.Value.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute), false).Any();
                entityType.IsSecured    = false;
                entityTypes.Add(type.Key.ToLower(), entityType);
            }

            foreach (var type in Rock.Reflection.FindTypes(typeof(Rock.Security.ISecured)))
            {
                string key = type.Key.ToLower();

                if (entityTypes.ContainsKey(key))
                {
                    entityTypes[key].IsSecured = true;
                }
                else
                {
                    var entityType = new EntityType();
                    entityType.Name         = type.Key;
                    entityType.FriendlyName = type.Value.Name.SplitCase();
                    entityType.AssemblyName = type.Value.AssemblyQualifiedName;
                    entityType.IsEntity     = false;
                    entityType.IsSecured    = true;
                    entityTypes.Add(key, entityType);
                }
            }

            using (var rockContext = new RockContext())
            {
                var entityTypeService = new EntityTypeService(rockContext);

                // Find any existing EntityTypes marked as an entity or secured that are no longer an entity or secured
                foreach (var oldEntityType in entityTypeService.Queryable()
                         .Where(e => e.IsEntity || e.IsSecured)
                         .ToList())
                {
                    if (!entityTypes.Keys.Contains(oldEntityType.Name.ToLower()))
                    {
                        oldEntityType.IsSecured    = false;
                        oldEntityType.IsEntity     = false;
                        oldEntityType.AssemblyName = null;
                        EntityTypeCache.Flush(oldEntityType.Id);
                    }
                }

                // Update any existing entities
                foreach (var existingEntityType in entityTypeService.Queryable()
                         .Where(e => entityTypes.Keys.Contains(e.Name))
                         .ToList())
                {
                    var key = existingEntityType.Name.ToLower();

                    var entityType = entityTypes[key];

                    if (existingEntityType.Name != entityType.Name ||
                        existingEntityType.IsEntity != entityType.IsEntity ||
                        existingEntityType.IsSecured != entityType.IsSecured ||
                        existingEntityType.FriendlyName != (existingEntityType.FriendlyName ?? entityType.FriendlyName) ||
                        existingEntityType.AssemblyName != entityType.AssemblyName)
                    {
                        existingEntityType.Name         = entityType.Name;
                        existingEntityType.IsEntity     = entityType.IsEntity;
                        existingEntityType.IsSecured    = entityType.IsSecured;
                        existingEntityType.FriendlyName = existingEntityType.FriendlyName ?? entityType.FriendlyName;
                        existingEntityType.AssemblyName = entityType.AssemblyName;
                        EntityTypeCache.Flush(existingEntityType.Id);
                    }
                    entityTypes.Remove(key);
                }

                // Add the newly discovered entities
                foreach (var entityTypeInfo in entityTypes)
                {
                    // Don't add the EntityType entity as it will probably have been automatically
                    // added by the audit on a previous save in this method.
                    if (entityTypeInfo.Value.Name != "Rock.Model.EntityType")
                    {
                        entityTypeService.Add(entityTypeInfo.Value);
                    }
                }

                rockContext.SaveChanges();

                // make sure the EntityTypeCache is synced up with any changes that were made
                foreach (var entityTypeModel in entityTypeService.Queryable())
                {
                    EntityTypeCache.Read(entityTypeModel);
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Uses Reflection to find all IEntity entities (all models), ISecured Types (could be a model or a component), and IRockBlockTypes.
        /// Then ensures that the <seealso cref="Rock.Model.EntityType" /> table is synced up to match.
        /// </summary>
        public static void RegisterEntityTypes()
        {
            List <Type> reflectedTypes = new List <Type>();

            // we'll auto-register anything that implements IEntity, ISecured or IRockBlockType
            reflectedTypes.AddRange(Rock.Reflection.FindTypes(typeof(Rock.Data.IEntity)).Values);
            reflectedTypes.AddRange(Rock.Reflection.FindTypes(typeof(Rock.Security.ISecured)).Values);
            reflectedTypes.AddRange(Rock.Reflection.FindTypes(typeof(Rock.Blocks.IRockBlockType)).Values);

            // do a distinct since some of the types implement both IEntity and ISecured
            reflectedTypes = reflectedTypes.Distinct().OrderBy(a => a.FullName).ToList();

            Dictionary <string, EntityType> entityTypesFromReflection = new Dictionary <string, EntityType>(StringComparer.OrdinalIgnoreCase);

            foreach (var reflectedType in reflectedTypes)
            {
                var entityType = new EntityType();
                entityType.Name         = reflectedType.FullName;
                entityType.FriendlyName = reflectedType.Name.SplitCase();
                entityType.AssemblyName = reflectedType.AssemblyQualifiedName;
                if (typeof(IEntity).IsAssignableFrom(reflectedType))
                {
                    entityType.IsEntity = reflectedType.GetCustomAttribute <System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute>() == null;
                }
                else
                {
                    entityType.IsEntity = false;
                }

                entityType.IsSecured = typeof(Rock.Security.ISecured).IsAssignableFrom(reflectedType);

                entityTypesFromReflection.AddOrIgnore(reflectedType.FullName, entityType);
            }
            ;

            using (var rockContext = new RockContext())
            {
                var entityTypeService = new EntityTypeService(rockContext);

                var reflectedTypeNames = reflectedTypes.Select(a => a.FullName).ToArray();

                // Get all the EntityType records from the Database without filtering them (we'll have to deal with them all)
                // Then we'll split them into a list of ones that don't exist and ones that still exist
                var entityTypeInDatabaseList = entityTypeService.Queryable().ToList();

                // Find any existing self-discovered EntityType records that no longer exist in reflectedTypes
                // but have C# narrow it down to ones that aren't in the reflectedTypeNames list
                var reflectedEntityTypesThatNoLongerExist = entityTypeInDatabaseList
                                                            .Where(e => !string.IsNullOrEmpty(e.AssemblyName))
                                                            .ToList()
                                                            .Where(e => !reflectedTypeNames.Contains(e.Name))
                                                            .OrderBy(a => a.Name)
                                                            .ToList();

                // clean up entitytypes that don't have an Assembly, but somehow have IsEntity or IsSecured set
                foreach (var entityTypesWithoutAssembliesButIsEntity in entityTypeInDatabaseList.Where(e => string.IsNullOrEmpty(e.AssemblyName) && (e.IsEntity || e.IsSecured)))
                {
                    if (entityTypesWithoutAssembliesButIsEntity.AssemblyName.IsNullOrWhiteSpace())
                    {
                        entityTypesWithoutAssembliesButIsEntity.IsEntity  = false;
                        entityTypesWithoutAssembliesButIsEntity.IsSecured = false;
                    }
                }

                foreach (var oldEntityType in reflectedEntityTypesThatNoLongerExist)
                {
                    Type foundType = null;
                    // if this isn't one of the EntityTypes that we self-register,
                    // see if it was manually registered first (with EntityTypeCache.Get(Type type, bool createIfNotExists))
                    try
                    {
                        foundType = Type.GetType(oldEntityType.AssemblyName, false);
                    }
                    catch
                    {
                        /* 2020-05-22 MDP
                         * GetType (string typeName, bool throwOnError) can throw exceptions even if throwOnError is false!
                         * see https://docs.microsoft.com/en-us/dotnet/api/system.type.gettype?view=netframework-4.5.2#System_Type_GetType_System_String_System_Boolean_
                         *
                         * so, if this happens, we'll ignore any error it returns in those cases too
                         */
                    }

                    if (foundType == null)
                    {
                        // it was manually registered but we can't create a Type from it
                        // so we'll update the EntityType.AssemblyName to null
                        // and set IsSecured and IsEntity to False (since a NULL type doesn't implement ISecured or IEntity)
                        oldEntityType.AssemblyName = null;
                        oldEntityType.IsSecured    = false;
                        oldEntityType.IsEntity     = false;
                    }
                }

                // Now get the entityType records that are still in the list of types we found thru reflection
                // but we'll have C# narrow it down to ones that aren't in the reflectedTypeNames list
                var reflectedEntityTypesThatStillExist = entityTypeInDatabaseList
                                                         .Where(e => reflectedTypeNames.Contains(e.Name))
                                                         .ToList();

                // Update any existing entities
                foreach (var existingEntityType in reflectedEntityTypesThatStillExist)
                {
                    var entityTypeFromReflection = entityTypesFromReflection.GetValueOrNull(existingEntityType.Name);
                    if (entityTypeFromReflection == null)
                    {
                        continue;
                    }

                    if (existingEntityType.Name != entityTypeFromReflection.Name ||
                        existingEntityType.IsEntity != entityTypeFromReflection.IsEntity ||
                        existingEntityType.IsSecured != entityTypeFromReflection.IsSecured ||
                        existingEntityType.FriendlyName != (existingEntityType.FriendlyName ?? entityTypeFromReflection.FriendlyName) ||
                        existingEntityType.AssemblyName != entityTypeFromReflection.AssemblyName)
                    {
                        existingEntityType.Name         = entityTypeFromReflection.Name;
                        existingEntityType.IsEntity     = entityTypeFromReflection.IsEntity;
                        existingEntityType.IsSecured    = entityTypeFromReflection.IsSecured;
                        existingEntityType.FriendlyName = existingEntityType.FriendlyName ?? entityTypeFromReflection.FriendlyName;
                        existingEntityType.AssemblyName = entityTypeFromReflection.AssemblyName;
                    }

                    entityTypesFromReflection.Remove(existingEntityType.Name);
                }

                // Add the newly discovered entities
                foreach (var entityType in entityTypesFromReflection.Values)
                {
                    // Don't add the EntityType entity as it will probably have been automatically
                    // added by the audit on a previous save in this method.
                    if (entityType.Name != "Rock.Model.EntityType")
                    {
                        entityTypeService.Add(entityType);
                    }
                }

                rockContext.SaveChanges();

                // make sure the EntityTypeCache is synced up with any changes that were made
                foreach (var entityTypeModel in entityTypeService.Queryable().AsNoTracking())
                {
                    EntityTypeCache.Get(entityTypeModel);
                }
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            EntityTypeService entityTypeService = new EntityTypeService( new RockContext() );
            SortProperty sortProperty = gEntityTypes.SortProperty;

            var qry = entityTypeService.Queryable().Where( e => e.IsSecured || e.IsEntity );

            string search = gfSettings.GetUserPreference( "Search" );
            if ( !string.IsNullOrWhiteSpace( search ) )
            {
                qry = qry.Where( h => h.Name.Contains( search ) || h.FriendlyName.Contains( search ) );
            }

            if ( sortProperty != null )
            {
                qry = qry.Sort( sortProperty );
            }
            else
            {
                qry = qry.OrderBy( p => p.Name );
            }

            gEntityTypes.DataSource = qry.ToList();
            gEntityTypes.DataBind();
        }
Exemple #5
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            EntityTypeService entityTypeService = new EntityTypeService();
            SortProperty sortProperty = gEntityTypes.SortProperty;

            if ( sortProperty != null )
            {
                gEntityTypes.DataSource = entityTypeService
                    .Queryable()
                    .Where( e => e.IsSecured || e.IsEntity )
                    .Sort( sortProperty ).ToList();
            }
            else
            {
                gEntityTypes.DataSource = entityTypeService
                    .Queryable()
                    .Where( e => e.IsSecured || e.IsEntity )
                    .OrderBy( p => p.Name ).ToList();
            }

            gEntityTypes.DataBind();
        }
        //Just mapping Connect Groups and not People Lists (Wonder if People lists could be Tags?)
        /// <summary>
        /// Maps the Connect Groups.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapGroups( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            int completedMembers = 0;
            int completedGroups = 0;
            int completedLifeStages = 0;
            int completedTags = 0;
            int completedIndividualTags = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying group import ({0:N0} found. Total may vary based on Group Type Name).", totalRows ) );

            foreach ( var row in tableData )
            {
                var rockContext = new RockContext();
                var lifeStageContext = new RockContext();
                var connectGroupContext = new RockContext();
                var connectGroupMemberContext = new RockContext();

                string groupTypeName = row["Group_Type_Name"] as string;
                if ( groupTypeName.Trim() == "Connect Groups" )            //Moves Connect Groups into Rock Groups
                {

                    var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string groupName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    //Check to see if Head of Connect Group Tree exists

                    //If it doesn't exist
                    if ( connectGroupsId == 0 )
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId = 1;
                        connectGroupTree.Name = "Connect Groups";
                        connectGroupTree.Description = "Crossroads Connect Group Ministry";
                        connectGroupTree.IsActive = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime = DateTime.Now;

                        //save group
                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Groups.Add( connectGroupTree );
                            rockContext.SaveChanges( DisableAudit );
                        } );
                    }

                    //check to see if life stage exists
                    //getting the life stage name
                    string lifeStage = groupName;
                    int index = lifeStage.IndexOf( "-" );
                    if ( index > 0 )
                        lifeStage = lifeStage.Substring( 0, index ).Trim();

                    //checks to see if it exists
                    int existingLifeStage = new GroupService( lookupContext ).Queryable().Where( g => g.Name == lifeStage ).Select( a => a.Id ).FirstOrDefault();
                    if ( existingLifeStage == 0 )
                    {
                        //Create one.
                        var connectGroupsLifeStage = new Group();
                        connectGroupsLifeStage.IsSystem = false;
                        connectGroupsLifeStage.ParentGroupId = connectGroupsId;
                        connectGroupsLifeStage.GroupTypeId = groupTypeIdSection;
                        connectGroupsLifeStage.CampusId = 1;
                        connectGroupsLifeStage.Name = lifeStage;
                        connectGroupsLifeStage.Description = "";
                        connectGroupsLifeStage.IsActive = true;
                        //connectGroupsLifeStage.Order = 0;
                        connectGroupsLifeStage.CreatedByPersonAliasId = 1;
                        connectGroupsLifeStage.CreatedDateTime = DateTime.Now;

                        //save Life Stage

                        lifeStageContext.WrapTransaction( () =>
                        {
                            lifeStageContext.Configuration.AutoDetectChangesEnabled = false;
                            lifeStageContext.Groups.Add( connectGroupsLifeStage );
                            lifeStageContext.SaveChanges( DisableAudit );
                        } );
                        completedLifeStages++;
                    }

                    int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();
                    existingLifeStage = new GroupService( lookupContext ).Queryable().Where( g => g.Name == lifeStage ).Select( a => a.Id ).FirstOrDefault();
                    //check to see if Connect Group exists.
                    if ( existingConnectGroup == 0 )
                    {
                        //Create one.
                        var connectGroups = new Group();
                        connectGroups.IsSystem = false;
                        connectGroups.GroupTypeId = groupTypeIdSmallGroup;
                        connectGroups.ParentGroupId = existingLifeStage;
                        connectGroups.CampusId = 1;
                        connectGroups.Name = groupName;
                        connectGroups.Description = "";
                        connectGroups.IsActive = true;
                        //connectGroups.Order = 0;
                        connectGroups.CreatedByPersonAliasId = 1;
                        connectGroups.CreatedDateTime = createdDateTime;
                        connectGroups.ForeignId = groupId.ToString(); //Will use this for GroupsAttendance

                        //Save Group
                        connectGroupContext.WrapTransaction( () =>
                        {
                            connectGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            connectGroupContext.Groups.Add( connectGroups );
                            connectGroupContext.SaveChanges( DisableAudit );
                        } );
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if ( existingConnectGroup != 0 )
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault();
                        int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault();
                        if ( groupMemberExists == 0 )
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem = false;
                            connectGroupMember.GroupId = existingConnectGroup;
                            connectGroupMember.PersonId = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                           // ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            connectGroupMemberContext.WrapTransaction( () =>
                            {
                                connectGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                connectGroupMemberContext.GroupMembers.Add( connectGroupMember );
                                connectGroupMemberContext.SaveChanges( DisableAudit );
                            } );
                            completedMembers++;
                        }
                    }

                    if ( completedMembers % percentage < 1 )
                    {
                        int percentComplete = completedMembers / percentage;
                        //ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if ( completedMembers % ReportingNumber < 1 )
                    {
                        ReportPartialProgress();
                    }

                }

                if ( groupTypeName.Trim() == "Care Ministries" )            //Moves Care Ministries into Rock Groups
                {

                    var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    var careMinistriesId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Care Ministries" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string groupName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if ( careMinistriesId == 0 )
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId = 1;
                        connectGroupTree.Name = "Care Ministries";
                        connectGroupTree.Description = "Crossroads Care Ministries";
                        connectGroupTree.IsActive = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime = DateTime.Now;

                        //save group
                        var careMinistryContext = new RockContext();
                        careMinistryContext.WrapTransaction( () =>
                        {
                            careMinistryContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryContext.Groups.Add( connectGroupTree );
                            careMinistryContext.SaveChanges( DisableAudit );
                        } );
                    }

                    int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();
                    int existingCareMinistries = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Care Ministries" ).Select( a => a.Id ).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if ( existingConnectGroup == 0 )
                    {
                        //Create one.
                        var careGroup = new Group();
                        careGroup.IsSystem = false;
                        careGroup.GroupTypeId = groupTypeIdSmallGroup;
                        careGroup.ParentGroupId = existingCareMinistries;
                        careGroup.CampusId = 1;
                        careGroup.Name = groupName;
                        careGroup.Description = "";
                        careGroup.IsActive = true;
                        //connectGroups.Order = 0;
                        careGroup.CreatedByPersonAliasId = 1;
                        careGroup.CreatedDateTime = createdDateTime;
                        careGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var careMinistryGroupContext = new RockContext();
                        careMinistryGroupContext.WrapTransaction( () =>
                        {
                            careMinistryGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryGroupContext.Groups.Add( careGroup );
                            careMinistryGroupContext.SaveChanges( DisableAudit );
                        } );
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if ( existingConnectGroup != 0 )
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault();
                        int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault();
                        if ( groupMemberExists == 0 )
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem = false;
                            connectGroupMember.GroupId = existingConnectGroup;
                            connectGroupMember.PersonId = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var careGroupMemberContext = new RockContext();
                            careGroupMemberContext.WrapTransaction( () =>
                            {
                                careGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                careGroupMemberContext.GroupMembers.Add( connectGroupMember );
                                careGroupMemberContext.SaveChanges( DisableAudit );
                            } );
                            completedMembers++;
                        }
                    }

                    if ( completedMembers % percentage < 1 )
                    {
                        int percentComplete = completedMembers / percentage;
                       // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if ( completedMembers % ReportingNumber < 1 )
                    {
                        ReportPartialProgress();
                    }

                }

                if ( groupTypeName.Trim() == "Intro Connect Groups" )            //Moves Intro Connect Groups into Rock Groups
                {

                    var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    var introConnectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Intro Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string groupName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if ( introConnectGroupsId == 0 )
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId = 1;
                        connectGroupTree.Name = "Intro Connect Groups";
                        connectGroupTree.Description = "Crossroads Intro Connect Groups";
                        connectGroupTree.IsActive = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime = DateTime.Now;

                        //save group
                        var introConnectGroupTreeContext = new RockContext();
                         introConnectGroupTreeContext.WrapTransaction( () =>
                        {
                            introConnectGroupTreeContext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupTreeContext.Groups.Add( connectGroupTree );
                            introConnectGroupTreeContext.SaveChanges( DisableAudit );
                        } );
                    }

                    int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();
                    int existingIntroConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Intro Connect Groups" ).Select( a => a.Id ).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if ( existingConnectGroup == 0 )
                    {
                        //Create one.
                        var introConnectGroup = new Group();
                        introConnectGroup.IsSystem = false;
                        introConnectGroup.GroupTypeId = groupTypeIdSmallGroup;
                        introConnectGroup.ParentGroupId = existingIntroConnectGroup;
                        introConnectGroup.CampusId = 1;
                        introConnectGroup.Name = groupName;
                        introConnectGroup.Description = "";
                        introConnectGroup.IsActive = true;
                        //connectGroups.Order = 0;
                        introConnectGroup.CreatedByPersonAliasId = 1;
                        introConnectGroup.CreatedDateTime = createdDateTime;
                        introConnectGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var introConnectGroupConext = new RockContext();
                        introConnectGroupConext.WrapTransaction( () =>
                        {
                            introConnectGroupConext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupConext.Groups.Add( introConnectGroup );
                            introConnectGroupConext.SaveChanges( DisableAudit );
                        } );
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if ( existingConnectGroup != 0 )
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault();
                        int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault();
                        if ( groupMemberExists == 0 )
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem = false;
                            connectGroupMember.GroupId = existingConnectGroup;
                            connectGroupMember.PersonId = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var introConnectGroupMemberConext = new RockContext();
                            introConnectGroupMemberConext.WrapTransaction( () =>
                            {
                                introConnectGroupMemberConext.Configuration.AutoDetectChangesEnabled = false;
                                introConnectGroupMemberConext.GroupMembers.Add( connectGroupMember );
                                introConnectGroupMemberConext.SaveChanges( DisableAudit );
                            } );
                            completedMembers++;
                        }
                    }

                    if ( completedMembers % percentage < 1 )
                    {
                        int percentComplete = completedMembers / percentage;
                       // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if ( completedMembers % ReportingNumber < 1 )
                    {
                        ReportPartialProgress();
                    }

                }

                if ( groupTypeName.Trim() == "People List" )    //Places People Lists in tags
                {

                    var tagService = new TagService( lookupContext );
                    var entityTypeService = new EntityTypeService( lookupContext );
                    var taggedItemService = new TaggedItemService( lookupContext );
                    var personService = new PersonService( lookupContext );

                    //var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    //var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    //var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string peopleListName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    if ( personId != null )
                    {
                        //check if tag exists
                        if ( tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault() == null )
                        {
                            //create if it doesn't
                            var newTag = new Tag();
                            newTag.IsSystem = false;
                            newTag.Name = peopleListName;
                            newTag.EntityTypeQualifierColumn = string.Empty;
                            newTag.EntityTypeQualifierValue = string.Empty;
                            newTag.EntityTypeId = entityTypeService.Queryable().Where( e => e.Name == "Rock.Model.Person" ).FirstOrDefault().Id;

                            //Save tag
                            var tagContext = new RockContext();
                            tagContext.WrapTransaction( () =>
                            {
                                tagContext.Configuration.AutoDetectChangesEnabled = false;
                                tagContext.Tags.Add( newTag );
                                tagContext.SaveChanges( DisableAudit );
                            } );

                            completedTags++;
                        }

                        var personAlias = new PersonAlias();
                        personAlias = null;

                        if ( tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault() != null ) //Makes sure tag exists
                        {
                            //selects the ID of the current people list / tag
                            int tagId = tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault().Id;

                            //gets the person instance in order to use person's GUID later.
                            var personTagged = personService.Queryable().Where( p => p.Id == personId ).FirstOrDefault();
                            if ( personTagged == null )
                            {
                                var personAliasService = new PersonAliasService(lookupContext);
                                personAlias = personAliasService.Queryable().Where( p => p.PersonId == (int)personId ).FirstOrDefault();
                                //ReportProgress( 0, string.Format( "Not able to tag person Id: {0} Tag Name: {1} F1 groupId: {2} Tag Id: {3}. ", personId, peopleListName, groupId, tagId ) );

                            }

                            //check if person already has this tag
                            if ( personTagged != null && taggedItemService.Queryable().Where( t => t.EntityGuid == personTagged.Guid && t.TagId == tagId ).FirstOrDefault() == null )
                            {

                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem = false;
                                taggedItem.TagId = tagId;
                                taggedItem.EntityGuid = personTagged.Guid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction( () =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add( taggedItem );
                                    tagContext.SaveChanges( DisableAudit );
                                } );

                                completedIndividualTags++;
                            }
                            if ( personAlias != null && taggedItemService.Queryable().Where( t => t.EntityGuid == personAlias.AliasPersonGuid && t.TagId == tagId ).FirstOrDefault() == null )
                            {

                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem = false;
                                taggedItem.TagId = tagId;
                                taggedItem.EntityGuid = personAlias.AliasPersonGuid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction( () =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add( taggedItem );
                                    tagContext.SaveChanges( DisableAudit );
                                } );

                                completedIndividualTags++;
                            }
                        }
                        //report Progress
                        if ( completedIndividualTags != 0 )
                        {
                            if ( completedIndividualTags % percentage < 1 )
                            {
                                int percentComplete = completedIndividualTags / percentage;
                               // ReportProgress( percentComplete, string.Format( "People Lists / Tags Imported: {0:N0}, Tagged Individuals: {1:N0} ({2:N0}% complete). ", completedTags, completedIndividualTags, percentComplete ) );
                            }
                            else if ( completedMembers % ReportingNumber < 1 )
                            {
                                ReportPartialProgress();
                            }
                        }
                    }
                }
            }
        }
        /// <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 ) );
        }