Theming SharePoint (4 of Infinite)

Michael O’Donovan brings us a blog post about custom (left) navigation in SharePoint. That is what I will be tackling today so I can move away from the ugly Tables and use a more common UL/LI scheme.

Here is my class:

using System;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
using Microsoft.SharePoint.Utilities;

namespace MMOinsite.SharePoint.Components
{
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal),
     AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
    public class ListNavigation : HierarchicalDataBoundControl
    {
        private XmlDocument navigationTree;
        private string currentNodeKey = string.Empty;

        private string linkClass = "NavLeftLink";
        private string listItemClass = "NavLeftListItem";
        private string listClass = "NavLeftList";
        private string linkSelectedClass = "NavLeftListItemSelected";

        private bool appendLevel = false;
        private string appendLevelClass = "NavLeftListItem";

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

            // Oh god, no data source! ABORT!
            if (!IsBoundUsingDataSourceID && (DataSource == null))
                return;

            HierarchicalDataSourceView view = GetData("");

            if (view == null)
                throw new InvalidOperationException("Cannot get any data from the data source control.");

            IHierarchicalEnumerable enumerable = view.Select();
            if (enumerable != null)
            {
                navigationTree = new XmlDocument();
                navigationTree.LoadXml("");

                try
                {
                    AddNavigationItem(navigationTree.DocumentElement, enumerable, 1);
                }
                finally { }

                ViewState["navXml"] = navigationTree.OuterXml;
            }
        }

        private void AddNavigationItem(XmlElement currentNode, IHierarchicalEnumerable enumerable, int depth)
        {
            foreach (object item in enumerable)
            {
                IHierarchyData data = enumerable.GetHierarchyData(item);

                NavigationItem navItem = BuildNavigationItem(data, depth);

                XmlElement newNavElement = BuildNavigationNode(currentNode, navItem);

                currentNode.AppendChild(newNavElement);

                if(data.HasChildren)
                {
                    IHierarchicalEnumerable newEnumerable = data.GetChildren();

                    if(newEnumerable != null)
                        AddNavigationItem(newNavElement, newEnumerable, depth + 1);
                }
            }
        }

        private NavigationItem BuildNavigationItem(IHierarchyData data, int depth)
        {
            NavigationItem tmpNavItem = new NavigationItem();

            try
            {
                INavigateUIData navNode = (INavigateUIData)data;

                tmpNavItem.Title = navNode.Value;
                tmpNavItem.Url = navNode.NavigateUrl;
                tmpNavItem.Level = depth;

                if (currentNodeKey.Length == 0)
                {
                    SiteMapDataSource dataSource = GetDataSource() as SiteMapDataSource;

                    if (dataSource != null)
                        if (dataSource.Provider.CurrentNode != null)
                            currentNodeKey = dataSource.Provider.CurrentNode.Url.ToLower();
                }

                if (string.Compare(tmpNavItem.Url, currentNodeKey, true, CultureInfo.InvariantCulture) == 0)
                    tmpNavItem.Selected = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return tmpNavItem;
        }

        private NavigationItem BuildNavigationItem(XmlNode node)
        {
            NavigationItem tmpNavItem = new NavigationItem();

            tmpNavItem.Title = node.Attributes["title"].InnerText;
            tmpNavItem.Url = node.Attributes["url"].InnerText;
            tmpNavItem.Selected = Convert.ToBoolean(node.Attributes["isSelected"].InnerText);
            tmpNavItem.Level = Convert.ToInt32(node.Attributes["level"].InnerText);

            return tmpNavItem;
        }

        private XmlElement BuildNavigationNode(XmlElement parentNode, NavigationItem navItem)
        {
            XmlElement tmpNode = navigationTree.CreateElement("node");

            tmpNode.SetAttribute("url", navItem.Url);
            tmpNode.SetAttribute("title", navItem.Title);
            tmpNode.SetAttribute("level", navItem.Level.ToString());
            tmpNode.SetAttribute("isSelected", navItem.Selected.ToString());

            return tmpNode;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (navigationTree == null && ViewState["navXml"] != null)
            {
                navigationTree = new XmlDocument();
                navigationTree.LoadXml(ViewState["navXml"].ToString());
            }

            XmlNodeList nodeList = navigationTree.SelectNodes("nodes/node");

            if (nodeList.Count > 0)
            {
                WriteListStart(writer);
                foreach (XmlNode node in nodeList)
                {
                    Render(node, writer);
                }
                WriteListEnd(writer);
            }
        }

        protected virtual void WriteListStart(HtmlTextWriter writer)
        {
            writer.Write(string.Format("
    ", ListClass)); } protected virtual void WriteListEnd(HtmlTextWriter writer) { writer.Write("
"); } protected virtual void Render(XmlNode navNode, HtmlTextWriter writer) { NavigationItem navItem = BuildNavigationItem(navNode); writer.Write( string.Format( "
  • ", ListItemClass, (AppendLevel) ? string.Format(" {0}{1}", AppendLevelClass, navItem.Level) : "" ) ); writer.Write( string.Format( "{2}", (navItem.Selected) ? LinkSelectedClass : LinkClass, navItem.Url, navItem.Title ) ); if (navNode.ChildNodes.Count > 0) { WriteListStart(writer); XmlNodeList nodeList = navNode.SelectNodes("node"); foreach (XmlNode childNode in nodeList) Render(childNode, writer); WriteListEnd(writer); } writer.Write("
  • "); } public string ListClass { get { return listClass; } set { listClass = value; } } public string LinkSelectedClass { get { return linkSelectedClass; } set { linkSelectedClass = value; } } public string LinkClass { get { return linkClass; } set { linkClass = value; } } public string ListItemClass { get { return listItemClass; } set { listItemClass = value; } } public bool AppendLevel { get { return appendLevel; } set { appendLevel = value; } } public string AppendLevelClass { get { return appendLevelClass; } set { appendLevelClass = value; } } } }

    But how do we install it? Good question John. Why thank you John! Copy it to your server. Open the GAC (C:\WINDOWS\assembly) and drag and drop. Now perform an IISRESET and add the control to your master page in the usual way:

    <%@ Register Tagprefix="asp" Namespace="MMOinsite.SharePoint.Components" Assembly="MMOinsite.SharePoint.Components, Version=1.0.0.0, Culture=neutral, PublicKeyToken=abb33cdce6ddaae1" %>
    
    ...
    
    
    

    It is important to note that the UL/LI scheme is incredibly flexible. You can make them horizontal, drop down menus or keep them as standard vertical lists. Once the control is in place, the designer (CSS for the win here) can take over. For this reason, this type of navigation scheme can also make its way to the top navigation bar. But I will leave that up to you as I have got to get back to work!

    Update (9:58): Here are the CSS styles I use with setting AppendLevel to true in the control tag of the master page. There is some pretty wacky CSS going on here and I am sure it can be cleaned up, but it works in IE7 and is a good place to start.

    .NavLeftLink{
    	color: #2D2D2D;
    }
    
    .NavLeftListItem{
    	background: #F2F8FF;
    	margin-left: 0px;
    	padding: 0px;
    	width: 100%;
    }
    
    .NavLeftListItem2{
    }
    
    .NavLeftListItem a{
    	padding: 2px 0px 2px 5px;
    	border-top: solid 1px #25475A;
    	width: 100%;
    }
    
    .NavLeftListItem a:hover{
    	background: #D4F7B9;
    }
    
    .NavLeftListItem1 a{
    	background: #BACCD6;
    	font-size: 1.2em;
    	font-weight: bold;
    	border-bottom: solid 1px #25475A;
    	margin-bottom: 1px;
    }
    
    .NavLeftListItem2 a{
    	background: #F2F8FF;
    	border: 0px;
    	padding-left: 20px;
    	font-size: 1em;
    	font-weight: normal;
    	background-image: url(/_layouts/images/navBullet.gif);
    	background-repeat: no-repeat;
    	background-position: 5px top;
    }
    
    .NavLeftListItem2 a:hover{
    	background-image: url(/_layouts/images/navBullet.gif);
    	background-repeat: no-repeat;
    	background-position: 5px top;
    }
    
    .NavLeftListItemSelected{
    	background: #D4F7B9;
    }
    
    .NavLeftList{
    	margin-top: 0px;
    	margin-left: 0px;
    	list-style: none;
    	border-bottom: solid 1px #25475A;
    }
    
    .NavLeftList .NavLeftList{
    	border: 0px;
    }

    One thought on “Theming SharePoint (4 of Infinite)

    1. Hi, thanks for the post, i tried to run the chsrp file and i am getting the error
      “type ‘Microsoft.Web.Management.Client.NavigationItem’ has no constructors defined”
      and i can not see the properties Title,URL,Level. how do we fix this error? much apprciate for your response. Thanks.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    *


    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>