Tuesday, April 23, 2013

Custom Top Navigation in SharePoint 2010


Hi,

We noticed one problem in default top navigation of SharePoint 2010 i.e.

There were three more tabs added to our top navigation apart from Home tab.

So when user goes to any page only Home tab was getting highlighted.

That is why we have been to custom top navigation so that to have Tab1, Tab2, Tab3 and Tab4

Now if user clicks on sub item1/sub item2   Tab2 should be highlighted, for this we have to update class as active.

So finally two tasks have to been achieved i.e. creating sub item1/sub item2 dynamically under Tab2 and highlighting tab by updating class of that as below.
Below is the code that has been written to achieve the same by deploying user control.

User Control Design

<div>
    <div id="nav">
        <ul id="ultopnav" runat="server">
            <li id="liHome" runat="server"><a href="~/SitePages/Home.aspx" id="aHome" runat="server">
                <span>Home</span></a></li>
            <li id="liCapabilities" runat="server"><a href="~/SitePages/Capabilities.aspx" id="aCapabilities"
                runat="server"><span>Capabilities</span></a></li>
            <li id="liCareerManager" runat="server"><a id="aCareerManager" runat="server"><span>
                Career Manager</span></a>
                <div class="dropdown">
                    <ul id="ulCareerManager" runat="server">
                        <!--<li class="nodivider"><a href="#">AZengaze Job Catalogue</a></li>
                        <li><a href="#">Local Role Assignment</a></li>-->
                    </ul>
                </div>
            </li>
            <li id="liCommunitiesofPractice" runat="server"><a href="~/SitePages/CommunitiesofPractice.aspx"
                id="aCommunitiesofPractice" runat="server"><span>Communities of Practice</span></a></li>
           
        </ul>
    </div>
</div>

Source Code
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts; 
using System.Globalization;
using Microsoft.Practices.SharePoint.Common.Logging;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;
using System.Text;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Web;


namespace SharePoint.MLZ.TopNavigationBar.ControlTemplates.SharePoint.MLZ.TopNavigationBar
{
    public partial class TopNavigationBarUserControl : UserControl
    {
        #region Private Variables
        StringBuilder sb = new StringBuilder();
        HtmlGenericControl htmlliJobCatalogue;
        HtmlGenericControl htmlliRoleAssignment;
        /// <summary>
        /// Initialises logger object
        /// </summary>
        private Microsoft.Practices.SharePoint.Common.Logging.ILogger logger = SharePointServiceLocator.GetCurrent().GetInstance<Microsoft.Practices.SharePoint.Common.Logging.ILogger>();

        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {

            DynamicCareerManagerSubItems();

            HighlightTab();

            SetHyperlinks();
           

        }

       
        #region Private Methods

        /// <summary>
        /// Dynamic Sub Items for Career Manager
        /// </summary>
        /// <returns></returns>
        private void DynamicCareerManagerSubItems()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb currentWeb = currentSite.OpenWeb())
                        {

                            SPList objlist = currentWeb.Lists["TopNavigation"];
                            int i = 0;
                            foreach (SPListItem item in objlist.Items)
                            {
                                htmlliJobCatalogue= new HtmlGenericControl("li");
                                htmlliJobCatalogue.ID = "liJobCatalogue";//nodivider

                                if (i == 0)
                                {
                                    htmlliJobCatalogue.Attributes.Add("class""nodivider");
                                }

                                HtmlGenericControl anchorJobCatalogue = new HtmlGenericControl("a");
                                anchorJobCatalogue.ID = "anchorJobCatalogue";                               
                                anchorJobCatalogue.Attributes.Add("href"Convert.ToString(item["URL"]));
                                anchorJobCatalogue.InnerText = Convert.ToString(item["Title"]);
                                htmlliJobCatalogue.Controls.Add(anchorJobCatalogue);
                                ulCareerManager.Controls.Add(htmlliJobCatalogue);

                                i++;
                            }
                        }
                    }
                });
            }
            catch (ArgumentException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Unable to Create Sub Items under Career Manager",Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (InvalidOperationException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, " Unable to Create Sub Items under Career Manager",Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (Exception ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Unable to Create Sub Items under Career Manager",Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }

        }

        /// <summary>
        /// Highlight Tab by adding class
        /// </summary>
        /// <returns>Query</returns>
        private void HighlightTab()
        {
            try
            {
                string currentPage;
                string URLString = HttpContext.Current.Request.Url.LocalPath.ToString();
                char[] delimiters = new char[] { '\\''?' };
                string[] words = URLString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                int i = words[0].IndexOf("SitePages/");
                currentPage = words[0].Substring(i + 10);

                if (!string.IsNullOrEmpty(currentPage))
                {
                    if ((string.Compare(currentPage, "JobCatalogue.aspx"true)) == 0 || (string.Compare(currentPage, "RoleAssignment.aspx"true)) == 0 ||
                        (string.Compare(currentPage, "LocalRoles.aspx"true)) == 0 || (string.Compare(currentPage, "Role.aspx"true)) == 0 ||
                        (string.Compare(currentPage, "Capability.aspx"true)) == 0 || (string.Compare(currentPage, "CapabilityLevel.aspx"true)) == 0 ||
                        (string.Compare(currentPage, "NewsArticle.aspx"true)) == 0 || (string.Compare(currentPage, "MyLearningWorkSpace.aspx"true)) == 0)
                    {
                        liCareerManager.Attributes.Add("class""active");
                        aCareerManager.Attributes.Add("class""active");
                    }
                    else if ((string.Compare(currentPage, "Capabilities.aspx"true) == 0))
                    {

                        liCapabilities.Attributes.Add("class""active");
                        aCapabilities.Attributes.Add("class""active");

                    }
                    else if ((string.Compare(currentPage, "CommunitiesOfPractice.aspx"true) == 0))
                    {


                        liCommunitiesofPractice.Attributes.Add("class""active");
                        aCommunitiesofPractice.Attributes.Add("class""active");


                    }
                    else
                    {
                        liHome.Attributes.Add("class""active");
                        aHome.Attributes.Add("class""active");

                    }

                }
                else
                {
                    liHome.Attributes.Add("class""active");
                    aHome.Attributes.Add("class""active");

                }
            }
            catch (ArgumentException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Unable To Add the Class"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (InvalidOperationException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, " Unable To Add the Class"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (Exception ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Unable To Add the Class"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }

        }

        private void SetHyperlinks()
        {
            try
            {
                aHome.HRef = SPContext.Current.Web.Url + "/SitePages/Index.aspx";
                aCapabilities.HRef = SPContext.Current.Web.Url + "/SitePages/Capabilities.aspx";
                aCommunitiesofPractice.HRef = SPContext.Current.Web.Url + "/SitePages/CommunitiesofPractice.aspx";
            }
            catch (ArgumentException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Unable to Create Hyperlinks"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (InvalidOperationException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, " Unable to Create Hyperlinks"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (Exception ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Unable to Create Hyperlinks"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }


        }
        #endregion


    }

}



No comments:

Post a Comment