Click here to Skip to main content
15,891,253 members
Articles / Productivity Apps and Services / Sharepoint

Site Content Web Part (SharePoint 2010)

Rate me:
Please Sign up or sign in to vote.
4.17/5 (4 votes)
15 May 2010CPOL3 min read 58.6K   1.7K   10  
Displays site and sub-site content in a hierarchical tree that is expandable and collapsible
//
//	SiteContentWebPart.cs - © Questech Systems
//	This notice must stay intact for use. Not for resale.
//
using System;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using QuestechSystems.SharePoint.ComponentModel;

namespace QuestechSystems.SharePoint.WebControls
{
    public class SiteContentWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDisplayName("SiteContentWebPartDisplayName_TopSiteUrl")]
        [SPWebDescription("SiteContentWebPartDescription_TopSiteUrl")]
        [SPCategory("SPCategory_Configuration")]
        public string TopSiteUrl
        {
            get
            {
                return _topSiteUrl;
            }
            set
            {
                _topSiteUrl = value;
            }
        }

        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDisplayName("SiteContentWebPartDisplayName_ExpandMap")]
        [SPWebDescription("SiteContentWebPartDescription_ExpandMap")]
        [SPCategory("SPCategory_Configuration")]
        public bool ExpandMap
        {
            get
            {
                return _expandMap;
            }
            set
            {
                _expandMap = value;
            }
        }

        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDisplayName("SiteContentWebPartDisplayName_ShowWebChildren")]
        [SPWebDescription("SiteContentWebPartDescription_ShowWebChildren")]
        [SPCategory("SPCategory_Configuration")]
        public bool ShowWebChildren
        {
            get
            {
                return _showWebChildren;
            }
            set
            {
                _showWebChildren = value;
            }
        }

        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDisplayName("SiteContentWebPartDisplayName_ShowFolderChildren")]
        [SPWebDescription("SiteContentWebPartDescription_ShowFolderChildren")]
        [SPCategory("SPCategory_Configuration")]
        public bool ShowFolderChildren
        {
            get
            {
                return _showFolderChildren;
            }
            set
            {
                _showFolderChildren = value;
            }
        }

        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDisplayName("SiteContentWebPartDisplayName_IncludeDiscussionFolders")]
        [SPWebDescription("SiteContentWebPartDescription_IncludeDiscussionFolders")]
        [SPCategory("SPCategory_Configuration")]
        public bool IncludeDiscussionFolders
        {
            get
            {
                return _includeDiscussionFolders;
            }
            set
            {
                _includeDiscussionFolders = value;
            }
        }

        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDisplayName("SiteContentWebPartDisplayName_MaxLevels")]
        [SPWebDescription("SiteContentWebPartDescription_MaxLevels")]
        [SPCategory("SPCategory_Configuration")]
        public int MaxLevels
        {
            get
            {
                return _maxLevels;
            }
            set
            {
                _maxLevels = value;
            }
        }

        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDescription("SiteContentWebPartDescription_ListCssClass")]
        [SPCategory("SPCategory_Configuration")]
        public string ListCssClass
        {
            get
            {
                return _listCssClass;
            }
            set
            {
                _listCssClass = value;
            }
        }

        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [SPWebDescription("SiteContentWebPartDescription_NodeCssClass")]
        [SPCategory("SPCategory_Configuration")]
        public string NodeCssClass
        {
            get
            {
                return _nodeCssClass;
            }
            set
            {
                _nodeCssClass = value;
            }
        }

        private const string FilePathSiteContent = "ClientScripts.SiteContentWebPart.js";
        private const string JSBlockKeySiteContent = "JSBlockKeySiteMap";
        private const string JSIncludeKeySiteContent = "JSIncludeKeySiteMap";

        private const string ImagePathFormatString = "{0}/images/{1}";
        private const string JavaScriptBlockFormatString = @"
