コード例 #1
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)
        {
            BlockType        blockType;
            BlockTypeService blockTypeService = new BlockTypeService();

            int blockTypeId = int.Parse(hfBlockTypeId.Value);

            if (blockTypeId == 0)
            {
                blockType = new BlockType();
                blockTypeService.Add(blockType, CurrentPersonId);
            }
            else
            {
                BlockTypeCache.Flush(blockTypeId);
                blockType = blockTypeService.Get(blockTypeId);
            }

            blockType.Name        = tbName.Text;
            blockType.Path        = tbPath.Text;
            blockType.Description = tbDescription.Text;

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

            blockTypeService.Save(blockType, CurrentPersonId);

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
コード例 #2
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)
        {
            BlockType        blockType;
            BlockTypeService blockTypeService = new BlockTypeService();

            int blockTypeId = int.Parse(hfBlockTypeId.Value);

            if (blockTypeId == 0)
            {
                blockType = new BlockType();
                blockTypeService.Add(blockType, CurrentPersonId);
            }
            else
            {
                BlockTypeCache.Flush(blockTypeId);
                blockType = blockTypeService.Get(blockTypeId);
            }

            blockType.Name        = tbName.Text;
            blockType.Path        = tbPath.Text;
            blockType.Description = tbDescription.Text;

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

            RockTransactionScope.WrapTransaction(() =>
            {
                blockTypeService.Save(blockType, CurrentPersonId);
            });

            NavigateToParentPage();
        }
コード例 #3
0
        /// <summary>
        /// Returns a collection of blocks for a given page and block type. This will usually be one but in some cases may be more.
        /// </summary>
        /// <param name="pageGuid">The page unique identifier.</param>
        /// <param name="blockTypeGuid">The block type unique identifier.</param>
        /// <returns></returns>
        public IQueryable <Block> GetByPageAndBlockType(Guid pageGuid, Guid blockTypeGuid)
        {
            int?pageId      = PageCache.GetId(pageGuid) ?? -1;
            int?blockTypeId = BlockTypeCache.GetId(blockTypeGuid) ?? -1;

            return(GetByPageAndBlockType(pageId.Value, blockTypeId.Value));
        }
コード例 #4
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)
        {
            BlockType        blockType;
            var              rockContext      = new RockContext();
            BlockTypeService blockTypeService = new BlockTypeService(rockContext);

            int blockTypeId = int.Parse(hfBlockTypeId.Value);

            if (blockTypeId == 0)
            {
                blockType = new BlockType();
                blockTypeService.Add(blockType);
            }
            else
            {
                BlockTypeCache.Flush(blockTypeId);
                blockType = blockTypeService.Get(blockTypeId);
            }

            blockType.Name        = tbName.Text;
            blockType.Path        = tbPath.Text;
            blockType.Description = tbDescription.Text;

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

            rockContext.SaveChanges();

            NavigateToParentPage();
        }
コード例 #5
0
        /// <summary>
        /// Gets the tabs.
        /// </summary>
        /// <param name="blockType">Type of the block.</param>
        /// <returns></returns>
        private List <string> GetTabs(BlockTypeCache blockType)
        {
            var result = new List <string> {
                "Basic Settings", "Advanced Settings"
            };

            if (this.ShowMobileOptions)
            {
                result.Insert(1, "Mobile Local Settings");
            }

            if (this.ShowCustomGridOptions || this.ShowCustomGridColumns)
            {
                result.Add("Custom Grid Options");
            }

            var customSettingTabNames = CustomSettingsProviders.Keys
                                        .Where(p => p.CustomSettingsTitle != "Basic Settings")
                                        .Where(p => p.CustomSettingsTitle != "Advanced Settings")
                                        .Select(p => p.CustomSettingsTitle);

            result.AddRange(customSettingTabNames);

            return(result);
        }
コード例 #6
0
        /// <summary>
        /// Loads the block types.
        /// </summary>
        private void LoadBlockTypes(bool registerBlockTypes)
        {
            if (registerBlockTypes)
            {
                // Add any unregistered blocks
                try
                {
                    BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page);
                }
                catch (Exception ex)
                {
                    nbMessage.Text    = "Error registering one or more block types";
                    nbMessage.Details = ex.Message + "<code>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</code>";
                    nbMessage.Visible = true;
                }
            }

            // Get a list of BlockTypes that does not include Mobile block types.
            var allExceptMobileBlockTypes = BlockTypeCache.All();

            foreach (var cachedBlockType in BlockTypeCache.All().Where(b => string.IsNullOrEmpty(b.Path)))
            {
                try
                {
                    var blockCompiledType = cachedBlockType.GetCompiledType();

                    if (typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockCompiledType))
                    {
                        allExceptMobileBlockTypes.Remove(cachedBlockType);
                    }
                }
                catch (Exception)
                {
                    // Intentionally ignored
                }
            }

            var blockTypes = allExceptMobileBlockTypes.Select(b => new { b.Id, b.Name, b.Category, b.Description }).ToList();

            ddlBlockType.Items.Clear();

            // Add the categorized block types
            foreach (var blockType in blockTypes.Where(b => b.Category != "").OrderBy(b => b.Category).ThenBy(b => b.Name))
            {
                var li = new ListItem(blockType.Name, blockType.Id.ToString());
                li.Attributes.Add("optiongroup", blockType.Category);
                li.Attributes.Add("title", blockType.Description);
                ddlBlockType.Items.Add(li);
            }

            // Add the uncategorized block types
            foreach (var blockType in blockTypes.Where(b => b.Category == null || b.Category == "").OrderBy(b => b.Name))
            {
                var li = new ListItem(blockType.Name, blockType.Id.ToString());
                li.Attributes.Add("optiongroup", "Other (not categorized)");
                li.Attributes.Add("title", blockType.Description);
                ddlBlockType.Items.Add(li);
            }
        }
