EntityType POCO Service class
Beispiel #1
0
        /// <summary>
        /// Gets the specified <see cref="Rock.Model.EntityType"/> by the object type. If a match is not found, it can optionally create a new <see cref="Rock.Model.EntityType"/> for the object.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to search for.</param>
        /// <param name="createIfNotFound">A <see cref="System.Boolean"/> value that indicates if a new <see cref="Rock.Model.EntityType"/> should be created if a match is not found. This value
        /// will be <c>true</c> if a new <see cref="Rock.Model.EntityType"/> should be created if there is not a match; otherwise <c>false</c>/</param>
        /// <param name="personAlias">A <see cref="Rock.Model.PersonAlias"/> representing the alias of the <see cref="Rock.Model.Person"/> who is searching for and possibly creating a new EntityType.  This value can be
        /// null if the logged in person is not known (i.e. an anonymous user).</param>
        /// <returns>A <see cref="Rock.Model.EntityType"/> matching the provided type. If a match is not found and createIfNotFound is false this value will be null.</returns>
        public EntityType Get(Type type, bool createIfNotFound, PersonAlias personAlias)
        {
            var entityType = Get(type.FullName);

            if (entityType != null)
            {
                return(entityType);
            }

            if (createIfNotFound)
            {
                // Create a new context so type can be saved independing of current context
                using (var rockContext = new RockContext())
                {
                    var entityTypeService = new EntityTypeService(rockContext);
                    entityType              = new EntityType();
                    entityType.Name         = type.FullName;
                    entityType.FriendlyName = type.Name.SplitCase();
                    entityType.AssemblyName = type.AssemblyQualifiedName;
                    entityTypeService.Add(entityType);
                    rockContext.SaveChanges();
                }

                // Read type using current context
                return(this.Get(entityType.Id));
            }

            return(null);
        }
        /// <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 );

            // Load Entity Type Filter
            var entityTypes = new EntityTypeService().GetEntities().OrderBy( t => t.FriendlyName ).ToList();
            entityTypeFilter.EntityTypes = entityTypes;
            entityTypePicker.EntityTypes = entityTypes;

            _canConfigure = RockPage.IsAuthorized( "Administrate", CurrentPerson );

            BindFilter();
            rFilter.ApplyFilterClick += rFilter_ApplyFilterClick;

            if ( _canConfigure )
            {
                rGrid.DataKeyNames = new string[] { "id" };
                rGrid.Actions.ShowAdd = true;

                rGrid.Actions.AddClick += rGrid_Add;
                rGrid.GridReorder += rGrid_GridReorder;
                rGrid.GridRebind += rGrid_GridRebind;
                rGrid.RowDataBound += rGrid_RowDataBound;

                modalDetails.SaveClick += modalDetails_SaveClick;
                modalDetails.OnCancelScript = string.Format( "$('#{0}').val('');", hfIdValue.ClientID );
            }
            else
            {
                nbMessage.Text = "You are not authorized to configure this page";
                nbMessage.Visible = true;
            }
        }
        /// <summary>
        /// Gets the specified <see cref="Rock.Model.EntityType"/> by the object type. If a match is not found, it can optionally create a new <see cref="Rock.Model.EntityType"/> for the object.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to search for.</param>
        /// <param name="createIfNotFound">A <see cref="System.Boolean"/> value that indicates if a new <see cref="Rock.Model.EntityType"/> should be created if a match is not found. This value
        /// will be <c>true</c> if a new <see cref="Rock.Model.EntityType"/> should be created if there is not a match; otherwise <c>false</c>/</param>
        /// <param name="personAlias">A <see cref="Rock.Model.PersonAlias"/> representing the alias of the <see cref="Rock.Model.Person"/> who is searching for and possibly creating a new EntityType.  This value can be
        /// null if the logged in person is not known (i.e. an anonymous user).</param>
        /// <returns>A <see cref="Rock.Model.EntityType"/> matching the provided type. If a match is not found and createIfNotFound is false this value will be null.</returns>
        public EntityType Get( Type type, bool createIfNotFound, PersonAlias personAlias )
        {
            var entityType = Get( type.FullName );
            if ( entityType != null )
            {
                return entityType;
            }

            if ( createIfNotFound )
            {
                // Create a new context so type can be saved independing of current context
                using ( var rockContext = new RockContext() )
                {
                    var EntityTypeService = new EntityTypeService( rockContext );
                    entityType = new EntityType();
                    entityType.Name = type.FullName;
                    entityType.FriendlyName = type.Name.SplitCase();
                    entityType.AssemblyName = type.AssemblyQualifiedName;
                    EntityTypeService.Add( entityType );
                    rockContext.SaveChanges();
                }

                // Read type using current context
                return this.Get( entityType.Id );
            }

            return null;
        }
