Data access/service class for Rock.Model.Category objects.
        /// <summary>
        /// Returns a collection of active <see cref="Rock.Model.PrayerRequest">PrayerRequests</see> that
        /// are in a specified <see cref="Rock.Model.Category"/> or any of its subcategories.
        /// </summary>
        /// <param name="categoryIds">A <see cref="System.Collections.Generic.List{Int32}"/> of
        /// the <see cref="Rock.Model.Category"/> IDs to retrieve PrayerRequests for.</param>
        /// <param name="onlyApproved">set false to include un-approved requests.</param>
        /// <param name="onlyUnexpired">set false to include expired requests.</param>
        /// <returns>An enumerable collection of <see cref="Rock.Model.PrayerRequest"/> that
        /// are in the specified <see cref="Rock.Model.Category"/> or any of its subcategories.</returns>
        public IEnumerable<PrayerRequest> GetByCategoryIds( List<int> categoryIds, bool onlyApproved = true, bool onlyUnexpired = true )
        {
            PrayerRequest prayerRequest = new PrayerRequest();
            Type type = prayerRequest.GetType();

            var prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( type );

            // Get all PrayerRequest category Ids that are the **parent or child** of the given categoryIds.
            CategoryService categoryService = new CategoryService( (RockContext)Context );
            IEnumerable<int> expandedCategoryIds = categoryService.GetByEntityTypeId( prayerRequestEntityTypeId )
                .Where( c => categoryIds.Contains( c.Id ) || categoryIds.Contains( c.ParentCategoryId ?? -1 ) )
                .Select( a => a.Id );

            // Now find the active PrayerRequests that have any of those category Ids.
            var list = Queryable( "RequestedByPersonAlias.Person" ).Where( p => p.IsActive == true && expandedCategoryIds.Contains( p.CategoryId ?? -1 ) );

            if ( onlyApproved )
            {
                list = list.Where( p => p.IsApproved == true );
            }

            if ( onlyUnexpired )
            {
                list = list.Where( p => RockDateTime.Today <= p.ExpirationDate );
            }

            return list;
        }
예제 #2
0
        /// <summary>
        /// Returns Category object from cache.  If category does not already exist in cache, it
        /// will be read and added to cache
        /// </summary>
        /// <param name="id">The id of the Category to read</param>
        /// <returns></returns>
        public static CategoryCache Read(int id)
        {
            string cacheKey = CategoryCache.CacheKey(id);

            ObjectCache   cache    = MemoryCache.Default;
            CategoryCache category = cache[cacheKey] as CategoryCache;

            if (category != null)
            {
                return(category);
            }
            else
            {
                var categoryService = new Rock.Model.CategoryService();
                var categoryModel   = categoryService.Get(id);
                if (categoryModel != null)
                {
                    category = new CategoryCache(categoryModel);

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

                    return(category);
                }
                else
                {
                    return(null);
                }
            }
        }
예제 #3
0
        private static CategoryCache LoadById2(int id, RockContext rockContext)
        {
            var categoryService = new Rock.Model.CategoryService(rockContext);
            var categoryModel   = categoryService.Get(id);

            if (categoryModel != null)
            {
                return(new CategoryCache(categoryModel));
            }

            return(null);
        }