コード例 #7
0
        /// <summary>
        /// Shows the detail for zone.
        /// </summary>
        /// <param name="zoneName">Name of the zone.</param>
        private void ShowDetailForZone(string zoneName)
        {
            int pageId = hfPageId.Value.AsInteger();
            var page   = PageCache.Get(pageId);

            hlInvalidZoneWarning.Visible = _invalidPageZones != null && _invalidPageZones.Contains(zoneName);

            lZoneTitle.Text = string.Format("{0} Zone", zoneName);
            lZoneIcon.Text  = "<i class='fa fa-th-large'></i>";
            if (page != null)
            {
                // Refresh ZoneList's "Count" text
                foreach (var zoneListItem in ddlZones.Items.OfType <ListItem>())
                {
                    var zoneBlockCount = page.Blocks.Where(a => a.Zone.Equals(zoneListItem.Value, StringComparison.OrdinalIgnoreCase)).Count();
                    zoneListItem.Text = string.Format("{0} ({1})", zoneListItem.Value, zoneBlockCount);
                }

                // update SiteBlock, LayoutBlock and PageBlock repeaters
                var zoneBlocks = page.Blocks.Where(a => a.Zone == zoneName).ToList();

                var blockTypes = zoneBlocks.Select(a => a.BlockType).Distinct().ToList();

                // if the blockType has changed since it IsInstancePropertiesVerified, check for updated attributes
                foreach (var blockType in blockTypes)
                {
                    if (blockType != null && !blockType.IsInstancePropertiesVerified)
                    {
                        try
                        {
                            int blockTypeId = blockType.Id;
                            using (var rockContext = new RockContext())
                            {
                                var  blockCompiledType = blockType.GetCompiledType();
                                int? blockEntityTypeId = EntityTypeCache.Get(typeof(Block)).Id;
                                bool attributesUpdated = Rock.Attribute.Helper.UpdateAttributes(blockCompiledType, blockEntityTypeId, "BlockTypeId", blockTypeId.ToString(), rockContext);
                                BlockTypeCache.Get(blockTypeId).MarkInstancePropertiesVerified(true);
                            }
                        }
                        catch
                        {
                            // ignore if it can't be compiled
                        }
                    }
                }

                rptSiteBlocks.DataSource = zoneBlocks.Where(a => a.BlockLocation == BlockLocation.Site).ToList();
                rptSiteBlocks.DataBind();

                rptLayoutBlocks.DataSource = zoneBlocks.Where(a => a.BlockLocation == BlockLocation.Layout).ToList();
                rptLayoutBlocks.DataBind();

                rptPageBlocks.DataSource = zoneBlocks.Where(a => a.BlockLocation == BlockLocation.Page).ToList();
                rptPageBlocks.DataBind();
            }
        }