Beispiel #4
0
        /// <summary>
        /// Gets an <see cref="Rock.Model.EntityType" /> by its name. If a match is not found, a new <see cref="Rock.Model.EntityType" /> can optionally be created.
        /// </summary>
        /// <param name="name">A <see cref="System.String" /> representing the name of the object/entity type to search for.</param>
        /// <param name="createIfNotFound">A <see cref="System.Boolean" /> value that indicates if a new <see cref="Rock.Model.EntityType" /> should be created if a match is not found. This value
        /// will be <c>true</c> if a new <see cref="Rock.Model.EntityType" /> should be created if there is not a match; otherwise <c>false</c>/</param>
        /// <returns></returns>
        public EntityType GetByName(string name, bool createIfNotFound)
        {
            var entityType = Get(name);

            if (entityType != null)
            {
                return(entityType);
            }

            if (createIfNotFound)
            {
                // Create a new context so type can be saved independing of current context
                var rockContext       = new RockContext();
                var entityTypeService = new EntityTypeService(rockContext);
                entityType      = new EntityType();
                entityType.Name = name;
                entityTypeService.Add(entityType);
                rockContext.SaveChanges();

                // Read type using current context
                return(this.Get(entityType.Id));
            }

            return(null);
        }
        /// <summary>
        /// Handles the SaveClick event of the mdEdit 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 mdEdit_SaveClick( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            EntityTypeService entityTypeService = new EntityTypeService( rockContext );
            EntityType entityType = entityTypeService.Get( int.Parse( hfEntityTypeId.Value ) );

            if ( entityType == null )
            {
                entityType = new EntityType();
                entityType.IsEntity = true;
                entityType.IsSecured = true;
                entityTypeService.Add( entityType );
            }

            entityType.Name = tbName.Text;
            entityType.FriendlyName = tbFriendlyName.Text;
            entityType.IsCommon = cbCommon.Checked;

            rockContext.SaveChanges();

            EntityTypeCache.Flush( entityType.Id );

            hfEntityTypeId.Value = string.Empty;

            HideDialog();

            BindGrid();
        }
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            Stopwatch stopwatch;

            RockContext rockContext = new RockContext();

            var entityTypes = new EntityTypeService( rockContext )
                                .Queryable().AsNoTracking().ToList();

            var indexableEntityTypes = entityTypes.Where( e =>
                                            e.IsIndexingSupported == true
                                            && e.IsIndexingEnabled == true )
                                        .ToList();

            StringBuilder results = new StringBuilder();

            foreach(var entityType in indexableEntityTypes )
            {
                Type type = Type.GetType( entityType.AssemblyName );

                if ( type != null )
                {
                    object classInstance = Activator.CreateInstance( type, null );
                    MethodInfo bulkItemsMethod = type.GetMethod( "BulkIndexDocuments" );

                    if ( classInstance != null && bulkItemsMethod != null )
                    {

                        stopwatch = Stopwatch.StartNew();
                        bulkItemsMethod.Invoke( classInstance, null );
                        stopwatch.Stop();

                        results.Append( string.Format(" {0} in {1}s,", entityType.FriendlyName, stopwatch.ElapsedMilliseconds/1000 ) );
                    }
                }
            }

            context.Result = results.ToString().TrimEnd(',');
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            using ( new UnitOfWorkScope() )
            {
                BinaryFileType binaryFileType;

                BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService();
                AttributeService attributeService = new AttributeService();
                AttributeQualifierService attributeQualifierService = new AttributeQualifierService();
                CategoryService categoryService = new CategoryService();

                int binaryFileTypeId = int.Parse( hfBinaryFileTypeId.Value );

                if ( binaryFileTypeId == 0 )
                {
                    binaryFileType = new BinaryFileType();
                    binaryFileTypeService.Add( binaryFileType, CurrentPersonId );
                }
                else
                {
                    binaryFileType = binaryFileTypeService.Get( binaryFileTypeId );
                }

                binaryFileType.Name = tbName.Text;
                binaryFileType.Description = tbDescription.Text;
                binaryFileType.IconCssClass = tbIconCssClass.Text;
                binaryFileType.AllowCaching = cbAllowCaching.Checked;

                if ( !string.IsNullOrWhiteSpace( cpStorageType.SelectedValue ) )
                {
                    var entityTypeService = new EntityTypeService();
                    var storageEntityType = entityTypeService.Get( new Guid( cpStorageType.SelectedValue ) );

                    if ( storageEntityType != null )
                    {
                        binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                    }
                }

                binaryFileType.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues( phAttributes, binaryFileType );

                if ( !binaryFileType.IsValid )
                {
                    // Controls will render the error messages                    
                    return;
                }

                RockTransactionScope.WrapTransaction( () =>
                    {
                        binaryFileTypeService.Save( binaryFileType, CurrentPersonId );

                        // get it back to make sure we have a good Id for it for the Attributes
                        binaryFileType = binaryFileTypeService.Get( binaryFileType.Guid );

                        /* Take care of Binary File Attributes */
                        var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( typeof( BinaryFile ) ).Id;

                        // delete BinaryFileAttributes that are no longer configured in the UI
                        var attributes = attributeService.Get( entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString() );
                        var selectedAttributeGuids = BinaryFileAttributesState.Select( a => a.Guid );
                        foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                        {
                            Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                            attributeService.Delete( attr, CurrentPersonId );
                            attributeService.Save( attr, CurrentPersonId );
                        }

                        // add/update the BinaryFileAttributes that are assigned in the UI
                        foreach ( var attributeState in BinaryFileAttributesState )
                        {
                            Rock.Attribute.Helper.SaveAttributeEdits( attributeState, attributeService, attributeQualifierService, categoryService,
                                entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), CurrentPersonId );
                        }

                        // SaveAttributeValues for the BinaryFileType
                        Rock.Attribute.Helper.SaveAttributeValues( binaryFileType, CurrentPersonId );

                    } );
            }

            NavigateToParentPage();
        }
        /// <summary>
        /// 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 );

            if (!bool.TryParse( GetAttributeValue( "ConfigureType" ), out _configuredType))
            {
                _configuredType = true;
            }

            bool displayShowInGrid = true;
            if (bool.TryParse(GetAttributeValue("DisplayShowInGrid"), out displayShowInGrid) && displayShowInGrid)
            {
                edtAttribute.ShowInGridVisible = true;
            }
            else
            {
                edtAttribute.ShowInGridVisible = false;
            }

            Guid entityTypeGuid = Guid.Empty;
            if ( Guid.TryParse( GetAttributeValue( "Entity" ), out entityTypeGuid ) )
            {
                _entityTypeId = EntityTypeCache.Read( entityTypeGuid ).Id;
            }
            _entityQualifierColumn = GetAttributeValue( "EntityQualifierColumn" );
            _entityQualifierValue = GetAttributeValue( "EntityQualifierValue" );
            _displayValueEdit = Convert.ToBoolean( GetAttributeValue( "AllowSettingofValues" ) );

            string entityIdString = GetAttributeValue( "EntityId" );
            if ( !string.IsNullOrWhiteSpace( entityIdString ) )
            {
                int entityIdint = 0;
                if ( int.TryParse( entityIdString, out entityIdint ) && entityIdint > 0 )
                {
                    _entityId = entityIdint;
                }
            }

            _canConfigure = IsUserAuthorized( Authorization.ADMINISTRATE );

            rFilter.ApplyFilterClick += rFilter_ApplyFilterClick;

            if ( _canConfigure )
            {
                rGrid.DataKeyNames = new string[] { "id" };
                rGrid.Actions.ShowAdd = true;

                rGrid.Actions.AddClick += rGrid_Add;
                rGrid.GridRebind += rGrid_GridRebind;
                rGrid.RowDataBound += rGrid_RowDataBound;

                rGrid.Columns[1].Visible = !_configuredType;   // qualifier

                rGrid.Columns[4].Visible = !_displayValueEdit; // default value / value
                rGrid.Columns[5].Visible = _displayValueEdit; // default value / value
                rGrid.Columns[6].Visible = _displayValueEdit;  // edit

                SecurityField securityField = rGrid.Columns[7] as SecurityField;
                securityField.EntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id;

                mdAttribute.SaveClick += mdAttribute_SaveClick;
                mdAttributeValue.SaveClick += mdAttributeValue_SaveClick;

                if ( !_configuredType )
                {
                    var entityTypeList = new EntityTypeService( new RockContext() ).GetEntities().ToList();
                    ddlEntityType.EntityTypes = entityTypeList;
                    ddlAttrEntityType.EntityTypes = entityTypeList;
                }

                BindFilter();

            }
            else
            {
                nbMessage.Text = "You are not authorized to configure this page";
                nbMessage.Visible = true;
            }
        }