예제 #4
0
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            if ( !string.IsNullOrWhiteSpace( value ) )
            {
                var guids = value.SplitDelimitedValues();
                var categories = new CategoryService( new RockContext() ).Queryable().Where( a => guids.Contains( a.Guid.ToString() ) );
                if ( categories.Any() )
                {
                    formattedValue = string.Join( ", ", ( from category in categories select category.Name ).ToArray() );
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
예제 #5
0
        void gCategories_GridReorder( object sender, GridReorderEventArgs e )
        {
            var rockContext = new RockContext();
            var categories = GetCategories( rockContext );
            if ( categories != null )
            {
                var changedIds = new CategoryService( rockContext ).Reorder( categories.ToList(), e.OldIndex, e.NewIndex );
                rockContext.SaveChanges();

                foreach ( int id in changedIds )
                {
                    CategoryCache.Flush( id );
                }
            }

            BindGrid();
        }
예제 #6
0
        /// <summary>
        /// Maps the notes.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        public void MapNotes( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var categoryService = new CategoryService( lookupContext );
            var personService = new PersonService( lookupContext );

            var noteTypes = new NoteTypeService( lookupContext ).Queryable().AsNoTracking().ToList();
            var personalNoteType = noteTypes.FirstOrDefault( nt => nt.Guid == new Guid( Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE ) );

            var importedUsers = new UserLoginService( lookupContext ).Queryable().AsNoTracking()
                .Where( u => u.ForeignId != null )
                .ToDictionary( t => t.ForeignId, t => t.PersonId );

            var noteList = new List<Note>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying note import ({0:N0} found).", totalRows ) );
            foreach ( var row in tableData.Where( r => r != null ) )
            {
                string text = row["Note_Text"] as string;
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                var noteTypeActive = row["NoteTypeActive"] as Boolean?;

                bool noteArchived = false;
                if ( row.Columns.FirstOrDefault( v => v.Name.Equals( "IsInactive" ) ) != null )
                {
                    /* =====================================================================
                    *  the NoteArchived column *should* work, but OrcaMDF won't read it...
                    *  instead check for a manually added column: IsInactive int null
                    *       var noteActive = row["NoteArchived"] as Boolean?;
                    *       if ( noteActive == null ) throw new NullReferenceException();
                    /* ===================================================================== */
                    var rowInactiveValue = row["IsInactive"] as int?;
                    noteArchived = rowInactiveValue.Equals( 1 );
                }

                var personKeys = GetPersonKeys( individualId, householdId );
                if ( personKeys != null && !string.IsNullOrWhiteSpace( text ) && noteTypeActive == true && !noteArchived )
                {
                    DateTime? dateCreated = row["NoteCreated"] as DateTime?;
                    string noteType = row["Note_Type_Name"] as string;

                    var note = new Note();
                    note.CreatedDateTime = dateCreated;
                    note.EntityId = personKeys.PersonId;

                    // These replace methods don't like being chained together
                    text = Regex.Replace( text, @"\t|\&nbsp;", " " );
                    text = text.Replace( "&#45;", "-" );
                    text = text.Replace( "&lt;", "<" );
                    text = text.Replace( "&gt;", ">" );
                    text = text.Replace( "&amp;", "&" );
                    text = text.Replace( "&quot;", @"""" );
                    text = text.Replace( "&#x0D", string.Empty );

                    note.Text = text.Trim();

                    int? userId = row["NoteCreatedByUserID"] as int?;
                    if ( userId != null && importedUsers.ContainsKey( userId ) )
                    {
                        var userKeys = ImportedPeople.FirstOrDefault( p => p.PersonId == (int)importedUsers[userId] );
                        if ( userKeys != null )
                        {
                            note.CreatedByPersonAliasId = userKeys.PersonAliasId;
                        }
                    }

                    int? matchingNoteTypeId = null;
                    if ( !noteType.StartsWith( "General", StringComparison.InvariantCultureIgnoreCase ) )
                    {
                        matchingNoteTypeId = noteTypes.Where( nt => nt.Name == noteType ).Select( i => (int?)i.Id ).FirstOrDefault();
                    }
                    else
                    {
                        matchingNoteTypeId = personalNoteType.Id;
                    }

                    if ( matchingNoteTypeId != null )
                    {
                        note.NoteTypeId = (int)matchingNoteTypeId;
                    }
                    else
                    {
                        // create the note type
                        var newNoteType = new NoteType();
                        newNoteType.EntityTypeId = personalNoteType.EntityTypeId;
                        newNoteType.EntityTypeQualifierColumn = string.Empty;
                        newNoteType.EntityTypeQualifierValue = string.Empty;
                        newNoteType.UserSelectable = true;
                        newNoteType.IsSystem = false;
                        newNoteType.Name = noteType;
                        newNoteType.Order = 0;

                        lookupContext.NoteTypes.Add( newNoteType );
                        lookupContext.SaveChanges( DisableAuditing );

                        noteTypes.Add( newNoteType );
                        note.NoteTypeId = newNoteType.Id;
                    }

                    noteList.Add( note );
                    completed++;

                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} notes imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveNotes( noteList );
                        ReportPartialProgress();
                        noteList.Clear();
                    }
                }
            }

            if ( noteList.Any() )
            {
                SaveNotes( noteList );
            }

            ReportProgress( 100, string.Format( "Finished note import: {0:N0} notes imported.", completed ) );
        }
예제 #7
0
        /// <summary>
        /// Handles displaying the stored filter values.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e as DisplayFilterValueArgs (hint: e.Key and e.Value).</param>
        protected void gfFilter_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e )
        {
            switch ( e.Key )
            {
                case "Prayer Category":

                    int categoryId = e.Value.AsIntegerOrNull() ?? All.Id;
                    if ( categoryId == All.Id )
                    {
                        e.Value = "All";
                    }
                    else
                    {
                        var service = new CategoryService( new RockContext() );
                        var category = service.Get( categoryId );
                        if ( category != null )
                        {
                            e.Value = category.Name;
                        }
                    }

                    break;
            }
        }
 /// <summary>
 /// Handles the Click event of the btnEdit 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 btnEdit_Click( object sender, EventArgs e )
 {
     CategoryService service = new CategoryService( new RockContext() );
     Category category = service.Get( hfCategoryId.ValueAsInt() );
     ShowEditDetails( category );
 }
        /// <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 )
        {
            GroupType groupType;
            var rockContext = new RockContext();
            GroupTypeService groupTypeService = new GroupTypeService( rockContext );
            GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );
            GroupScheduleExclusionService scheduleExclusionService = new GroupScheduleExclusionService( rockContext );

            int groupTypeId = int.Parse( hfGroupTypeId.Value );

            if ( groupTypeId == 0 )
            {
                groupType = new GroupType();
                groupTypeService.Add( groupType );
            }
            else
            {
                groupType = groupTypeService.Get( groupTypeId );

                // selected roles
                var selectedRoleGuids = GroupTypeRolesState.Select( r => r.Guid );
                foreach ( var role in groupType.Roles.Where( r => !selectedRoleGuids.Contains( r.Guid ) ).ToList() )
                {
                    groupType.Roles.Remove( role );
                    groupTypeRoleService.Delete( role );
                }
            }

            foreach ( var roleState in GroupTypeRolesState )
            {
                GroupTypeRole role = groupType.Roles.Where( r => r.Guid == roleState.Guid ).FirstOrDefault();
                if ( role == null )
                {
                    role = new GroupTypeRole();
                    groupType.Roles.Add( role );
                }
                else
                {
                    roleState.Id = role.Id;
                    roleState.Guid = role.Guid;
                }

                role.CopyPropertiesFrom( roleState );
            }

            ScheduleType allowedScheduleTypes = ScheduleType.None;
            foreach( ListItem li in cblScheduleTypes.Items )
            {
                if ( li.Selected )
                {
                    allowedScheduleTypes = allowedScheduleTypes | (ScheduleType)li.Value.AsInteger();
                }
            }

            GroupLocationPickerMode locationSelectionMode = GroupLocationPickerMode.None;
            foreach ( ListItem li in cblLocationSelectionModes.Items )
            {
                if ( li.Selected )
                {
                    locationSelectionMode = locationSelectionMode | (GroupLocationPickerMode)li.Value.AsInteger();
                }
            }

            groupType.Name = tbName.Text;
            groupType.Description = tbDescription.Text;
            groupType.GroupTerm = tbGroupTerm.Text;
            groupType.GroupMemberTerm = tbGroupMemberTerm.Text;
            groupType.ShowInGroupList = cbShowInGroupList.Checked;
            groupType.ShowInNavigation = cbShowInNavigation.Checked;
            groupType.IconCssClass = tbIconCssClass.Text;
            groupType.TakesAttendance = cbTakesAttendance.Checked;
            groupType.SendAttendanceReminder = cbSendAttendanceReminder.Checked;
            groupType.AttendanceRule = ddlAttendanceRule.SelectedValueAsEnum<AttendanceRule>();
            groupType.AttendancePrintTo = ddlPrintTo.SelectedValueAsEnum<PrintTo>();
            groupType.AllowedScheduleTypes = allowedScheduleTypes;
            groupType.LocationSelectionMode = locationSelectionMode;
            groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt();
            groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked;
            groupType.InheritedGroupTypeId = gtpInheritedGroupType.SelectedGroupTypeId;
            groupType.EnableLocationSchedules = cbEnableLocationSchedules.Checked;

            groupType.ChildGroupTypes = new List<GroupType>();
            groupType.ChildGroupTypes.Clear();
            foreach ( var item in ChildGroupTypesDictionary )
            {
                var childGroupType = groupTypeService.Get( item.Key );
                if ( childGroupType != null )
                {
                    groupType.ChildGroupTypes.Add( childGroupType );
                }
            }

            // Delete any removed exclusions
            foreach ( var exclusion in groupType.GroupScheduleExclusions.Where( s => !ScheduleExclusionDictionary.Keys.Contains( s.Guid ) ).ToList() )
            {
                groupType.GroupScheduleExclusions.Remove( exclusion );
                scheduleExclusionService.Delete( exclusion );
            }

            // Update exclusions
            foreach( var keyVal in ScheduleExclusionDictionary )
            {
                var scheduleExclusion = groupType.GroupScheduleExclusions
                    .FirstOrDefault( s => s.Guid.Equals( keyVal.Key));
                if ( scheduleExclusion == null )
                {
                    scheduleExclusion = new GroupScheduleExclusion();
                    groupType.GroupScheduleExclusions.Add( scheduleExclusion);
                }

                scheduleExclusion.StartDate = keyVal.Value.Start;
                scheduleExclusion.EndDate = keyVal.Value.End;
            }

            DefinedValueService definedValueService = new DefinedValueService( rockContext );

            groupType.LocationTypes = new List<GroupTypeLocationType>();
            groupType.LocationTypes.Clear();
            foreach ( var item in LocationTypesDictionary )
            {
                var locationType = definedValueService.Get( item.Key );
                if ( locationType != null )
                {
                    groupType.LocationTypes.Add( new GroupTypeLocationType { LocationTypeValueId = locationType.Id } );
                }
            }

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

            // need WrapTransaction due to Attribute saves
            rockContext.WrapTransaction( () =>
            {
                rockContext.SaveChanges();

                /* Save Attributes */
                string qualifierValue = groupType.Id.ToString();
                SaveAttributes( new GroupType().TypeId, "Id", qualifierValue, GroupTypeAttributesState, rockContext );
                SaveAttributes( new Group().TypeId, "GroupTypeId", qualifierValue, GroupAttributesState, rockContext );
                SaveAttributes( new GroupMember().TypeId, "GroupTypeId", qualifierValue, GroupMemberAttributesState, rockContext );

                // Reload to save default role
                groupType = groupTypeService.Get( groupType.Id );
                groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault( r => r.Guid.Equals( DefaultRoleGuid ) );
                if ( groupType.DefaultGroupRole == null )
                {
                    groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault();
                }

                rockContext.SaveChanges();

                // Reload the roles and apply their attribute values
                foreach ( var role in groupTypeRoleService.GetByGroupTypeId( groupType.Id ).ToList() )
                {
                    role.LoadAttributes( rockContext );
                    var roleState = GroupTypeRolesState.Where( r => r.Guid.Equals( role.Guid ) ).FirstOrDefault();
                    if ( roleState != null && roleState.AttributeValues != null )
                    {
                        foreach ( var attributeValue in roleState.AttributeValues )
                        {
                            role.SetAttributeValue( attributeValue.Key, roleState.GetAttributeValue( attributeValue.Key ) );
                        }

                        role.SaveAttributeValues( rockContext );
                    }
                }
            } );

            GroupTypeCache.Flush( groupType.Id );

            NavigateToParentPage();
        }
예제 #10
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit( int categoryId )
        {
            Category category = null;
            if ( categoryId > 0 )
            {
                category = new CategoryService().Get( categoryId );
            }

            if ( category != null )
            {
                tbName.Text = category.Name;
                tbDescription.Text = category.Description;
                catpParentCategory.SetValue( category.ParentCategoryId );
                tbIconCssClass.Text = category.IconCssClass;
            }
            else
            {
                tbName.Text = string.Empty;
                tbDescription.Text = string.Empty;
                catpParentCategory.SetValue( _parentCategoryId );
                tbIconCssClass.Text = string.Empty;
            }

            hfIdValue.Value = categoryId.ToString();
            mdDetails.Show();
        }
예제 #11
0
        /// <summary>
        /// Handles the Delete event of the rGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGrid_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var service = new CategoryService( rockContext );

            var category = service.Get( (int)rGrid.DataKeys[e.RowIndex]["id"] );
            if ( category != null )
            {
                string errorMessage = string.Empty;
                if ( service.CanDelete( category, out errorMessage ) )
                {

                    service.Delete( category );

                    rockContext.SaveChanges();
                }
                else
                {
                    nbMessage.Text = errorMessage;
                    nbMessage.Visible = true;
                }
            }

            BindGrid();
        }
예제 #12
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 mdDetails_SaveClick( object sender, EventArgs e )
        {
            int categoryId = 0;
            if ( hfIdValue.Value != string.Empty && !int.TryParse( hfIdValue.Value, out categoryId ) )
            {
                categoryId = 0;
            }

            var service = new CategoryService();
            Category category = null;

            if ( categoryId != 0 )
            {
                category = service.Get( categoryId );
            }

            if ( category == null )
            {
                category = new Category();
                category.EntityTypeId = _entityTypeId;
                var lastCategory = GetUnorderedCategories()
                    .OrderByDescending( c => c.Order ).FirstOrDefault();
                category.Order = lastCategory != null ? lastCategory.Order + 1 : 0;

                service.Add( category, CurrentPersonId );
            }

            category.Name = tbName.Text;
            category.Description = tbDescription.Text;
            category.ParentCategoryId = catpParentCategory.SelectedValueAsInt();
            category.IconCssClass = tbIconCssClass.Text;

            List<int> orphanedBinaryFileIdList = new List<int>();
           
            if ( category.IsValid )
            {
                RockTransactionScope.WrapTransaction( () =>
                {
                    service.Save( category, CurrentPersonId );

                    BinaryFileService binaryFileService = new BinaryFileService();
                    foreach ( int binaryFileId in orphanedBinaryFileIdList )
                    {
                        var binaryFile = binaryFileService.Get( binaryFileId );
                        if ( binaryFile != null )
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            binaryFileService.Save( binaryFile, CurrentPersonId );
                        }
                    }

                } );

                hfIdValue.Value = string.Empty;
                mdDetails.Hide();

                BindGrid();
            }
        }
예제 #13
0
        private IQueryable<Category> GetUnorderedCategories()
        {
            var queryable = new CategoryService().Queryable().Where( c => c.EntityTypeId == _entityTypeId );
            if (_parentCategoryId.HasValue)
            {
                queryable = queryable.Where( c => c.ParentCategoryId == _parentCategoryId );
            }
            else
            {
                queryable = queryable.Where( c => c.ParentCategoryId == null );
            }

            return queryable;
        }
예제 #14
0
        /// <summary>
        /// Handles the Delete event of the gCategories control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gCategories_Delete( object sender, RowEventArgs e )
        {
            var service = new CategoryService();

            var category = service.Get( (int)gCategories.DataKeys[e.RowIndex]["id"] );
            if ( category != null )
            {
                string errorMessage = string.Empty;
                if ( service.CanDelete( category, out errorMessage ) )
                {

                    service.Delete( category, CurrentPersonId );
                    service.Save( category, CurrentPersonId );
                }
                else
                {
                    nbMessage.Text = errorMessage;
                    nbMessage.Visible = true;
                }
            }

            BindGrid();
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="categoryId">The category identifier.</param>
        /// <param name="parentCategoryId">The parent category id.</param>
        public void ShowDetail( int categoryId, int? parentCategoryId )
        {
            pnlDetails.Visible = false;

            var categoryService = new CategoryService( new RockContext() );
            Category category = null;

            if ( !categoryId.Equals( 0 ) )
            {
                category = categoryService.Get( categoryId );
            }

            if ( category == null )
            {
                category = new Category { Id = 0, IsSystem = false, ParentCategoryId = parentCategoryId};

                // fetch the ParentCategory (if there is one) so that security can check it
                category.ParentCategory = categoryService.Get( parentCategoryId ?? 0 );
                category.EntityTypeId = entityTypeId;
                category.EntityTypeQualifierColumn = entityTypeQualifierProperty;
                category.EntityTypeQualifierValue = entityTypeQualifierValue;
            }

            if (category.EntityTypeId != entityTypeId || !category.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
            {
                pnlDetails.Visible = false;
                return;
            }

            pnlDetails.Visible = true;
            hfCategoryId.Value = category.Id.ToString();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;

            // if the person is Authorized to EDIT the category, or has EDIT for the block
            var canEdit = category.IsAuthorized( Authorization.EDIT, CurrentPerson ) || this.IsUserAuthorized(Authorization.EDIT);
            if ( !canEdit )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Category.FriendlyTypeName );
            }

            if ( category.IsSystem )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( Category.FriendlyTypeName );
            }

            btnSecurity.Visible = category.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson );
            btnSecurity.Title = category.Name;
            btnSecurity.EntityId = category.Id;

            if ( readOnly )
            {
                btnEdit.Visible = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails( category );
            }
            else
            {
                btnEdit.Visible = true;
                string errorMessage = string.Empty;
                btnDelete.Visible = true;
                btnDelete.Enabled = categoryService.CanDelete(category, out errorMessage);
                btnDelete.ToolTip = btnDelete.Enabled ? string.Empty : errorMessage;

                if ( category.Id > 0 )
                {
                    ShowReadonlyDetails( category );
                }
                else
                {
                    ShowEditDetails( category );
                }
            }

            if ( btnDelete.Visible && btnDelete.Enabled )
            {
                btnDelete.Attributes["onclick"] = string.Format( "javascript: return Rock.dialogs.confirmDelete(event, '{0}');", Category.FriendlyTypeName.ToLower() );
            }
        }
        /// <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 )
        {
            Category category;

            var rockContext = new RockContext();
            CategoryService categoryService = new CategoryService( rockContext );

            int categoryId = hfCategoryId.ValueAsInt();

            if ( categoryId == 0 )
            {
                category = new Category();
                category.IsSystem = false;
                category.EntityTypeId = entityTypeId;
                category.EntityTypeQualifierColumn = entityTypeQualifierProperty;
                category.EntityTypeQualifierValue = entityTypeQualifierValue;
                category.Order = 0;
                categoryService.Add( category );
            }
            else
            {
                category = categoryService.Get( categoryId );
            }

            category.Name = tbName.Text;
            category.ParentCategoryId = cpParentCategory.SelectedValueAsInt();
            category.IconCssClass = tbIconCssClass.Text;
            category.HighlightColor = tbHighlightColor.Text;

            List<int> orphanedBinaryFileIdList = new List<int>();

            if ( !Page.IsValid )
            {
                return;
            }

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

            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            foreach ( int binaryFileId in orphanedBinaryFileIdList )
            {
                var binaryFile = binaryFileService.Get( binaryFileId );
                if ( binaryFile != null )
                {
                    // marked the old images as IsTemporary so they will get cleaned up later
                    binaryFile.IsTemporary = true;
                }
            }

            rockContext.SaveChanges();
            CategoryCache.Flush( category.Id );

            var qryParams = new Dictionary<string, string>();
            qryParams["CategoryId"] = category.Id.ToString();
            NavigateToPage( RockPage.Guid, qryParams );
        }
예제 #17
0
        private IQueryable<Category> GetUnorderedCategories( RockContext rockContext = null )
        {
            rockContext = rockContext ?? new RockContext();

            var queryable = new CategoryService( rockContext ).Queryable().Where( c => c.EntityTypeId == _entityTypeId );
            if (_parentCategoryId.HasValue)
            {
                queryable = queryable.Where( c => c.ParentCategoryId == _parentCategoryId );
            }
            else
            {
                queryable = queryable.Where( c => c.ParentCategoryId == null );
            }

            return queryable;
        }
예제 #18
0
        private IQueryable<Category> GetUnorderedCategories()
        {
            string selectedValue = rFilter.GetUserPreference( "EntityType" );

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

            if ( !string.IsNullOrWhiteSpace( selectedValue ) )
            {
                if ( selectedValue == "0" )
                {
                    queryable = queryable
                        .Where( c =>
                            c.EntityTypeQualifierColumn == "EntityTypeId" &&
                            c.EntityTypeQualifierValue == null );
                }
                else
                {
                    queryable = queryable
                        .Where( c =>
                            c.EntityTypeQualifierColumn == "EntityTypeId" &&
                            c.EntityTypeQualifierValue == selectedValue );
                }
            }

            return queryable;
        }
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );

            // TODO log exception if noteType is null

            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            if ( _blockInstancePrayerRequestCategoryGuid.HasValue )
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService( rockContext );

                if ( _blockInstancePrayerRequestCategoryGuid.HasValue )
                {
                    var categories = new CategoryService( rockContext ).GetAllDescendents( _blockInstancePrayerRequestCategoryGuid.Value ).Select( a => a.Id ).ToList();

                    var prayerRequestQry = new PrayerRequestService( rockContext ).Queryable().Where( a => a.CategoryId.HasValue &&
                        ( a.Category.Guid == _blockInstancePrayerRequestCategoryGuid.Value || categories.Contains( a.CategoryId.Value ) ) )
                        .Select( a => a.Id );

                    prayerComments = prayerComments.Where( a => a.EntityId.HasValue && prayerRequestQry.Contains( a.EntityId.Value ) );
                }
            }

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // Filter by Category.  First see if there is a Block Setting, otherwise use the Grid Filter
            CategoryCache categoryFilter = null;
            var blockCategoryGuid = GetAttributeValue( "PrayerRequestCategory" ).AsGuidOrNull();
            if ( blockCategoryGuid.HasValue )
            {
                categoryFilter = CategoryCache.Read( blockCategoryGuid.Value );
            }

            if ( categoryFilter == null && catpPrayerCategoryFilter.Visible )
            {
                int? filterCategoryId = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull();
                if ( filterCategoryId.HasValue )
                {
                    categoryFilter = CategoryCache.Read( filterCategoryId.Value );
                }
            }

            if ( categoryFilter != null )
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService( rockContext );
                var categories = new CategoryService( rockContext ).GetAllDescendents( categoryFilter.Guid ).Select( a => a.Id ).ToList();

                var prayerRequestQry = new PrayerRequestService( rockContext ).Queryable().Where( a => a.CategoryId.HasValue &&
                    ( a.Category.Guid == categoryFilter.Guid || categories.Contains( a.CategoryId.Value ) ) )
                    .Select( a => a.Id );

                prayerComments = prayerComments.Where( a => a.EntityId.HasValue && prayerRequestQry.Contains( a.EntityId.Value ) );
            }

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderByDescending( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
예제 #21
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit( int categoryId )
        {
            var category = new CategoryService( new RockContext() ).Get( categoryId );

            if ( category != null )
            {
                tbName.Text = category.Name;
                tbDescription.Text = category.Description;
                tbIconCssClass.Text = category.IconCssClass;
                tbHighlightColor.Text = category.HighlightColor;
            }
            else
            {
                tbName.Text = string.Empty;
                tbDescription.Text = string.Empty;
                tbIconCssClass.Text = string.Empty;
            }

            int entityTypeId = 0;
            if ( category == null || category.EntityTypeQualifierValue == null ||
                !int.TryParse( category.EntityTypeQualifierValue, out entityTypeId ) )
            {
                entityTypeId = 0;
            }

            if ( entityTypeId == 0 )
            {
                var filterValue = rFilter.GetUserPreference( "EntityType" );
                if ( !string.IsNullOrWhiteSpace( filterValue ) )
                {
                    if ( !int.TryParse( filterValue, out entityTypeId ) )
                    {
                        entityTypeId = 0;
                    }
                }
            }

            entityTypePicker.SelectedEntityTypeId = entityTypeId;

            hfIdValue.Value = categoryId.ToString();
            modalDetails.Show();
        }
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDelete_Click( object sender, EventArgs e )
        {
            int? parentCategoryId = null;

            var rockContext = new RockContext();
            var categoryService = new CategoryService( rockContext );
            var category = categoryService.Get( int.Parse( hfCategoryId.Value ) );

            if ( category != null )
            {
                string errorMessage;
                if ( !categoryService.CanDelete( category, out errorMessage ) )
                {
                    ShowReadonlyDetails( category );
                    mdDeleteWarning.Show( errorMessage, ModalAlertType.Information );
                }
                else
                {
                    parentCategoryId = category.ParentCategoryId;

                    CategoryCache.Flush( category.Id );

                    categoryService.Delete( category );
                    rockContext.SaveChanges();

                    // reload page, selecting the deleted category's parent
                    var qryParams = new Dictionary<string, string>();
                    if ( parentCategoryId != null )
                    {
                        qryParams["CategoryId"] = parentCategoryId.ToString();
                    }

                    NavigateToPage( RockPage.Guid, qryParams );
                }
            }
        }
예제 #23
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 modalDetails_SaveClick( object sender, EventArgs e )
        {
            int categoryId = 0;
            if ( hfIdValue.Value != string.Empty && !int.TryParse( hfIdValue.Value, out categoryId ) )
            {
                categoryId = 0;
            }

            var rockContext = new RockContext();
            var service = new CategoryService( rockContext );
            Category category = null;

            if ( categoryId != 0 )
            {
                CategoryCache.Flush( categoryId );
                category = service.Get( categoryId );
            }

            if ( category == null )
            {
                category = new Category();
                category.EntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id;
                category.EntityTypeQualifierColumn = "EntityTypeId";

                var lastCategory = GetUnorderedCategories()
                    .OrderByDescending( c => c.Order ).FirstOrDefault();
                category.Order = lastCategory != null ? lastCategory.Order + 1 : 0;

                service.Add( category );
            }

            category.Name = tbName.Text;
            category.Description = tbDescription.Text;

            string QualifierValue = null;
            if ( ( entityTypePicker.SelectedEntityTypeId ?? 0 ) != 0 )
            {
                QualifierValue = entityTypePicker.SelectedEntityTypeId.ToString();
            }
            category.EntityTypeQualifierValue = QualifierValue;

            category.IconCssClass = tbIconCssClass.Text;
            category.HighlightColor = tbHighlightColor.Text;

            List<int> orphanedBinaryFileIdList = new List<int>();

            if ( category.IsValid )
            {
                BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                foreach ( int binaryFileId in orphanedBinaryFileIdList )
                {
                    var binaryFile = binaryFileService.Get( binaryFileId );
                    if ( binaryFile != null )
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                    }
                }

                rockContext.SaveChanges();

                hfIdValue.Value = string.Empty;
                modalDetails.Hide();

                BindGrid();
            }
        }
        /// <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 )
        {
            var rockContext = new RockContext();
            MarketingCampaignAdType marketingCampaignAdType;

            MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService( rockContext );

            int marketingCampaignAdTypeId = int.Parse( hfMarketingCampaignAdTypeId.Value );

            if ( marketingCampaignAdTypeId == 0 )
            {
                marketingCampaignAdType = new MarketingCampaignAdType();
                marketingCampaignAdTypeService.Add( marketingCampaignAdType );
            }
            else
            {
                marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdTypeId );
            }

            marketingCampaignAdType.Name = tbName.Text;
            marketingCampaignAdType.DateRangeType = (DateRangeTypeEnum)int.Parse( ddlDateRangeType.SelectedValue );

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

            RockTransactionScope.WrapTransaction( () =>
            {
                AttributeService attributeService = new AttributeService( rockContext );
                AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );
                CategoryService categoryService = new CategoryService( rockContext );

                rockContext.SaveChanges();

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

                var entityTypeId = EntityTypeCache.Read( typeof( MarketingCampaignAd ) ).Id;
                string qualifierColumn = "MarketingCampaignAdTypeId";
                string qualifierValue = marketingCampaignAdType.Id.ToString();

                // Get the existing attributes for this entity type and qualifier value
                var attributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );

                // Delete any of those attributes that were removed in the UI
                var selectedAttributeGuids = AttributesState.Select( a => a.Guid );
                foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                {
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );

                    attributeService.Delete( attr );
                }

                rockContext.SaveChanges();

                // Update the Attributes that were assigned in the UI
                foreach ( var attributeState in AttributesState )
                {
                    Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                }

            } );

            NavigateToParentPage();
        }
        /// <summary>
        /// Binds any needed data to the Grid Filter also using the user's stored
        /// preferences.
        /// </summary>
        private void BindFilter()
        {
            drpDateRange.DelimitedValues = gfFilter.GetUserPreference( FilterSetting.DateRange );

            // Set the category picker's selected value
            int selectedPrayerCategoryId = gfFilter.GetUserPreference( FilterSetting.PrayerCategory ).AsInteger();
            Category prayerCategory = new CategoryService( new RockContext() ).Get( selectedPrayerCategoryId );
            catpPrayerCategoryFilter.SetValue( prayerCategory );

            // only show the Filter if there isn't Category set in the Block Setting
            CategoryCache blockCategory = null;
            var blockCategoryGuid = GetAttributeValue( "PrayerRequestCategory" ).AsGuidOrNull();
            if ( blockCategoryGuid.HasValue )
            {
                blockCategory = CategoryCache.Read( blockCategoryGuid.Value );
            }

            catpPrayerCategoryFilter.Visible = blockCategory == null;
        }
예제 #26
0
        /// <summary>
        /// Handles the Delete event of the gCategories control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gCategories_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var service = new CategoryService( rockContext );

            var category = service.Get( e.RowKeyId );
            if ( category != null )
            {
                string errorMessage = string.Empty;
                if ( service.CanDelete( category, out errorMessage ) )
                {
                    int categoryId = category.Id;

                    service.Delete( category );
                    rockContext.SaveChanges();

                    CategoryCache.Flush( categoryId );
                }
                else
                {
                    nbMessage.Text = errorMessage;
                    nbMessage.Visible = true;
                }
            }

            BindGrid();
        }
예제 #27
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 )
        {
            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();
        }
예제 #28
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 mdDetails_SaveClick( object sender, EventArgs e )
        {
            int categoryId = 0;
            if ( hfIdValue.Value != string.Empty && !int.TryParse( hfIdValue.Value, out categoryId ) )
            {
                categoryId = 0;
            }

            var rockContext = new RockContext();
            var service = new CategoryService( rockContext );
            Category category = null;

            if ( categoryId != 0 )
            {
                category = service.Get( categoryId );
            }

            if ( category == null )
            {
                category = new Category();
                category.EntityTypeId = _entityTypeId;
                var lastCategory = GetUnorderedCategories()
                    .OrderByDescending( c => c.Order ).FirstOrDefault();
                category.Order = lastCategory != null ? lastCategory.Order + 1 : 0;

                service.Add( category );
            }

            category.Name = tbName.Text;
            category.Description = tbDescription.Text;
            category.ParentCategoryId = catpParentCategory.SelectedValueAsInt();
            category.IconCssClass = tbIconCssClass.Text;
            category.HighlightColor = tbHighlightColor.Text;

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

            List<int> orphanedBinaryFileIdList = new List<int>();

            if ( category.IsValid )
            {
                BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                foreach ( int binaryFileId in orphanedBinaryFileIdList )
                {
                    var binaryFile = binaryFileService.Get( binaryFileId );
                    if ( binaryFile != null )
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                    }
                }

                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();
                    category.SaveAttributeValues( rockContext );
                } );

                CategoryCache.Flush( category.Id );

                hfIdValue.Value = string.Empty;
                mdDetails.Hide();

                BindGrid();
            }
        }
예제 #29
0
        private List<WorkflowNavigationCategory> GetData()
        {
            int entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.WorkflowType ) ).Id;

            var selectedCategories = new List<Guid>();
            GetAttributeValue( "Categories" ).SplitDelimitedValues().ToList().ForEach( c => selectedCategories.Add( c.AsGuid() ) );

            bool includeChildCategories = GetAttributeValue( "IncludeChildCategories" ).AsBoolean();

            var rockContext = new RockContext();
            var categories = new CategoryService( rockContext ).GetNavigationItems( entityTypeId, selectedCategories, includeChildCategories, CurrentPerson );
            var workflowTypes = new WorkflowTypeService( rockContext ).Queryable( "ActivityTypes.ActionTypes" ).ToList();
            return GetWorkflowNavigationCategories( categories, workflowTypes );
        }
예제 #30
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            if ( !Page.IsPostBack )
            {
                if ( _canConfigure )
                {
                    BindGrid();
                }
            }
            else
            {
                if ( !string.IsNullOrWhiteSpace( hfIdValue.Value ) )
                {
                    var rockContext = new RockContext();
                    Category category = new CategoryService( rockContext ).Get( hfIdValue.Value.AsInteger() );
                    if (category == null)
                    {
                        category = new Category { EntityTypeId = _entityTypeId };
                    }
                    category.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls( category, phAttributes, false, BlockValidationGroup );

                    mdDetails.Show();
                }
            }

            base.OnLoad( e );
        }
예제 #31
0
        /// <summary>
        /// Binds any needed data to the Grid Filter also using the user's stored
        /// preferences.
        /// </summary>
        private void BindFilter()
        {
            // Set the Approval Status
            var item = ddlApprovedFilter.Items.FindByValue( gfFilter.GetUserPreference( FilterSetting.ApprovalStatus ) );
            if ( item != null )
            {
                item.Selected = true;
            }

            // Set the Public Status
            var itemPublic = ddlPublicFilter.Items.FindByValue( gfFilter.GetUserPreference( FilterSetting.PublicStatus ) );
            if ( itemPublic != null )
            {
                itemPublic.Selected = true;
            }

            // Set the Commenting Status
            var itemAllowComments = ddlAllowCommentsFilter.Items.FindByValue( gfFilter.GetUserPreference( FilterSetting.CommentingStatus ) );
            if ( itemAllowComments != null )
            {
                itemAllowComments.Selected = true;
            }

            // Set the Active Status
            var itemActiveStatus = ddlActiveFilter.Items.FindByValue( gfFilter.GetUserPreference( FilterSetting.ActiveStatus ) );
            if ( itemActiveStatus != null )
            {
                itemActiveStatus.Selected = true;
            }

            // Set the Active Status
            var itemUrgentStatus = ddlUrgentFilter.Items.FindByValue( gfFilter.GetUserPreference( FilterSetting.UrgentStatus ) );
            if ( itemUrgentStatus != null )
            {
                itemUrgentStatus.Selected = true;
            }

            string fromDate = gfFilter.GetUserPreference( FilterSetting.FromDate );
            if ( !string.IsNullOrWhiteSpace( fromDate ) )
            {
                drpDateRange.LowerValue = DateTime.Parse( fromDate );
            }

            string toDate = gfFilter.GetUserPreference( FilterSetting.ToDate );
            if ( !string.IsNullOrWhiteSpace( toDate ) )
            {
                drpDateRange.UpperValue = DateTime.Parse( toDate );
            }

            // Set the category picker's selected value
            int selectedPrayerCategoryId = gfFilter.GetUserPreference( FilterSetting.PrayerCategory ).AsInteger();
            Category prayerCategory = new CategoryService( new RockContext() ).Get( selectedPrayerCategoryId );
            catpPrayerCategoryFilter.SetValue( prayerCategory );
        }
예제 #32
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit( int categoryId )
        {
            Category category = null;
            if ( categoryId > 0 )
            {
                category = new CategoryService( new RockContext() ).Get( categoryId );
            }

            if ( category == null )
            {
                category = new Category
                {
                    Id = 0,
                    EntityTypeId = _entityTypeId,
                    ParentCategoryId = _parentCategoryId,
                };
            }

            tbName.Text = category.Name;
            tbDescription.Text = category.Description;
            catpParentCategory.SetValue( category.ParentCategoryId );
            tbIconCssClass.Text = category.IconCssClass;
            tbHighlightColor.Text = category.HighlightColor;

            category.LoadAttributes();
            phAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls( category, phAttributes, true, BlockValidationGroup );

            hfIdValue.Value = categoryId.ToString();
            mdDetails.Show();
        }