コード例 #8
0
        /// <summary>
        /// Handles the Click event of the btnLoadBlockTypesAndPages 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 btnLoadBlockTypesAndPages_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            // ensure update attributes is called on every blocktype
            foreach (var blockType in new BlockTypeService(rockContext).Queryable().AsNoTracking().ToList())
            {
                System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
                var blockTypeCache = BlockTypeCache.Get(blockType.Guid);
                if (!blockTypeCache.IsInstancePropertiesVerified)
                {
                    try
                    {
                        var blockControl      = this.Page.LoadControl(blockTypeCache.Path) as RockBlock;
                        int?blockEntityTypeId = EntityTypeCache.Get(typeof(Block)).Id;
                        Rock.Attribute.Helper.UpdateAttributes(blockControl.GetType(), blockEntityTypeId, "BlockTypeId", blockType.Id.ToString(), rockContext);
                        blockTypeCache.MarkInstancePropertiesVerified(true);
                        System.Diagnostics.Debug.WriteLine(string.Format("[{1}ms] BlockType {0}", blockTypeCache.Path, stopwatch.Elapsed.TotalMilliseconds));
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex);
                    }
                }

                stopwatch.Stop();
            }

            foreach (var page in new PageService(rockContext).Queryable())
            {
                string url = string.Empty;
                try
                {
                    System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
                    var proxySafeUri = Request.UrlProxySafe();
                    url = $"{proxySafeUri.Scheme}://{WebRequestHelper.GetHostNameFromRequest( HttpContext.Current )}:{proxySafeUri.Port}{ResolveRockUrl( new PageReference( page.Id ).BuildUrl() )}";

                    //url = string.Format( "http{0}://{1}:{2}{3}",
                    //    ( Request.IsSecureConnection ) ? "s" : "",
                    //    WebRequestHelper.GetHostNameFromRequest( HttpContext.Current ),
                    //    Request.UrlProxySafe().Port,
                    //    ResolveRockUrl( new PageReference( page.Id ).BuildUrl() ) );

                    WebRequest request = WebRequest.Create(url);
                    request.Timeout = 10000;
                    WebResponse response = request.GetResponse();
                    stopwatch.Stop();
                    System.Diagnostics.Debug.WriteLine(string.Format("[{2}ms] Loaded {0} {1} ", page.InternalName, url, stopwatch.Elapsed.TotalMilliseconds));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Exception Loading {0} {1}, {2}", page.InternalName, url, ex));
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// Gets the Guid for the BlockType that has the specified Id
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public override Guid?GetGuid(int id)
        {
            var cacheItem = BlockTypeCache.Get(id);

            if (cacheItem != null)
            {
                return(cacheItem.Guid);
            }

            return(null);
        }
コード例 #10
0
        /// <summary>
        /// Handles the Click event of the btnNewBlockQuickSetting 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 btnNewBlockQuickSetting_Click(object sender, EventArgs e)
        {
            LinkButton btnNewBlockQuickSetting = sender as LinkButton;

            BlockTypeCache quickSettingBlockType = BlockTypeCache.Read(btnNewBlockQuickSetting.CommandArgument.AsInteger());

            if (quickSettingBlockType != null)
            {
                ddlBlockType.SetValue(quickSettingBlockType.Id);
                ddlBlockType_SelectedIndexChanged(sender, e);
            }
        }
コード例 #11
0
        /// <summary>
        /// Gets the tabs.
        /// </summary>
        /// <param name="blockType">Type of the block.</param>
        /// <returns></returns>
        private List <string> GetTabs(BlockTypeCache blockType)
        {
            var result = new List <string> {
                "Basic Settings", "Advanced Settings"
            };

            if (this.ShowCustomGridOptions || this.ShowCustomGridColumns)
            {
                result.Add("Custom Grid Options");
            }

            return(result);
        }
コード例 #12
0
        /// <summary>
        /// Flushes the block type attributes.
        /// </summary>
        private void FlushBlockTypeAttributes()
        {
            // Flush BlockType, Block and Entity Attributes
            AttributeCache.FlushEntityAttributes();

            BlockTypeCache.Flush(hfBlockTypeId.Value.AsInteger());
            var blockTypeCache = BlockTypeCache.Read(hfBlockTypeId.Value.AsInteger());

            foreach (var blockId in new BlockService(new RockContext()).GetByBlockTypeId(hfBlockTypeId.Value.AsInteger()).Select(a => a.Id).ToList())
            {
                BlockCache.Flush(blockId);
            }
        }
コード例 #13
0
        /// <summary>
        /// Determines whether [is block configured to allow retakes] [the specified assessment type list item].
        /// </summary>
        /// <param name="assessmentTypeListItem">The assessment type list item.</param>
        /// <returns>
        ///   <c>true</c> if [is block configured to allow retakes] [the specified assessment type list item]; otherwise, <c>false</c>.
        /// </returns>
        private bool IsBlockConfiguredToAllowRetakes(AssessmentTypeListItem assessmentTypeListItem)
        {
            string domain = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).Replace("https://", string.Empty).Replace("http://", string.Empty);
            string route  = assessmentTypeListItem.AssessmentPath.Replace("/", string.Empty);

            var rockContext      = new RockContext();
            var pageRouteService = new PageRouteService(rockContext);
            var pageId           = pageRouteService
                                   .Queryable()
                                   .Where(r => r.Route == route)
                                   .Where(r => r.Page.Layout.Site.SiteDomains.Select(d => d.Domain == domain).FirstOrDefault())
                                   .Select(r => r.PageId)
                                   .FirstOrDefault();

            Guid blockTypeGuid = Guid.Empty;

            switch (route)
            {
            case "ConflictProfile":
                blockTypeGuid = Rock.SystemGuid.BlockType.CONFLICT_PROFILE.AsGuid();
                break;

            case "EQ":
                blockTypeGuid = Rock.SystemGuid.BlockType.EQ_INVENTORY.AsGuid();
                break;

            case "Motivators":
                blockTypeGuid = Rock.SystemGuid.BlockType.MOTIVATORS.AsGuid();
                break;

            case "SpiritualGifts":
                blockTypeGuid = Rock.SystemGuid.BlockType.GIFTS_ASSESSMENT.AsGuid();
                break;

            case "DISC":
                blockTypeGuid = Rock.SystemGuid.BlockType.DISC.AsGuid();
                break;
            }

            int?blockTypeId  = BlockTypeCache.GetId(blockTypeGuid);
            var blockService = new BlockService(rockContext);
            var block        = blockTypeGuid != Guid.Empty ? blockService.GetByPageAndBlockType(pageId, blockTypeId.Value).FirstOrDefault() : null;

            if (block != null)
            {
                block.LoadAttributes();
                return(block.GetAttributeValue("AllowRetakes").AsBooleanOrNull() ?? true);
            }

            return(true);
        }
コード例 #14
0
        /// <summary>
        /// Raises the <see cref="E:Init" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            try
            {
                int?blockId = PageParameter("BlockId").AsIntegerOrNull();
                if (!blockId.HasValue)
                {
                    return;
                }

                var _block = BlockCache.Get(blockId.Value);

                Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage;
                if (dialogPage != null)
                {
                    dialogPage.OnSave  += new EventHandler <EventArgs>(masterPage_OnSave);
                    dialogPage.Title    = _block.BlockType.Name;
                    dialogPage.SubTitle = string.Format("{0} / Id: {1}", _block.BlockType.Category, blockId);
                }

                if (_block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                {
                    var blockTypeId = _block.BlockTypeId;
                    var blockType   = BlockTypeCache.Get(blockTypeId);
                    if (blockType != null && !blockType.IsInstancePropertiesVerified)
                    {
                        using (var rockContext = new RockContext())
                        {
                            var  blockCompiledType = _block.BlockType.GetCompiledType();
                            int? blockEntityTypeId = EntityTypeCache.Get(typeof(Block)).Id;
                            bool attributesUpdated = Rock.Attribute.Helper.UpdateAttributes(blockCompiledType, blockEntityTypeId, "BlockTypeId", blockTypeId.ToString(), rockContext);
                            BlockTypeCache.Get(blockTypeId).MarkInstancePropertiesVerified(true);
                        }
                    }
                }
                else
                {
                    DisplayError("You are not authorized to edit this block", null);
                }
            }
            catch (SystemException ex)
            {
                DisplayError(ex.Message, "<pre>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</pre>");
            }

            base.OnInit(e);

            LoadCustomSettingsTabs();
        }
コード例 #15
0
        /// <summary>
        /// Gets the tabs.
        /// </summary>
        /// <param name="blockType">Type of the block.</param>
        /// <returns></returns>
        private List <string> GetTabs(BlockTypeCache blockType)
        {
            var  blockControlType   = System.Web.Compilation.BuildManager.GetCompiledType(blockType.Path);
            bool customColumnsBlock = typeof(Rock.Web.UI.ICustomGridColumns).IsAssignableFrom(blockControlType);

            var result = new List <string> {
                "Basic Settings", "Advanced Settings"
            };

            if (customColumnsBlock)
            {
                result.Add("Custom Grid Columns");
            }

            return(result);
        }
コード例 #16
0
        /// <summary>
        /// Verifies the block type instance properties to make sure they are compiled and have the attributes updated,
        /// with an option to cancel the loop.
        /// </summary>
        public static void VerifyBlockTypeInstanceProperties(int[] blockTypesIdToVerify, CancellationToken cancellationToken)
        {
            if (blockTypesIdToVerify.Length == 0)
            {
                return;
            }

            foreach (int blockTypeId in blockTypesIdToVerify)
            {
                if (cancellationToken.IsCancellationRequested == true)
                {
                    return;
                }

                try
                {
                    /* 2020-09-04 MDP
                     * Notice that we call BlockTypeCache.Get every time we need data from it.
                     * We do this because the BlockTypeCache get easily get stale due to other threads.
                     */

                    if (BlockTypeCache.Get(blockTypeId)?.IsInstancePropertiesVerified == false)
                    {
                        // make sure that only one thread is trying to compile block types and attributes so that we don't get collisions and unneeded compiler overhead
                        lock ( VerifyBlockTypeInstancePropertiesLockObj )
                        {
                            if (BlockTypeCache.Get(blockTypeId)?.IsInstancePropertiesVerified == false)
                            {
                                using (var rockContext = new RockContext())
                                {
                                    var  blockTypeCache    = BlockTypeCache.Get(blockTypeId);
                                    Type blockCompiledType = blockTypeCache.GetCompiledType();

                                    bool attributesUpdated = RockBlock.CreateAttributes(rockContext, blockCompiledType, blockTypeId);
                                    BlockTypeCache.Get(blockTypeId)?.MarkInstancePropertiesVerified(true);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // ignore if the block couldn't be compiled, it'll get logged and shown when the page tries to load the block into the page
                    Debug.WriteLine(ex);
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Binds the block type repeater.
        /// </summary>
        private void BindBlockTypeRepeater()
        {
            var items = new List <ComponentItem>();

            //
            // Find all mobile block types and build the component repeater.
            //
            var blockTypes = BlockTypeCache.All()
                             .Where(t => t.Category == ddlBlockTypeCategory.SelectedValue)
                             .OrderBy(t => t.Name);

            foreach (var blockType in blockTypes)
            {
                try
                {
                    var blockCompiledType = blockType.GetCompiledType();

                    if (!typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockCompiledType))
                    {
                        continue;
                    }

                    var iconCssClassAttribute = ( IconCssClassAttribute )blockCompiledType.GetCustomAttribute(typeof(IconCssClassAttribute));

                    var item = new ComponentItem
                    {
                        IconCssClass = iconCssClassAttribute != null ? iconCssClassAttribute.IconCssClass : "fa fa-question",
                        Name         = blockType.Name,
                        Id           = blockType.Id
                    };

                    items.Add(item);
                }
                catch
                {
                    /* Intentionally ignored. */
                }
            }

            ComponentItemState        = items;
            rptrBlockTypes.DataSource = ComponentItemState;
            rptrBlockTypes.DataBind();
        }
コード例 #18
0
        /// <summary>
        /// Gets the block type attributes that are defined in code in the blocktype
        /// </summary>
        /// <returns></returns>
        private List <string> GetBlockTypeStaticAttributeKeys()
        {
            var blockTypeCache = BlockTypeCache.Read(hfBlockTypeId.Value.AsInteger());
            List <FieldAttribute> blockProperties = new List <FieldAttribute>();;

            try
            {
                var blockControlType = System.Web.Compilation.BuildManager.GetCompiledType(blockTypeCache.Path);

                foreach (var customAttribute in blockControlType.GetCustomAttributes(typeof(FieldAttribute), true))
                {
                    blockProperties.Add((FieldAttribute)customAttribute);
                }
            }
            catch
            {
                // ignore if the block can't compile
            }

            var blockStaticAttributeKeys = blockProperties.Select(a => a.Key).ToList();

            return(blockStaticAttributeKeys);
        }
コード例 #19
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            int    entityTypeIdBlock   = EntityTypeCache.Read(typeof(Rock.Model.Block), true, rockContext).Id;
            string entityTypeQualifier = BlockTypeCache.Read(Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid(), rockContext).Id.ToString();
            var    htmlContentService  = new HtmlContentService(rockContext);
            var    attributeValueQry   = new AttributeValueService(rockContext).Queryable()
                                         .Where(a => a.Attribute.Key == "RequireApproval" && a.Attribute.EntityTypeId == entityTypeIdBlock)
                                         .Where(a => a.Attribute.EntityTypeQualifierColumn == "BlockTypeId" && a.Attribute.EntityTypeQualifierValue == entityTypeQualifier)
                                         .Where(a => a.Value == "True")
                                         .Select(a => a.EntityId);

            var qry = htmlContentService.Queryable().Where(a => attributeValueQry.Contains(a.BlockId));

            // Filter by approved/unapproved
            if (ddlApprovedFilter.SelectedIndex > -1)
            {
                if (ddlApprovedFilter.SelectedValue.ToLower() == "unapproved")
                {
                    qry = qry.Where(a => a.IsApproved == false);
                }
                else if (ddlApprovedFilter.SelectedValue.ToLower() == "approved")
                {
                    qry = qry.Where(a => a.IsApproved == true);
                }
            }

            // Filter by the person that approved the content
            if (_canApprove)
            {
                int?personId = gContentListFilter.GetUserPreference("Approved By").AsIntegerOrNull();
                if (personId.HasValue)
                {
                    qry = qry.Where(a => a.ApprovedByPersonAliasId.HasValue && a.ApprovedByPersonAlias.PersonId == personId);
                }
            }

            SortProperty sortProperty = gContentList.SortProperty;

            if (sortProperty != null)
            {
                qry = qry.Sort(sortProperty);
            }
            else
            {
                qry = qry.OrderByDescending(a => a.ModifiedDateTime);
            }

            var selectQry = qry.Select(a => new
            {
                a.Id,
                SiteName = a.Block.PageId.HasValue ? a.Block.Page.Layout.Site.Name : a.Block.Layout.Site.Name,
                PageName = a.Block.Page.InternalName,
                a.ModifiedDateTime,
                a.IsApproved,
                ApprovedDateTime = a.IsApproved ? a.ApprovedDateTime : null,
                ApprovedByPerson = a.IsApproved ? a.ApprovedByPersonAlias.Person : null,
                BlockPageId      = a.Block.PageId,
                BlockLayoutId    = a.Block.LayoutId,
            });

            // Filter by Site
            if (ddlSiteFilter.SelectedIndex > 0)
            {
                if (ddlSiteFilter.SelectedValue.ToLower() != "all")
                {
                    selectQry = selectQry.Where(h => h.SiteName == ddlSiteFilter.SelectedValue);
                }
            }

            gContentList.DataSource = selectQry.ToList();
            gContentList.DataBind();
        }
コード例 #20
0
        /// <summary>
        /// Shows the detail information on the page.
        /// </summary>
        /// <param name="pageId">The page identifier.</param>
        private void ShowDetail(int pageId)
        {
            var page = PageCache.Get(pageId);

            pnlEditPage.Visible = false;

            //
            // Ensure the page exists.
            //
            if (page == null)
            {
                nbError.Text = "This page does not exist in the system.";

                pnlDetails.Visible = false;
                pnlBlocks.Visible  = false;

                return;
            }

            //
            // Configure Copy Page Guid
            //
            RockPage.AddScriptLink(this.Page, "~/Scripts/clipboard.js/clipboard.min.js");
            string script = string.Format(@"
    new ClipboardJS('#{0}');
    $('#{0}').tooltip();
", btnCopyToClipboard.ClientID);

            ScriptManager.RegisterStartupScript(btnCopyToClipboard, btnCopyToClipboard.GetType(), "share-copy", script, true);

            btnCopyToClipboard.Attributes["data-clipboard-text"] = page.Guid.ToString();
            btnCopyToClipboard.Attributes["title"] = string.Format("Copy the Guid {0} to the clipboard.", page.Guid.ToString());

            ddlPageList.SelectedValue = page.Id.ToString();

            //
            // Ensure user has access to view this page.
            //
            if (!page.IsAuthorized(Authorization.VIEW, CurrentPerson))
            {
                nbError.Text = Rock.Constants.EditModeMessage.NotAuthorizedToView(typeof(Rock.Model.Page).GetFriendlyTypeName());

                pnlDetails.Visible = false;
                pnlBlocks.Visible  = false;

                return;
            }

            //
            // Setup the Details panel information.
            //
            hfPageId.Value = page.Id.ToString();
            lPageName.Text = page.InternalName;

            var fields = new List <KeyValuePair <string, string> >();

            fields.Add(new KeyValuePair <string, string>("Title", page.PageTitle));
            fields.Add(new KeyValuePair <string, string>("Layout", page.Layout.Name));
            fields.Add(new KeyValuePair <string, string>("Display In Navigation", page.DisplayInNavWhen == DisplayInNavWhen.WhenAllowed ? "<i class='fa fa-check'></i>" : string.Empty));
            if (page.IconBinaryFileId.HasValue)
            {
                fields.Add(new KeyValuePair <string, string>("Icon", GetImageTag(page.IconBinaryFileId, 200, 200, isThumbnail: true)));
            }

            // TODO: I'm pretty sure something like this already exists in Rock, but I can never find it. - dh
            ltDetails.Text = string.Join("", fields.Select(f => string.Format("<div class=\"col-md-6\"><dl><dt>{0}</dt><dd>{1}</dd></dl></div>", f.Key, f.Value)));

            pnlDetails.Visible  = true;
            pnlEditPage.Visible = false;

            //
            // If the user cannot edit, then do not show any of the block stuff.
            //
            if (!page.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                pnlBlocks.Visible   = false;
                lbEdit.Visible      = false;
                btnSecurity.Visible = false;

                return;
            }

            lbEdit.Visible       = true;
            btnSecurity.Title    = "Secure " + page.InternalName;
            btnSecurity.EntityId = page.Id;

            //
            // Setup the category drop down list for filtering blocks.
            //
            var selectedCategory = ddlBlockTypeCategory.SelectedValue;
            var categories       = new List <string>();

            foreach (var blockType in BlockTypeCache.All().Where(b => string.IsNullOrEmpty(b.Path)))
            {
                try
                {
                    var blockCompiledType = blockType.GetCompiledType();

                    if (typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockCompiledType))
                    {
                        if (!categories.Contains(blockType.Category))
                        {
                            categories.Add(blockType.Category);
                        }
                    }
                }
                catch
                {
                    /* Intentionally ignored. */
                }
            }
            ddlBlockTypeCategory.Items.Clear();
            foreach (var c in categories.OrderBy(c => c))
            {
                var text = c;
                if (c.StartsWith("Mobile >"))
                {
                    text = c.Replace("Mobile >", string.Empty).Trim();
                }
                ddlBlockTypeCategory.Items.Add(new ListItem(text, c));
            }
            ddlBlockTypeCategory.SetValue(selectedCategory);

            BindBlockTypeRepeater();
            BindZones();

            pnlDetails.Visible  = true;
            pnlEditPage.Visible = false;
            pnlBlocks.Visible   = true;
        }
コード例 #21
0
        /// <summary>
        /// Binds the zones repeater.
        /// </summary>
        private void BindZones()
        {
            var rockContext = new RockContext();
            int pageId      = hfPageId.Value.AsInteger();
            var page        = new PageService(rockContext).Get(pageId);
            var zones       = new List <BlockContainer>();

            //
            // Parse and find all known zones in the Phone layout.
            //
            try
            {
                var xaml = XElement.Parse(page.Layout.LayoutMobilePhone);
                foreach (var zoneNode in xaml.Descendants().Where(e => e.Name.LocalName == "Zone"))
                {
                    var zoneName = zoneNode.Attribute(XName.Get("ZoneName")).Value;

                    if (!zones.Any(z => z.Name == zoneName))
                    {
                        zones.Add(new BlockContainer
                        {
                            Name       = zoneName,
                            Components = new List <BlockInstance>()
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                nbZoneError.Text  = ex.Message;
                rptrZones.Visible = false;
                return;
            }

            //
            // Parse and find all known zones in the Tablet layout.
            //
            try
            {
                var xaml = XElement.Parse(page.Layout.LayoutMobileTablet);
                foreach (var zoneNode in xaml.Descendants().Where(e => e.Name.LocalName == "RockZone"))
                {
                    var zoneName = zoneNode.Attribute(XName.Get("ZoneName")).Value;

                    if (!zones.Any(z => z.Name == zoneName))
                    {
                        zones.Add(new BlockContainer
                        {
                            Name       = zoneName,
                            Components = new List <BlockInstance>()
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                nbZoneError.Text  = ex.Message;
                rptrZones.Visible = false;
                return;
            }

            //
            // Loop through all blocks on this page and add them to the appropriate zone.
            //
            foreach (var block in new BlockService(rockContext).Queryable().Where(b => b.PageId == pageId).OrderBy(b => b.Order).ThenBy(b => b.Id))
            {
                var blockCompiledType = BlockTypeCache.Get(block.BlockTypeId).GetCompiledType();
                if (!typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockCompiledType))
                {
                    continue;
                }

                var zone = zones.SingleOrDefault(z => z.Name == block.Zone);

                //
                // If we couldn't find the zone in the layouts, then add (or use existing) zone called 'Unknown'
                //
                if (zone == null)
                {
                    zone = zones.SingleOrDefault(z => z.Name == "Unknown");
                    if (zone == null)
                    {
                        zone = new BlockContainer
                        {
                            Name       = "Unknown",
                            Components = new List <BlockInstance>()
                        };
                        zones.Add(zone);
                    }
                }

                var iconCssClassAttribute = ( IconCssClassAttribute )blockCompiledType.GetCustomAttribute(typeof(IconCssClassAttribute));

                zone.Components.Add(new BlockInstance
                {
                    Name         = block.Name,
                    Type         = block.BlockType.Name,
                    IconCssClass = iconCssClassAttribute != null ? iconCssClassAttribute.IconCssClass : "fa fa-question",
                    Id           = block.Id
                });
            }

            rptrZones.Visible    = true;
            rptrZones.DataSource = zones;
            rptrZones.DataBind();
        }
コード例 #22
0
        /// <summary>
        /// Updates the bulk update security.
        /// </summary>
        private static void UpdateBulkUpdateSecurity()
        {
            var rockContext = new RockContext();
            var authService = new Rock.Model.AuthService(rockContext);

            var bulkUpdateBlockType = BlockTypeCache.Get(Rock.SystemGuid.BlockType.BULK_UPDATE.AsGuid());
            var bulkUpdateBlocks    = new BlockService(rockContext).Queryable().Where(a => a.BlockTypeId == bulkUpdateBlockType.Id).ToList();

            foreach (var bulkUpdateBlock in bulkUpdateBlocks)
            {
                var alreadyUpdated = authService.Queryable().Where(a =>
                                                                   (a.Action == "EditConnectionStatus" || a.Action == "EditRecordStatus") &&
                                                                   a.EntityTypeId == bulkUpdateBlock.TypeId &&
                                                                   a.EntityId == bulkUpdateBlock.Id).Any();

                if (alreadyUpdated)
                {
                    // EditConnectionStatus and/or EditRecordStatus has already been set, so don't copy VIEW auth to it
                    continue;
                }

                var groupIdAuthRules     = new HashSet <int>();
                var personIdAuthRules    = new HashSet <int>();
                var specialRoleAuthRules = new HashSet <SpecialRole>();
                var authRulesToAdd       = new List <AuthRule>();

                Dictionary <ISecured, List <AuthRule> > parentAuthRulesList = new Dictionary <ISecured, List <AuthRule> >();
                ISecured secured = bulkUpdateBlock;
                while (secured != null)
                {
                    var             entityType = secured.TypeId;
                    List <AuthRule> authRules  = Authorization.AuthRules(secured.TypeId, secured.Id, Authorization.VIEW).OrderBy(a => a.Order).ToList();

                    foreach (var rule in authRules)
                    {
                        if (rule.GroupId.HasValue)
                        {
                            if (!groupIdAuthRules.Contains(rule.GroupId.Value))
                            {
                                groupIdAuthRules.Add(rule.GroupId.Value);
                                authRulesToAdd.Add(rule);
                            }
                        }

                        else if (rule.PersonId.HasValue)
                        {
                            if (!personIdAuthRules.Contains(rule.PersonId.Value))
                            {
                                personIdAuthRules.Add(rule.PersonId.Value);
                                authRulesToAdd.Add(rule);
                            }
                        }
                        else if (rule.SpecialRole != SpecialRole.None)
                        {
                            if (!specialRoleAuthRules.Contains(rule.SpecialRole))
                            {
                                specialRoleAuthRules.Add(rule.SpecialRole);
                                authRulesToAdd.Add(rule);
                            }
                        }
                    }

                    secured = secured.ParentAuthority;
                }

                List <Auth> authsToAdd = new List <Auth>();

                foreach (var auth in authRulesToAdd)
                {
                    authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditConnectionStatus"));
                    authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditRecordStatus"));
                }

                int authOrder = 0;
                authsToAdd.ForEach(a => a.Order = authOrder++);

                authService.AddRange(authsToAdd);
                Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditConnectionStatus");
                Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditRecordStatus");
            }

            rockContext.SaveChanges();
        }
コード例 #23
0
 /// <summary>
 /// Updates any Cache Objects that are associated with this entity
 /// </summary>
 /// <param name="entityState">State of the entity.</param>
 /// <param name="dbContext">The database context.</param>
 public void UpdateCache(EntityState entityState, Rock.Data.DbContext dbContext)
 {
     BlockTypeCache.UpdateCachedEntity(this.Id, entityState);
 }
コード例 #24
0
        /// <summary>
        /// Raises the <see cref="E:Init" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage;
            if (dialogPage != null)
            {
                dialogPage.OnSave += new EventHandler <EventArgs>(masterPage_OnSave);
            }

            try
            {
                int   blockId = Convert.ToInt32(PageParameter("BlockId"));
                Block _block  = new BlockService(new RockContext()).Get(blockId);

                if (_block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                {
                    var blockType = BlockTypeCache.Read(_block.BlockTypeId);
                    if (blockType != null && !blockType.IsInstancePropertiesVerified)
                    {
                        System.Web.UI.Control control = Page.LoadControl(blockType.Path);
                        if (control is RockBlock)
                        {
                            using (var rockContext = new RockContext())
                            {
                                var rockBlock         = control as RockBlock;
                                int?blockEntityTypeId = EntityTypeCache.Read(typeof(Block)).Id;
                                Rock.Attribute.Helper.UpdateAttributes(rockBlock.GetType(), blockEntityTypeId, "BlockTypeId", blockType.Id.ToString(), rockContext);
                            }

                            blockType.IsInstancePropertiesVerified = true;
                        }
                    }

                    phAttributes.Controls.Clear();
                    phAdvancedAttributes.Controls.Clear();

                    _block.LoadAttributes();
                    if (_block.Attributes != null)
                    {
                        foreach (var attributeCategory in Rock.Attribute.Helper.GetAttributeCategories(_block))
                        {
                            if (attributeCategory.Category != null && attributeCategory.Category.Name.Equals("customsetting", StringComparison.OrdinalIgnoreCase))
                            {
                            }
                            else if (attributeCategory.Category != null && attributeCategory.Category.Name.Equals("advanced", StringComparison.OrdinalIgnoreCase))
                            {
                                Rock.Attribute.Helper.AddEditControls(
                                    string.Empty, attributeCategory.Attributes.Select(a => a.Key).ToList(),
                                    _block, phAdvancedAttributes, string.Empty, !Page.IsPostBack, new List <string>());
                            }
                            else
                            {
                                Rock.Attribute.Helper.AddEditControls(
                                    attributeCategory.Category != null ? attributeCategory.Category.Name : string.Empty,
                                    attributeCategory.Attributes.Select(a => a.Key).ToList(),
                                    _block, phAttributes, string.Empty, !Page.IsPostBack, new List <string>());
                            }
                        }
                    }
                }
                else
                {
                    DisplayError("You are not authorized to edit this block", null);
                }
            }
            catch (SystemException ex)
            {
                DisplayError(ex.Message, "<pre>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</pre>");
            }

            base.OnInit(e);
        }
コード例 #25
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)
        {
            base.OnLoad(e);

            List <int>  expandedPageIds = new List <int>();
            RockContext rockContext     = new RockContext();
            PageService pageService     = new PageService(rockContext);

            var allPages = pageService.Queryable("PageContexts, PageRoutes");

            foreach (var page in allPages)
            {
                PageCache.Read(page);
            }

            foreach (var block in new BlockService(rockContext).Queryable())
            {
                BlockCache.Read(block);
            }

            foreach (var blockType in new BlockTypeService(rockContext).Queryable())
            {
                BlockTypeCache.Read(blockType);
            }

            if (Page.IsPostBack)
            {
                foreach (string expandedId in hfExpandedIds.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    int id = 0;
                    if (expandedId.StartsWith("p") && expandedId.Length > 1)
                    {
                        if (int.TryParse(expandedId.Substring(1), out id))
                        {
                            expandedPageIds.Add(id);
                        }
                    }
                }
            }
            else
            {
                string pageSearch = this.PageParameter("pageSearch");
                if (!string.IsNullOrWhiteSpace(pageSearch))
                {
                    foreach (Page page in pageService.Queryable().Where(a => a.InternalName.IndexOf(pageSearch) >= 0))
                    {
                        Page selectedPage = page;
                        while (selectedPage != null)
                        {
                            selectedPage = selectedPage.ParentPage;
                            if (selectedPage != null)
                            {
                                expandedPageIds.Add(selectedPage.Id);
                            }
                        }
                    }
                }
            }

            var sb = new StringBuilder();

            sb.AppendLine("<ul id=\"treeview\">");

            string rootPage = GetAttributeValue("RootPage");

            if (!string.IsNullOrEmpty(rootPage))
            {
                Guid pageGuid = rootPage.AsGuid();
                allPages = allPages.Where(a => a.ParentPage.Guid == pageGuid);
            }
            else
            {
                allPages = allPages.Where(a => a.ParentPageId == null);
            }

            foreach (var page in allPages.OrderBy(a => a.Order).ThenBy(a => a.InternalName).Include(a => a.Blocks).ToList())
            {
                sb.Append(PageNode(PageCache.Read(page), expandedPageIds, rockContext));
            }

            sb.AppendLine("</ul>");

            lPages.Text = sb.ToString();
        }
コード例 #26
0
        /// <summary>
        /// Adds the page nodes.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="expandedPageIdList">The expanded page identifier list.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        protected string PageNode(Page page, List <int> expandedPageIdList, RockContext rockContext)
        {
            var sb = new StringBuilder();

            string pageSearch = this.PageParameter("pageSearch");
            bool   isSelected = false;

            if (!string.IsNullOrWhiteSpace(pageSearch))
            {
                isSelected = page.InternalName.IndexOf(pageSearch, StringComparison.OrdinalIgnoreCase) >= 0;
            }

            bool isExpanded = expandedPageIdList.Contains(page.Id);

            sb.AppendFormat("<li data-expanded='{4}' data-model='Page' data-id='p{0}'><span><i class=\"fa fa-file-o\">&nbsp;</i> <a href='{1}'>{2}</a></span>{3}", page.Id, new PageReference(page.Id).BuildUrl(), isSelected ? "<strong>" + page.InternalName + "</strong>" : page.InternalName, Environment.NewLine, isExpanded.ToString().ToLower());

            if (page.Pages.Any() || page.Blocks.Any())
            {
                sb.AppendLine("<ul>");

                foreach (var childPage in page.Pages.OrderBy(a => a.Order).ThenBy(a => a.InternalName))
                {
                    sb.Append(PageNode(childPage, expandedPageIdList, rockContext));
                }

                foreach (var block in page.Blocks.OrderBy(b => b.Order))
                {
                    sb.AppendFormat("<li data-expanded='false' data-model='Block' data-id='b{0}'><span>{1}{2}:{3}</span></li>{4}", block.Id, CreateConfigIcon(block), block.Name, BlockTypeCache.Read(block.BlockTypeId, rockContext).Name, Environment.NewLine);
                }

                sb.AppendLine("</ul>");
            }

            sb.AppendLine("</li>");

            return(sb.ToString());
        }
コード例 #27
0
 /// <summary>
 /// Gets the cache object associated with this Entity
 /// </summary>
 /// <returns></returns>
 public IEntityCache GetCacheObject()
 {
     return(BlockTypeCache.Get(this.Id));
 }
コード例 #28
0
        /// <summary>
        /// Handles the Click event of the btnAddBlock 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 btnAddBlock_Click(object sender, EventArgs e)
        {
            tbNewBlockName.Text = string.Empty;

            // Load the block types
            using (var rockContext = new RockContext())
            {
                try
                {
                    BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page);
                }
                catch
                {
                    // ignore
                }


                Rock.Model.BlockTypeService blockTypeService = new Rock.Model.BlockTypeService(rockContext);
                var blockTypes = blockTypeService.Queryable().AsNoTracking()
                                 .Select(b => new { b.Id, b.Name, b.Category, b.Description })
                                 .ToList();

                ddlBlockType.Items.Clear();

                // Add the categorized block types
                foreach (var blockType in blockTypes
                         .Where(b => b.Category != string.Empty)
                         .OrderBy(b => b.Category)
                         .ThenBy(b => b.Name))
                {
                    var li = new ListItem(blockType.Name, blockType.Id.ToString());
                    li.Attributes.Add("optiongroup", blockType.Category);
                    li.Attributes.Add("title", blockType.Description);
                    ddlBlockType.Items.Add(li);
                }

                // Add the uncategorized block types
                foreach (var blockType in blockTypes
                         .Where(b => b.Category == null || b.Category == string.Empty)
                         .OrderBy(b => b.Name))
                {
                    var li = new ListItem(blockType.Name, blockType.Id.ToString());
                    li.Attributes.Add("optiongroup", "Other (not categorized)");
                    li.Attributes.Add("title", blockType.Description);
                    ddlBlockType.Items.Add(li);
                }
            }

            var htmlContentBlockType = BlockTypeCache.Read(Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid());

            ddlBlockType.SetValue(htmlContentBlockType.Id);

            rblAddBlockLocation.Items.Clear();

            var page = PageCache.Read(hfPageId.Value.AsInteger());

            var listItemPage = new ListItem();

            listItemPage.Text     = string.Format("Page ({0})", page.ToString());
            listItemPage.Value    = "Page";
            listItemPage.Selected = true;

            var listItemLayout = new ListItem();

            listItemLayout.Text     = string.Format("Layout ({0})", page.Layout);
            listItemLayout.Value    = "Layout";
            listItemLayout.Selected = false;

            var listItemSite = new ListItem();

            listItemSite.Text     = string.Format("Site ({0})", page.Layout.Site);
            listItemSite.Value    = "Site";
            listItemSite.Selected = false;

            rblAddBlockLocation.Items.Add(listItemPage);
            rblAddBlockLocation.Items.Add(listItemLayout);
            rblAddBlockLocation.Items.Add(listItemSite);
            mdAddBlock.Title = "Add Block to " + ddlZones.SelectedValue + " Zone";
            mdAddBlock.Show();
        }
コード例 #29
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(EntityState entityState, Rock.Data.DbContext dbContext)
        {
            AttributeCache.UpdateCachedEntity(this.Id, entityState);
            AttributeCache.UpdateCacheEntityAttributes(this, entityState);

            int?   entityTypeId;
            string entityTypeQualifierColumn;
            string entityTypeQualifierValue;

            if (entityState == EntityState.Deleted)
            {
                entityTypeId = originalEntityTypeId;
                entityTypeQualifierColumn = originalEntityTypeQualifierColumn;
                entityTypeQualifierValue  = originalEntityTypeQualifierValue;
            }
            else
            {
                entityTypeId = this.EntityTypeId;
                entityTypeQualifierColumn = this.EntityTypeQualifierColumn;
                entityTypeQualifierValue  = this.EntityTypeQualifierValue;
            }

            if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && string.IsNullOrEmpty(entityTypeQualifierColumn) && string.IsNullOrEmpty(entityTypeQualifierValue))
            {
                GlobalAttributesCache.Remove();
            }

            if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && entityTypeQualifierColumn == Attribute.SYSTEM_SETTING_QUALIFIER && string.IsNullOrEmpty(entityTypeQualifierValue))
            {
                Rock.Web.SystemSettings.Remove();
            }

            if (entityTypeId.HasValue)
            {
                if (entityTypeId == EntityTypeCache.GetId <Block>())
                {
                    // Update BlockTypes/Blocks that reference this attribute
                    if (entityTypeQualifierColumn.Equals("BlockTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?blockTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (blockTypeId.HasValue)
                        {
                            BlockTypeCache.FlushItem(blockTypeId.Value);

                            foreach (var blockId in new BlockService(dbContext as RockContext).GetByBlockTypeId(blockTypeId.Value).Select(a => a.Id).ToList())
                            {
                                BlockCache.FlushItem(blockId);
                            }
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <DefinedValue>())
                {
                    // Update DefinedTypes/DefinedValues that reference this attribute
                    if (entityTypeQualifierColumn.Equals("DefinedTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?definedTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (definedTypeId.HasValue)
                        {
                            DefinedTypeCache.FlushItem(definedTypeId.Value);

                            foreach (var definedValueId in new DefinedValueService(dbContext as RockContext).GetByDefinedTypeId(definedTypeId.Value).Select(a => a.Id).ToList())
                            {
                                DefinedValueCache.FlushItem(definedValueId);
                            }
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <WorkflowActivityType>())
                {
                    if (entityTypeQualifierColumn.Equals("ActivityTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?activityTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (activityTypeId.HasValue)
                        {
                            WorkflowActivityTypeCache.FlushItem(activityTypeId.Value);
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <GroupType>())
                {
                    if (entityTypeQualifierColumn.Equals("Id", StringComparison.OrdinalIgnoreCase))
                    {
                        int?groupTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (groupTypeId.HasValue)
                        {
                            GroupTypeCache.FlushItem(groupTypeId.Value);
                        }
                    }
                    else if (entityTypeQualifierColumn.Equals("GroupTypePurposeValueId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?groupTypePurposeValueId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (groupTypePurposeValueId.HasValue)
                        {
                            foreach (var groupTypeId in GroupTypeCache.All().Where(a => a.GroupTypePurposeValueId == groupTypePurposeValueId.Value).Select(a => a.Id).ToList())
                            {
                                GroupTypeCache.FlushItem(groupTypeId);
                            }
                        }
                    }
                }
                else if (entityTypeId.HasValue)
                {
                    // some other EntityType. If it the EntityType has a CacheItem associated with it, clear out all the CachedItems of that type to ensure they have a clean read of the Attributes that were Added, Changed or Removed
                    EntityTypeCache entityType = EntityTypeCache.Get(entityTypeId.Value, dbContext as RockContext);

                    if (entityType?.HasEntityCache() == true)
                    {
                        entityType.ClearCachedItems();
                    }
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Handles the Click event of the btnAddBlock 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 btnAddBlock_Click(object sender, EventArgs e)
        {
            tbNewBlockName.Text = string.Empty;

            // Load the block types
            using (var rockContext = new RockContext())
            {
                try
                {
                    BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page);
                }
                catch
                {
                    // ignore
                }

                // Get a list of BlockTypes that does not include Mobile block types.
                List <BlockTypeCache> allExceptMobileBlockTypes = new List <BlockTypeCache>();
                foreach (var cachedBlockType in BlockTypeCache.All())
                {
                    try
                    {
                        var blockCompiledType = cachedBlockType.GetCompiledType();

                        if (!typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockCompiledType))
                        {
                            allExceptMobileBlockTypes.Add(cachedBlockType);
                        }
                    }
                    catch (Exception)
                    {
                        // Intentionally ignored
                    }
                }

                var blockTypes = allExceptMobileBlockTypes.Select(b => new { b.Id, b.Name, b.Category, b.Description }).ToList();

                ddlBlockType.Items.Clear();

                // Add the categorized block types
                foreach (var blockType in blockTypes.Where(b => b.Category != string.Empty).OrderBy(b => b.Category).ThenBy(b => b.Name))
                {
                    var li = new ListItem(blockType.Name, blockType.Id.ToString());
                    li.Attributes.Add("optiongroup", blockType.Category);
                    li.Attributes.Add("title", blockType.Description);
                    ddlBlockType.Items.Add(li);
                }

                // Add the uncategorized block types
                foreach (var blockType in blockTypes.Where(b => b.Category == null || b.Category == string.Empty).OrderBy(b => b.Name))
                {
                    var li = new ListItem(blockType.Name, blockType.Id.ToString());
                    li.Attributes.Add("optiongroup", "Other (not categorized)");
                    li.Attributes.Add("title", blockType.Description);
                    ddlBlockType.Items.Add(li);
                }
            }

            // Set the initial selection to the HTMLContent block.
            ddlBlockType.SetValue(BlockTypeCache.Get(Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid()).Id);

            rblAddBlockLocation.Items.Clear();

            var page = PageCache.Get(hfPageId.Value.AsInteger());

            var listItemPage = new ListItem();

            listItemPage.Text     = string.Format("Page ({0})", page.ToString());
            listItemPage.Value    = "Page";
            listItemPage.Selected = true;

            var listItemLayout = new ListItem();

            listItemLayout.Text     = string.Format("Layout ({0})", page.Layout);
            listItemLayout.Value    = "Layout";
            listItemLayout.Selected = false;

            var listItemSite = new ListItem();

            listItemSite.Text     = string.Format("Site ({0})", page.Layout.Site);
            listItemSite.Value    = "Site";
            listItemSite.Selected = false;

            rblAddBlockLocation.Items.Add(listItemPage);
            rblAddBlockLocation.Items.Add(listItemLayout);
            rblAddBlockLocation.Items.Add(listItemSite);
            mdAddBlock.Title = "Add Block to " + ddlZones.SelectedValue + " Zone";
            mdAddBlock.Show();
        }