Beispiel #9
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns( DataView dataView )
        {
            var entityTypeService = new EntityTypeService();

            ddlEntityType.Items.Clear();
            ddlEntityType.Items.Add( new ListItem( string.Empty, string.Empty ) );
            new EntityTypeService().GetEntityListItems().ForEach( l => ddlEntityType.Items.Add( l ) );
        }
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );

            var userLogin = userLoginService.Queryable().Where( a => a.ApiKey == tbKey.Text ).FirstOrDefault();
            if ( userLogin != null && userLogin.PersonId != int.Parse( hfRestUserId.Value ) )
            {
                // this key already exists in the database. Show the error and get out of here.
                nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. ";
                nbWarningMessage.Visible = true;
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                var restUser = new Person();
                if ( int.Parse( hfRestUserId.Value ) != 0 )
                {
                    restUser = personService.Get( int.Parse( hfRestUserId.Value ) );
                }
                else
                {
                    personService.Add( restUser );
                    rockContext.SaveChanges();
                    restUser.Aliases.Add( new PersonAlias { AliasPersonId = restUser.Id, AliasPersonGuid = restUser.Guid } );
                }

                // the rest user name gets saved as the last name on a person
                History.EvaluateChange( changes, "Last Name", restUser.LastName, tbName.Text );
                restUser.LastName = tbName.Text;
                restUser.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid() ).Id;
                if ( cbActive.Checked )
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;
                }
                else
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid() ).Id;
                }

                if ( restUser.IsValid )
                {
                    if ( rockContext.SaveChanges() > 0 )
                    {
                        if ( changes.Any() )
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( Person ),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                restUser.Id,
                                changes );
                        }
                    }
                }

                // the description gets saved as a system note for the person
                var noteType = new NoteTypeService( rockContext )
                    .Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                var noteService = new NoteService( rockContext );
                var note = noteService.Get( noteType.Id, restUser.Id ).FirstOrDefault();
                if ( note == null )
                {
                    note = new Note();
                    noteService.Add( note );
                }

                note.NoteTypeId = noteType.Id;
                note.EntityId = restUser.Id;
                note.Text = tbDescription.Text;
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                var entityType = new EntityTypeService( rockContext )
                    .Get( "Rock.Security.Authentication.Database" );
                userLogin = userLoginService.GetByPersonId( restUser.Id ).FirstOrDefault();
                if ( userLogin == null )
                {
                    userLogin = new UserLogin();
                    userLoginService.Add( userLogin );
                }

                if ( string.IsNullOrWhiteSpace( userLogin.UserName ) )
                {
                    userLogin.UserName = Guid.NewGuid().ToString();
                }

                userLogin.IsConfirmed = true;
                userLogin.ApiKey = tbKey.Text;
                userLogin.PersonId = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();
            } );
            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 ) );
        }