g_strImgChannelOpenHTML = ""<img src='{0}/images/node-open.gif' style='border-width:0px;'>"";
g_strImgChannelClosedHTML = ""<img src='{0}/images/node-closed.gif' style='border-width:0px;'>"";
";
        private const string ListOpenHtmlFormatString = @"
<ul id=""{0}_{1}"" style=""display: {2};"" style="""">";
        private const string OnClickJavaScriptFormatString = "toggleLayer('{0}_{1}');return false";
        private const string TopListOpenHtmlFormatString = "<ul{0}>";

        private const string DisplayBlock = "block";
        private const string DisplayNone = "none";
        private const string ListCloseHtml = "\n</ul>";
        private const string ListItemOpenHtml = "\n<li>";
        private const string ListItemCloseHtml = "</li>";
        private const string ToggleImageIDSuffix = "x";

        private IHierarchicalEnumerable _dataItems;
        private bool _expandMap = true;
        private bool _includeDiscussionFolders = false;
        private bool _showFolderChildren = true;
        private bool _showWebChildren = true;
        private int _maxLevels = 0;
        private int _parentCount = 0;
        private string _displayOnLoad;
        private string _imageUrl;
        private string _listCssClass;
        private string _nodeCssClass;
        private string _topSiteUrl;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _imageUrl = SPWebPartManager.GetClassResourcePath(SPContext.Current.Web, this.GetType());

            if (_expandMap)
            {
                _displayOnLoad = DisplayBlock;
            }
            else
            {
                _displayOnLoad = DisplayNone;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            ClientScriptManager cs = Page.ClientScript;
            if (!cs.IsClientScriptIncludeRegistered(typeof(Page), JSIncludeKeySiteContent))
            {
                string scriptUrl = cs.GetWebResourceUrl(this.GetType(), String.Format("{0}.{1}", Utility.DefaultNamespace, FilePathSiteContent));
                cs.RegisterClientScriptInclude(typeof(Page), JSIncludeKeySiteContent, scriptUrl);
            }
            if (!cs.IsClientScriptBlockRegistered(typeof(Page), JSBlockKeySiteContent))
            {
                string scriptBlock = String.Format(JavaScriptBlockFormatString, _imageUrl);
                cs.RegisterClientScriptBlock(typeof(Page), JSBlockKeySiteContent, scriptBlock, true);
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            try
            {
                InitDataSourceControl();

                String cssClassHtml = String.Empty;
                if (!String.IsNullOrEmpty(_listCssClass))
                {
                    cssClassHtml = String.Format(" class=\"{0}\"", _listCssClass);
                }
                Controls.Add(new LiteralControl(String.Format(TopListOpenHtmlFormatString, cssClassHtml)));

                IHierarchyData node;
                foreach (object dataItem in _dataItems)
                {
                    node = _dataItems.GetHierarchyData(dataItem);
                    RenderNode(node, 1);
                }

                Controls.Add(new LiteralControl(ListCloseHtml));
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.Message));
            }
        }

        private void InitDataSourceControl()
        {
            SPHierarchyDataSourceControl dataSourceControl = new SPHierarchyDataSourceControl();

            dataSourceControl.IncludeDiscussionFolders = _includeDiscussionFolders;
            dataSourceControl.ShowDocLibChildren = true;
            dataSourceControl.ShowFolderChildren = _showFolderChildren;
            dataSourceControl.ShowListChildren = true;
            dataSourceControl.ShowWebChildren = _showWebChildren;

            if (String.IsNullOrEmpty(_topSiteUrl))
            {
                dataSourceControl.RootContextObject = "Web";
            }
            else
            {
                using (SPWeb startSite = SPContext.Current.Site.OpenWeb(_topSiteUrl))
                {
                    if (startSite == null)
                    {
                        dataSourceControl.RootContextObject = "Web";
                    }
                    else
                    {
                        dataSourceControl.RootWebId = startSite.ID.ToString();
                    }
                }
            }

            HierarchicalDataSourceView view = dataSourceControl.GetHierarchicalViewPublic("");
            _dataItems = view.Select();
        }

        private void RenderNode(IHierarchyData node, int level)
        {
            if (node == null)
            {
                return;
            }

            if (IsNodeExpandable(node, level))
            {
                RenderNodeHasChildren(node, level);
            }
            else
            {
                RenderNodeHasNoChildren(node);
            }
        }

        private bool IsNodeExpandable(IHierarchyData node, int level)
        {
            if (!node.HasChildren)
            {
                return false;
            }

            if (level >= _maxLevels && _maxLevels != 0)
            {
                return false;
            }

            return true;
        }

        private void RenderNodeHasNoChildren(IHierarchyData node)
        {
            Controls.Add(new LiteralControl(ListItemOpenHtml));
            HtmlImage image = new HtmlImage();
            image.Src = String.Format(ImagePathFormatString, _imageUrl, "node.gif");
            Controls.Add(image);
            Controls.Add(new LiteralControl(" "));
            RenderNodeItem(node);
            Controls.Add(new LiteralControl(ListItemCloseHtml));
        }

        private void RenderNodeHasChildren(IHierarchyData node, int level)
        {
            _parentCount++;
            string nodeID = _parentCount.ToString();

            Controls.Add(new LiteralControl(ListItemOpenHtml));

            HyperLink hyperlink = new HyperLink();
            hyperlink.ID = nodeID + ToggleImageIDSuffix;
            hyperlink.NavigateUrl = "javascript:void(null);";
            hyperlink.Attributes["onClick"] = String.Format(OnClickJavaScriptFormatString, base.ClientID, nodeID);
            if (_expandMap)
            {
                hyperlink.ImageUrl = String.Format(ImagePathFormatString, _imageUrl, "node-open.gif");
            }
            else
            {
                hyperlink.ImageUrl = String.Format(ImagePathFormatString, _imageUrl, "node-closed.gif");
            }
            Controls.Add(hyperlink);

            Controls.Add(new LiteralControl(" "));

            RenderNodeItem(node);

            Controls.Add(new LiteralControl(String.Format(ListOpenHtmlFormatString, base.ClientID, nodeID, _displayOnLoad)));

            IHierarchicalEnumerable enumerables = node.GetChildren();
            IHierarchyData childrenNode;

            if (enumerables != null)
            {
                foreach (object dataItem in enumerables)
                {
                    childrenNode = _dataItems.GetHierarchyData(dataItem);
                    RenderNode(childrenNode, level + 1);
                }
            }

            Controls.Add(new LiteralControl(ListCloseHtml));
            Controls.Add(new LiteralControl(ListItemCloseHtml));
        }

        private void RenderNodeItem(IHierarchyData node)
        {
            PropertyDescriptorCollection propDescriptors = TypeDescriptor.GetProperties(node);

            string title = GetPropertyDescriptorValue(node, "Name");
            string url = GetPropertyDescriptorValue(node, "ServerRelativeUrl");

            if (String.IsNullOrEmpty(title) || String.IsNullOrEmpty(url))
            {
                return;
            }

            HyperLink hyperlink = new HyperLink();
            hyperlink.CssClass = _nodeCssClass;
            hyperlink.NavigateUrl = url;
            hyperlink.Text = SPEncode.HtmlEncode(title);
            Controls.Add(hyperlink);
        }

        private string GetPropertyDescriptorValue(IHierarchyData node, string propertyName)
        {
            PropertyDescriptorCollection propDescriptors = TypeDescriptor.GetProperties(node);

            if (propDescriptors.Count >= 1)
            {
                foreach (PropertyDescriptor property in propDescriptors)
                {
                    if (String.Compare(property.Name, propertyName, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        return Convert.ToString(property.GetValue(node));
                    }
                }
            }

            return null;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Canada Canada
A Microsoft Certified Professional Developer and Technology Specialist.

Experience and expertise in SharePoint 2016 / 2013 / 2010 / 2007.

Role ranges from a developer in a multi-person team to a solution consultant with expert-level skills, leading a project to completion status.

Proven experience working effectively in a team environment and a self-managed environment.

Comments and Discussions