Wednesday, August 29, 2012

How to hide top navigation bar links without using Audiences.

EDIT 11/2013: I have come to think that this is just a bad idea.  It works, don't get me wrong, and it may work in your situation (see my many caveats further down in the post), but it's very difficult to maintain / manage, and has the potential to render an entire site useless, if the code starts throwing exceptions.  My plan is to try and do something similar conceptually, but do it all through JSOM in a script file.  That way if the code suffers catastrophic failure, the master page will still load and the site will still be accessible.  In any case, I have left everything as originally posted, for your entertainment.  Proceed at your own risk.

Here is a little technique you can use to hide top navigation bar links from users, based on their membership in SharePoint groups. You won't have to use the User Profile Service to set up Audiences, and you won't have to use the Publishing Infrastructure feature to access the navigation nodes (although you don't really need it anyway), so it may work on SharePoint Foundation as well as Server. (I haven't tested it on Foundation so I'm not positive about that.)

You will, however, have to edit your master page. If you are new to SharePoint, remember that a best practice is to not edit the out-of-the-box master page. Even if you don't currently have a custom master page, to use this technique you should at least make a copy of v4.master and use the copy instead of the original, because you're about to make your master page custom.

Here are a few resources on how to make a copy of v4.master and assign your copy as the new master page in SharePoint:

The idea behind this is pretty simple: we can check a user's group membership using server-side code while the page is still being constructed, but at that point we can't really mess with the top navigation bar.  SharePoint is going to do its thing and load the links in the top nav bar as they are defined in the SPWeb.Navigation.TopNavigationBar node collection on the web, whether we like it or not. But, we can manipulate DOM elements on the client side after the page is rendered. So what we have to do is pass the user authorization information we get on the server side to the client, where we can then act on that information.

The first step in getting all this to work is to include jQuery in your master page so we can use it to remove the links once the page is loaded. Here are a few resources on how to include jQuery on your master page:

fitandfinish.ironworks.com
blogs.msdn.com/b/publicsector
threewill.com

Now that' we've got the jQuery ready, let's look at some code. This should all be included just at the end of the <head> section of the master page.


<script runat="server" type="text/C#"> 
    private Control FindControlRecursive(Control control, string id)
    {
        Control returnControl = control.FindControl(id);
        if (returnControl == null)
        {
            foreach (Control child in control.Controls)
            {
                returnControl = FindControlRecursive(child, id);
                if (returnControl != null && returnControl.ID == id)
                {
                    return returnControl;
                }
            }
        }
        return returnControl;
    }

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

        bool isGroupOneUser = false;
        bool isGroupTwoUser = false;

        try
        {
            int groupOneID = SPContext.Current.Web.Groups["Group One Users"].ID;
            isGroupOneUser = SPContext.Current.Web.IsCurrentUserMemberOfGroup(groupOneID);
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("Group cannot be found")) { /* do nothing */ }
            else
                throw;
        }

        try
        {
            int groupTwoID = SPContext.Current.Web.Groups["Group Two Users"].ID;
            isGroupTwoUser = SPContext.Current.Web.IsCurrentUserMemberOfGroup(groupTwoID);
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("Group cannot be found")) { /* do nothing */ }
            else
                throw;
        }

        if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
        {
            isGroupOneUser = true;
            isGroupTwoUser = true;
        }

        HiddenField groupOneField = new HiddenField();
        groupOneField.Value = isGroupOneUser.ToString().ToUpper();
        groupOneField.ID = "isGroupOneUser";

        HiddenField groupTwoField = new HiddenField();
        groupTwoField.Value = isGroupTwoUser.ToString().ToUpper();
        groupTwoField.ID = "isGroupTwoUser";

        Control topNavBarArea = FindControlRecursive(this, "PlaceHolderTopNavBar");

        topNavBarArea.Controls.Add(groupOneField);
        topNavBarArea.Controls.Add(groupTwoField);
    }
</script>
<script type="text/javascript">
    $(document).ready(function () {
        if ($('input[id*="isGroupOneUser"]').val() == "FALSE") {
            $('span:contains("Link One Title")').closest('li').hide();
        }
        if ($('input[id*="isGroupTwoUser"]').val() == "FALSE") {
            $('span:contains("Link Two Title")').closest('li').hide();
        }
    });
</script>


Did you get all that? No? Ok, let's break it down...

There are two script sections, one is C# code to run server side, and one is jQuery to run client side.  In the server-side section, the first method, FindControlRecursive() is a neat little method I found on StackExchange. It gets used later on when we want to embed a few hidden controls in the page.  The second method is the override of OnLoad(), and that's where we get to work.

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

        bool isGroupOneUser = false;
        bool isGroupTwoUser = false;

First, let the default OnLoad() run its course.  Then, define some boolean variables that will hold the results of the authorization checks.  Because the restricted links should only be revealed if the user is a member of the appropriate group, set these to false initially, in order to prevent anyone from seeing something they shouldn't if there happens to be an error when performing the authorization check.

        try
        {
            int groupOneID = SPContext.Current.Web.Groups["Group One Users"].ID;
            isGroupOneUser = SPContext.Current.Web.IsCurrentUserMemberOfGroup(groupOneID);
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("Group cannot be found")) { /* do nothing */ }
            else
                throw;
        }


