Tuesday, April 23, 2013

Restricting People Picker to search users within site collection


Hi,

We had requirement i.e. if any user searches any user id through people picker, it has to populate only if the user id exists in the current site collection.

For this we have run the below power shell script and we achieved it
Later we have rolled back i.e. if we user searches any user id, people picker should populate if user id exists in Active directory
Through power shell script, we have rolled back as below

Finally script has been delivered as below
//RemovePeoplePickerRestrictions.bat

cd /d %~dp0
@echo off
powershell.exe -noexit .\PSRemovePeoplePickerRestrictions.ps1 .\RemovePeoplePickerRestrictions.csv

//RemovePeoplePickerRestrictions.csv

WebAppUrl
https://webappurl/

//PSRemovePeoplePickerRestrictions.ps1

#///<summary>
#/* Script Name : PSRemovePeoplePickerRestrictions
# * Purpose : Used to remove the peoplepicker restrictions and to connect peoplepicker to AZ AD
#///</summary>

#-----Input parameters to the script
param($inputFile)

#------To check if Sharepoint cmdlets are registered are registered
if ( (Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.Powershell
}
#---------------------------------------------------------------------------------------------------

#-----------------------------------------Start Logging---------------------------------------------
$filepath = $MyInvocation.MyCommand.Definition                                      
$directorypath = [System.IO.Path]::GetDirectoryName($filepath)
$LogTime = Get-Date -Format yyyy-MM-dd_h-mm
$LogFile = $directorypath + "\RemovePeoplePickerRestrictions_Log_$LogTime.txt"
Start-Transcript -Path $LogFile -Force
#---------------------------------------------------------------------------------------------------

#---------------------------------------------------------------------------------------------------
# Function to add the Membership tab to my site
function RemovePeoplePickerRestrictions()
{
    param([string] $webAppUrl)

$WebApp = Get-SPWebApplication -Identity $webAppUrl

if($WebApp -ne $null)
{
Set-Alias -Name stsadm -Value $env:CommonProgramFiles"\Microsoft Shared\Web Server Extensions\14\BIN\STSADM.EXE"

#The following script will remove the restriction from people picker thus search from AZ AD...
stsadm -o setproperty -propertyname peoplepicker-onlysearchwithinsitecollection -propertyvalue "" -url $webAppUrl

#The following script will resolve the users within the site collection
$WebApp1 = Get-SPWebApplication -Identity $webAppUrl
$WebApp1.PeoplePickerSettings.PeopleEditorOnlyResolveWithinSiteCollection = $false;
$WebApp1.Update();
}
else
{
Write-Host 'Not a valid Web application url...'
}
}
#---------------------------------------------------------------------------------------------------

#-----------------------------------------------------------------------------------
#loop through a csv file
Import-Csv $inputFile | ForEach{                            
    $webAppUrl = $_.WebAppUrl
               
    try
    {
write-host "Removing the peoplepicker restrictions from $webAppUrl..."
        RemovePeoplePickerRestrictions $webAppUrl
write-host "Completed..."
    }
    catch
    {
write-host "Completed with errors..."
        Write-Output $_
    }
}
#---------------------------------------------------------------------------------------------------

#-----------------------------------------End Logging-----------------------------------------------
Stop-Transcript
#---------------------------------------------------------------------------------------------------


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


    }

}