예제 #1
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();
            }
        }
예제 #2
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));
                }
            }
        }
        /// <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);
        }
예제 #4
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.Get(btnNewBlockQuickSetting.CommandArgument.AsInteger());

            if (quickSettingBlockType != null)
            {
                ddlBlockType.SetValue(quickSettingBlockType.Id);
                ddlBlockType_SelectedIndexChanged(sender, e);
            }
        }
        /// <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();
        }
        /// <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);
                }
            }
        }
예제 #7
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.Get(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);
        }
예제 #8
0
 /// <summary>
 /// Gets the cache object associated with this Entity
 /// </summary>
 /// <returns></returns>
 public IEntityCache GetCacheObject()
 {
     return(BlockTypeCache.Get(this.Id));
 }
예제 #9
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();
        }
예제 #10
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();
        }
예제 #11
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.Get(Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid());

            ddlBlockType.SetValue(htmlContentBlockType.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();
        }
예제 #12
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();
        }
예제 #13
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            int    entityTypeIdBlock   = EntityTypeCache.Get(typeof(Rock.Model.Block), true, rockContext).Id;
            string entityTypeQualifier = BlockTypeCache.Get(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,
                BlockSiteId      = a.Block.SiteId,
            });

            gContentList.EntityTypeId = EntityTypeCache.Get <HtmlContent>().Id;

            // 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();
        }
예제 #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)
        {
            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);
                dialogPage.Title    = _block.BlockType.Name;
                dialogPage.SubTitle = string.Format("{0} / Id: {1}", _block.BlockType.Category, blockId);

                if (_block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                {
                    var blockType = BlockTypeCache.Get(_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.Get(typeof(Block)).Id;
                                Rock.Attribute.Helper.UpdateAttributes(rockBlock.GetType(), blockEntityTypeId, "BlockTypeId", blockType.Id.ToString(), rockContext);
                            }

                            blockType.MarkInstancePropertiesVerified(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);
        }