Next, check whether the current user is a member of a specific group.  This is done inside a try / catch block in case the group doesn't exist on the site.  Remember, this is the master page, so if we throw an error here we break the entire site, because no pages will be able to load.  Inside the catch block, check to see if it's the particular error of the group not being found on the site.  If that's the case, I've chosen to do nothing, because I want the restricted link to remain hidden even if the group does not exist.  But, you could put isGroupOneUser = true; instead, which would effectively reveal the link to everyone if the group did not exist.  If the error thrown is something other than the group not being found, we want to know about it, so re-throw any other exceptions.

        if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
        {
            isGroupOneUser = true;
            isGroupTwoUser = true;
        }

Lastly, if the user happens to be a site collection administrator, set all the booleans to true no matter what they were set to before, which will reveal all restricted links regardless of whether or not the user belongs to the appropriate groups.  After all, if they're a site collection admin, they should be able to see what's going on with the site, no?

Now that we have our authorization information for the current user, we have to send the information to the client so we can use it.  We do this by embedding some new controls in the page.

        HiddenField groupOneField = new HiddenField();
        groupOneField.Value = isGroupOneUser.ToString().ToUpper();
        groupOneField.ID = "isGroupOneUser";

First make a new hidden field.  Set the value of the field to be the result of the authorization check.  I chose to standardize the result as upper case because later we will be doing a string comparison (since a hidden field stores a string, and not a true boolean), so I want to be sure I know exactly what I'm looking for.  Then set the ID of the field to something unique and meaningful, so jQuery can easily find it later.

        Control topNavBarArea = FindControlRecursive(this, "PlaceHolderTopNavBar");

        topNavBarArea.Controls.Add(groupOneField);
        topNavBarArea.Controls.Add(groupTwoField);

Now that the hidden fields are set with the information we want to pass to the client, use the FindControlRecursive() method to find an appropriate control on the page to add them. In the interest of sanity and organization, since these controls do have to do with manipulating the top nav bar, I chose to add them right to the place where SharePoint is going to add the top nav bar. You can add them anywhere though, just look around on the page and choose a control. Once the control is found, add the hidden fields, and the hand-off is made -- on to the client!

    $(document).ready(function () {
        if ($('input[id*="isGroupOneUser"]').val() == "FALSE") {
            $('span:contains("Link One Title")').closest('li').hide();
        }

In typical jQuery fashion, start by waiting until the page is fully loaded before doing anything. Then, find the hidden field using the ID value set earlier. It might have been possible to use $('#<%=isGroupOneUser.ClientID%>') to find the hidden field, but I decided to go with the attribute contains selector instead, since I wasn't sure when the client ID substitution would happen relative to when the hidden fields were actually added to the page. (I would hate to be trying to substitute the ClientID property of a control that didn't exist yet...) So, find the input control who's ID attribute contains exactly what it was set to in the server side code, and see if the value is false. If so, find the link that should be hidden by finding the span that contains the text visible on the link. Then, traverse up the DOM tree to the closest (in this case, containing) list item element, and hide that element.

Now at this point you might be asking yourself "where the heck did these <span> and <li> elements come from? I want to hide a nav bar link, so shouldn't I be looking for an <a> element?" Well, if we take a look at how SharePoint actually renders the top nav bar controls, you'll see that there is a method to my madness:

<div id="zz16_TopNavigationMenuV4" class="s4-tn">
    <div class="menu horizontal menu-horizontal">
        <ul class="root static">
            <li class="static">
                <a class="static menu-item" href="/url/to/link_one.aspx">
                    <span class="additional-background">
                        <span class="menu-item-text">Link One Title</span>
                    </span>
                </a>
            </li>
            <li class="static">
                <a class="static menu-item" href="/url/to/link_two.aspx">
                    <span class="additional-background">
                        <span class="menu-item-text">Link Two Title</span>
                    </span>
                </a>
            </li>
        </ul>
    </div>
</div>

So as you can see, the <a> element is only a part of what makes up an entire top nav bar link construction. And since none of the elements rendered have ID or name attributes we can hook into to find the correct link with any assurance, I went with finding the text that is the name of the link itself, since I definitely know what that's going to be, because I put them there and named them myself. And even if you weren't the one to create the links in your scenario, you certainly know what they're named just by looking at the top nav bar. So after I find the <span> that contains the specific text that I'm looking for, I traverse up the DOM tree to the highest element that forms a top nav bar link, which happens to be a <li> element. Then I hide that element, in order to hide the whole construction.

And it works like a charm -- all the other links slide over so there's no gaps or odd spacing, everything stays ril ril purty.

Keep in mind though, this technique may not work well in every scenario, so YMMV. In my case, it was a very stable environment, meaning: we built it once and that's the way it's going to stay.  There's one master page used everywhere, there are not going to be a lot of team collaboration sites (or any sites, for that matter) being created or deleted by the end users as they need, and no one is going to be adding or removing top nav bar links willy-nilly.  If there's a lot of dynamism to your environment and these links are going to come and go, or if you have multiple different master pages, this may not be the right technique for you, since any changes that have to be made to the behavior of hiding the links has to be made on the master page itself, which could translate into a lot of administrative overhead. But if you only have one master page, and the links you need in the top nav bar are likely not to change very often, this might work for you.