Beispiel #12
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>
        /// Shows the edit.
        /// </summary>
        /// <param name="entityTypeId">The entity type id.</param>
        protected void ShowEdit( int entityTypeId )
        {
            EntityTypeService entityTypeService = new EntityTypeService( new RockContext() );
            EntityType entityType = entityTypeService.Get( entityTypeId );

            if ( entityType != null )
            {
                mdEdit.Title = ActionTitle.Edit( EntityType.FriendlyTypeName );
                hfEntityTypeId.Value = entityType.Id.ToString();
                tbName.Text = entityType.Name;
                tbName.Enabled = false; // !entityType.IsEntity;
                tbFriendlyName.Text = entityType.FriendlyName;
                cbCommon.Checked = entityType.IsCommon;
            }
            else
            {
                mdEdit.Title = ActionTitle.Add( EntityType.FriendlyTypeName );
                hfEntityTypeId.Value = 0.ToString();
                tbName.Text = string.Empty;
                tbName.Enabled = true;
                tbFriendlyName.Text = string.Empty;
                cbCommon.Checked = false;
            }

            ShowDialog( "Edit" );
        }
Beispiel #14
0
        /// <summary>
        /// Reads the specified GUID.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static EntityTypeCache Read( Guid guid, RockContext rockContext = null )
        {
            ObjectCache cache = MemoryCache.Default;
            object cacheObj = cache[guid.ToString()];

            EntityTypeCache entityType = null;
            if ( cacheObj != null )
            {
                entityType = Read( (int)cacheObj );
            }

            if ( entityType == null )
            {
                rockContext = rockContext ?? new RockContext();
                var entityTypeService = new EntityTypeService( rockContext );
                var entityTypeModel = entityTypeService.Get( guid );
                if ( entityTypeModel != null )
                {
                    entityType = new EntityTypeCache( entityTypeModel );

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set( EntityTypeCache.CacheKey( entityType.Id ), entityType, cachePolicy );
                    cache.Set( entityType.Guid.ToString(), entityType.Id, cachePolicy );
                }
            }

            return entityType;
        }
Beispiel #15
0
        /// <summary>
        /// Returns EntityType object from cache.  If entityBlockType does not already exist in cache, it
        /// will be read and added to cache
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static EntityTypeCache Read( int id, RockContext rockContext = null )
        {
            string cacheKey = EntityTypeCache.CacheKey( id );
            ObjectCache cache = MemoryCache.Default;
            EntityTypeCache entityType = cache[cacheKey] as EntityTypeCache;

            if ( entityType == null )
            {
                rockContext = rockContext ?? new RockContext();
                var entityTypeService = new EntityTypeService( rockContext );
                var entityTypeModel = entityTypeService.Get( id );
                if ( entityTypeModel != null )
                {
                    entityType = new EntityTypeCache( entityTypeModel );

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set( cacheKey, entityType, cachePolicy );
                    cache.Set( entityType.Guid.ToString(), entityType.Id, cachePolicy );
                }
            }

            return entityType;
        }
Beispiel #16
0
        /// <summary>
        /// Reads the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="createNew">if set to <c>true</c> [create new].</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static EntityTypeCache Read( string name, bool createNew, RockContext rockContext = null )
        {
            int? entityTypeId = null;

            lock ( obj )
            {
                if ( entityTypes.ContainsKey( name ) )
                {
                    entityTypeId = entityTypes[name];
                }
            }

            if ( entityTypeId.HasValue )
            {
                return Read( entityTypeId.Value );
            }

            var entityTypeService = new EntityTypeService( rockContext ?? new RockContext() );
            var entityTypeModel = entityTypeService.Get( name, createNew );
            if ( entityTypeModel != null )
            {
                return Read( entityTypeModel );
            }
            else
            {
                return null;
            }
        }
Beispiel #17
0
        /// <summary>
        /// Reads the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="createIfNotFound">if set to <c>true</c> [create if not found].</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static EntityTypeCache Read( Type type, bool createIfNotFound = true, RockContext rockContext = null )
        {
            int? entityTypeId = null;

            if ( type.Namespace == "System.Data.Entity.DynamicProxies" )
            {
                type = type.BaseType;
            }

            lock ( obj )
            {
                if ( entityTypes.ContainsKey( type.FullName ) )
                {
                    entityTypeId = entityTypes[type.FullName];
                }
            }

            if ( entityTypeId.HasValue )
            {
                return Read( entityTypeId.Value );
            }

            var entityTypeService = new EntityTypeService( rockContext ?? new RockContext() );
            var entityTypeModel = entityTypeService.Get( type, createIfNotFound, null );
            return Read( entityTypeModel );
        }
        /// <summary>
        /// Determines whether the specified Data View forms part of a filter.
        /// </summary>
        /// <param name="dataViewId">The unique identifier of a Data View.</param>
        /// <param name="filter">The filter.</param>
        /// <returns>
        ///   <c>true</c> if the specified Data View forms part of the conditions for the specified filter.
        /// </returns>
        public bool IsViewInFilter( int dataViewId, DataViewFilter filter )
        {
            var dataViewFilterEntityId = new EntityTypeService( (RockContext)this.Context ).Get( typeof( OtherDataViewFilter ), false, null ).Id;

            return IsViewInFilter( dataViewId, filter, dataViewFilterEntityId );
        }
Beispiel #19
0
        /// <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 );

            // if limiting by category list hide the filters
            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "CategoryFilter" ) ) )
            {
                rFilter.Visible = false;
            }

            _configuredType = GetAttributeValue( "ConfigureType" ).AsBooleanOrNull() ?? true;
            edtAttribute.ShowInGridVisible = GetAttributeValue( "EnableShowInGrid" ).AsBooleanOrNull() ?? false;

            Guid? entityTypeGuid = GetAttributeValue( "Entity" ).AsGuidOrNull();
            if ( entityTypeGuid.HasValue )
            {
                _entityTypeId = EntityTypeCache.Read( entityTypeGuid.Value ).Id;
            }

            _entityQualifierColumn = GetAttributeValue( "EntityQualifierColumn" );
            _entityQualifierValue = GetAttributeValue( "EntityQualifierValue" );
            _displayValueEdit = GetAttributeValue( "AllowSettingofValues" ).AsBooleanOrNull() ?? false;

            _entityId = GetAttributeValue( "EntityId" ).AsIntegerOrNull();
            if ( _entityId == 0 )
            {
                _entityId = null;
            }

            _canConfigure = IsUserAuthorized( Rock.Security.Authorization.ADMINISTRATE );

            _enableOrdering = GetAttributeValue( "EnableOrdering" ).AsBoolean();

            rFilter.ApplyFilterClick += rFilter_ApplyFilterClick;

            if ( _canConfigure )
            {
                rGrid.DataKeyNames = new string[] { "Id" };
                rGrid.Actions.ShowAdd = true;
                rGrid.AllowSorting = !_enableOrdering;
                rGrid.GridReorder += RGrid_GridReorder;
                rGrid.Actions.AddClick += rGrid_Add;
                rGrid.GridRebind += rGrid_GridRebind;
                rGrid.RowDataBound += rGrid_RowDataBound;

                rGrid.Columns[0].Visible = _enableOrdering;
                rGrid.Columns[2].Visible = !_configuredType;   // qualifier

                rGrid.Columns[5].Visible = !_displayValueEdit; // default value / value
                rGrid.Columns[6].Visible = _displayValueEdit; // default value / value
                rGrid.Columns[7].Visible = _displayValueEdit;  // edit

                SecurityField securityField = rGrid.Columns[8] as SecurityField;
                securityField.EntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id;

                mdAttribute.SaveClick += mdAttribute_SaveClick;
                mdAttributeValue.SaveClick += mdAttributeValue_SaveClick;

                if ( !_configuredType )
                {
                    var entityTypeList = new EntityTypeService( new RockContext() ).GetEntities().ToList();
                    ddlEntityType.EntityTypes = entityTypeList;
                    ddlAttrEntityType.EntityTypes = entityTypeList;
                }

                BindFilter();
            }
            else
            {
                nbMessage.Text = "You are not authorized to configure this page";
                nbMessage.Visible = true;
            }
        }
Beispiel #20
0
        /// <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 )
        {
            EntityTypeService entityTypeService = new EntityTypeService();
            EntityType entityType = entityTypeService.Get( int.Parse( hfEntityTypeId.Value ) );

            entityType.FriendlyName = tbFriendlyName.Text;
            entityType.IsCommon = cbCommon.Checked;

            entityTypeService.Save( entityType, CurrentPersonId );

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible = true;

            hfEntityTypeId.Value = string.Empty;
        }
Beispiel #21
0
        //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>
        /// 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();
        }
Beispiel #23
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();
        }
        /// <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 an <see cref="Rock.Model.EntityType" /> by its name. If a match is not found, a new <see cref="Rock.Model.EntityType" /> can optionally be created.
        /// </summary>
        /// <param name="name">A <see cref="System.String" /> representing the name of the object/entity type to search for.</param>
        /// <param name="createIfNotFound">A <see cref="System.Boolean" /> value that indicates if a new <see cref="Rock.Model.EntityType" /> should be created if a match is not found. This value
        /// will be <c>true</c> if a new <see cref="Rock.Model.EntityType" /> should be created if there is not a match; otherwise <c>false</c>/</param>
        /// <returns></returns>
        public EntityType Get( string name, bool createIfNotFound )
        {
            var entityType = Get( name );
            if ( entityType != null )
            {
                return entityType;
            }

            if ( createIfNotFound )
            {
                // Create a new context so type can be saved independing of current context
                var rockContext = new RockContext();
                var EntityTypeService = new EntityTypeService( rockContext );
                entityType = new EntityType();
                entityType.Name = name;
                EntityTypeService.Add( entityType );
                rockContext.SaveChanges();

                // Read type using current context
                return this.Get( entityType.Id );
            }

            return null;
        }
Beispiel #26
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="entityTypeId">The entity type id.</param>
        protected void ShowEdit( int entityTypeId )
        {
            pnlList.Visible = false;
            pnlDetails.Visible = true;

            EntityTypeService entityTypeService = new EntityTypeService();
            EntityType entityType = entityTypeService.Get( entityTypeId );

            // set edit history marker
            this.AddHistory( "edit", "", "Edit Entity Type" );

            if ( entityType != null )
            {
                lActionTitle.Text = ActionTitle.Edit( EntityType.FriendlyTypeName ).FormatAsHtmlTitle();
                hfEntityTypeId.Value = entityType.Id.ToString();
                tbName.Text = entityType.Name;
                tbFriendlyName.Text = entityType.FriendlyName;
                cbCommon.Checked = entityType.IsCommon;
            }
            else
            {
                lActionTitle.Text = ActionTitle.Add( EntityType.FriendlyTypeName ).FormatAsHtmlTitle();
                hfEntityTypeId.Value = 0.ToString();
                tbName.Text = string.Empty;
                tbFriendlyName.Text = string.Empty;
                cbCommon.Checked = false;
            }

            tbName.Enabled = !entityType.IsEntity;

        }
        private IQueryable<Category> GetUnorderedCategories( int? entityTypeId, RockContext rockContext = null )
        {
            rockContext = rockContext ?? new RockContext();

            var attributeEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id;
            var queryable = new CategoryService( rockContext ).Queryable()
                .Where( c =>
                    c.EntityTypeId == attributeEntityTypeId &&
                    c.EntityTypeQualifierColumn == "EntityTypeId" );

            if ( entityTypeId.HasValue )
            {
                var stringValue = entityTypeId.Value.ToString();
                queryable = queryable.Where( c =>
                    ( entityTypeId.Value == 0 && c.EntityTypeQualifierValue == null ) ||
                    ( entityTypeId.Value != 0 && c.EntityTypeQualifierValue != null && c.EntityTypeQualifierValue == stringValue ) );
            }
            else
            {
                // Exclude the categories for block and service job attributes, since they are controlled through code attribute decorations
                var exclusions = new List<Guid>();
                exclusions.Add( Rock.SystemGuid.EntityType.BLOCK.AsGuid() );
                exclusions.Add( Rock.SystemGuid.EntityType.SERVICE_JOB.AsGuid() );

                var entities = new EntityTypeService( rockContext ).GetEntities()
                    .Where( t => !exclusions.Contains( t.Guid ) )
                    .Select( e => e.Id )
                    .ToList()
                    .Select( e => e.ToString() )
                    .ToList();

                queryable = queryable.Where( c =>
                    c.EntityTypeQualifierValue == null ||
                    entities.Contains( c.EntityTypeQualifierValue ) );
            }

            return queryable;
        }
        /// <summary>
        /// Determines whether the specified Data View forms part of a filter.
        /// </summary>
        /// <param name="dataViewId">The unique identifier of a Data View.</param>
        /// <param name="filter">The filter.</param>
        /// <returns>
        ///   <c>true</c> if the specified Data View forms part of the conditions for the specified filter.
        /// </returns>
        public bool IsViewInFilter(int dataViewId, DataViewFilter filter)
        {
            var dataViewFilterEntityId = new EntityTypeService(( RockContext )this.Context).Get(typeof(OtherDataViewFilter), false, null).Id;

            return(IsViewInFilter(dataViewId, filter, dataViewFilterEntityId));
        }
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            // Exclude the categories for block and service job attributes, since they are controlled through code attribute decorations
            var exclusions = new List<Guid>();
            exclusions.Add( Rock.SystemGuid.EntityType.BLOCK.AsGuid() );
            exclusions.Add( Rock.SystemGuid.EntityType.SERVICE_JOB.AsGuid() );

            var rockContext = new RockContext();
            var entityTypes = new EntityTypeService( rockContext ).GetEntities()
                .Where( t => !exclusions.Contains( t.Guid ) )
                .OrderBy( t => t.FriendlyName )
                .ToList();

            entityTypePicker.EntityTypes = entityTypes;

            // Load Entity Type Filter
            var attributeEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id;
            var categoryEntities = new CategoryService( rockContext ).Queryable()
                .Where( c =>
                    c.EntityTypeId == attributeEntityTypeId &&
                    c.EntityTypeQualifierColumn == "EntityTypeId" &&
                    c.EntityTypeQualifierValue != null )
                .Select( c => c.EntityTypeQualifierValue )
                .ToList()
                .Select( c => c.AsInteger() );

            entityTypeFilter.EntityTypes = entityTypes.Where( e => categoryEntities.Contains( e.Id ) ).ToList();
            entityTypeFilter.SelectedValue = rFilter.GetUserPreference( "EntityType" );
        }
        /// <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 );
                }
            }
        }
        private IQueryable<Category> GetUnorderedCategories( RockContext rockContext = null )
        {
            rockContext = rockContext ?? new RockContext();

            string selectedValue = rFilter.GetUserPreference( "EntityType" );

            var attributeEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id;
            var queryable = new CategoryService( rockContext ).Queryable()
                .Where( c =>
                    c.EntityTypeId == attributeEntityTypeId &&
                    c.EntityTypeQualifierColumn == "EntityTypeId" );

            if ( !string.IsNullOrWhiteSpace( selectedValue ) )
            {
                if ( selectedValue == "0" )
                {
                    queryable = queryable.Where( c => c.EntityTypeQualifierValue == null );
                }
                else
                {
                    queryable = queryable.Where( c => c.EntityTypeQualifierValue == selectedValue );
                }
            }
            else
            {
                // Exclude the categories for block and service job attributes, since they are controlled through code attribute decorations
                var exclusions = new List<Guid>();
                exclusions.Add( Rock.SystemGuid.EntityType.BLOCK.AsGuid() );
                exclusions.Add( Rock.SystemGuid.EntityType.SERVICE_JOB.AsGuid() );

                var entities = new EntityTypeService( rockContext ).GetEntities()
                    .Where( t => !exclusions.Contains( t.Guid ) )
                    .Select( e => e.Id )
                    .ToList()
                    .Select( e => e.ToString() )
                    .ToList();

                queryable = queryable.Where( c => entities.Contains( c.EntityTypeQualifierValue ) );
            }

            return queryable;
        }
        /// <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 )
        {
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();
            BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );

            int binaryFileTypeId = int.Parse( hfBinaryFileTypeId.Value );

            if ( binaryFileTypeId == 0 )
            {
                binaryFileType = new BinaryFileType();
                binaryFileTypeService.Add( binaryFileType );
            }
            else
            {
                binaryFileType = binaryFileTypeService.Get( binaryFileTypeId );
            }

            binaryFileType.Name = tbName.Text;
            binaryFileType.Description = tbDescription.Text;
            binaryFileType.IconCssClass = tbIconCssClass.Text;
            binaryFileType.AllowCaching = cbAllowCaching.Checked;
            binaryFileType.RequiresViewSecurity = cbRequiresViewSecurity.Checked;
            binaryFileType.MaxWidth = nbMaxWidth.Text.AsInteger();
            binaryFileType.MaxHeight = nbMaxHeight.Text.AsInteger();
            binaryFileType.PreferredFormat = ddlPreferredFormat.SelectedValueAsEnum<Format>();
            binaryFileType.PreferredResolution = ddlPreferredResolution.SelectedValueAsEnum<Resolution>();
            binaryFileType.PreferredColorDepth = ddlPreferredColorDepth.SelectedValueAsEnum<ColorDepth>();
            binaryFileType.PreferredRequired = cbPreferredRequired.Checked;

            if ( !string.IsNullOrWhiteSpace( cpStorageType.SelectedValue ) )
            {
                var entityTypeService = new EntityTypeService( rockContext );
                var storageEntityType = entityTypeService.Get( new Guid( cpStorageType.SelectedValue ) );

                if ( storageEntityType != null )
                {
                    binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                }
            }

            binaryFileType.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributes, binaryFileType );

            if ( !binaryFileType.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                rockContext.SaveChanges();

                // get it back to make sure we have a good Id for it for the Attributes
                binaryFileType = binaryFileTypeService.Get( binaryFileType.Guid );

                /* Take care of Binary File Attributes */
                var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( typeof( BinaryFile ) ).Id;

                // delete BinaryFileAttributes that are no longer configured in the UI
                var attributes = attributeService.Get( entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString() );
                var selectedAttributeGuids = BinaryFileAttributesState.Select( a => a.Guid );
                foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                {
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                    attributeService.Delete( attr );
                }
                rockContext.SaveChanges();

                // add/update the BinaryFileAttributes that are assigned in the UI
                foreach ( var attributeState in BinaryFileAttributesState )
                {
                    Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext );
                }

                // SaveAttributeValues for the BinaryFileType
                binaryFileType.SaveAttributeValues( rockContext );

            } );

            AttributeCache.FlushEntityAttributes();

            NavigateToParentPage();
        }
Beispiel #33
0
 /// <summary>
 /// Gets the edit value as the IEntity.Id
 /// </summary>
 /// <param name="control">The control.</param>
 /// <param name="configurationValues">The configuration values.</param>
 /// <returns></returns>
 public int? GetEditValueAsEntityId( Control control, Dictionary<string, ConfigurationValue> configurationValues )
 {
     Guid guid = GetEditValue( control, configurationValues ).AsGuid();
     var item = new EntityTypeService( new RockContext() ).Get( guid );
     return item != null ? item.Id : (int?)null;
 }
Beispiel #34
0
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            string selectedEntitiesSetting = dataMap.GetString( "Entities" );

            RockContext rockContext = new RockContext();

            var selectedEntityTypes = EntityTypeCache.All().Where(e => e.IsIndexingSupported && e.IsIndexingEnabled);

            string results = string.Empty;

            if ( selectedEntitiesSetting.IsNotNullOrWhitespace() )
            {
                var selectedEntityIds = selectedEntitiesSetting.Split( ',' ).Select( int.Parse ).ToList();
                selectedEntityTypes = selectedEntityTypes.Where( e => selectedEntityIds.Contains( e.Id ) );
            }

            foreach(var entityTypeCache in selectedEntityTypes )
            {
                EntityTypeService entityTypeService = new EntityTypeService( rockContext );
                var entityType = entityTypeService.Get( entityTypeCache.Id );

                IndexContainer.DeleteIndex( entityType.IndexModelType );
                IndexContainer.CreateIndex( entityType.IndexModelType );

                Type type = entityTypeCache.GetEntityType();

                if ( type != null )
                {
                    object classInstance = Activator.CreateInstance( type, null );
                    MethodInfo bulkItemsMethod = type.GetMethod( "BulkIndexDocuments" );

                    if ( classInstance != null && bulkItemsMethod != null )
                    {
                        var timer = System.Diagnostics.Stopwatch.StartNew();
                        bulkItemsMethod.Invoke( classInstance, null );
                        timer.Stop();
                        results += $"{entityType.FriendlyName}: {timer.ElapsedMilliseconds/1000}s,";
                    }
                }
            }

            context.Result = "Indexing results: " + results.Trim( ',' );
        }
Beispiel #35
0
 /// <summary>
 /// Sets the edit value from IEntity.Id value
 /// </summary>
 /// <param name="control">The control.</param>
 /// <param name="configurationValues">The configuration values.</param>
 /// <param name="id">The identifier.</param>
 public void SetEditValueFromEntityId( Control control, Dictionary<string, ConfigurationValue> configurationValues, int? id )
 {
     var item = new EntityTypeService( new RockContext() ).Get( id ?? 0 );
     string guidValue = item != null ? item.Guid.ToString() : string.Empty;
     SetEditValue( control, configurationValues, guidValue );
 }