Dynamic Table of Contents on SharePoint Wiki Page

In my earlier blog “Add Bookmark on SharePoint page for Table of contents” I explained how to add book mark to create table of contents so that we can navigate to the respective content on click of the link in Table of contents.

But then problem was, if we have multiple headers and all needs to be listed in Table of Contents then we have do manually for each link and add Bookmarks. If there are multiple pages with multiple headers in each page then its going to take lot of time. So we were asked to implement something that will put the header from each section and puts it in the Table of Contents. After googling for a while I got multiple articles but they all were for site pages but ours were wiki pages. Then by using the code from one article and modified it to work for Wiki pages and below is the working code.

Below code takes the content inside the header tags (h1,h2,h3,h4) and places them in the Table of contents. Place the below code in Content editor.

JQuery –


function GenerateTOC() {

<div id="tocHeader">Table of Contents</div>
 //$(".ms-wikicontent h1, .ms-wikicontent h2, .ms-wikicontent h3, .ms-wikicontent h4").each(function(i) { 
 $("h1, h2, h3, h4").each(function(i) {

var currentNode = $(this);

currentNode.attr("id", "title" + i);
var linkClass;

linkClass = "toc_Level1"

linkClass = "toc_Level2"

linkClass = "toc_Level3"

linkClass = "toc_Level4"

var text = currentNode.html();
text = text.replace("
", "");

if (text.trim())
 $("#toc").append("<a id='link" + i + "' class='" + linkClass + "' href='#title" + i + "' title='" + currentNode.attr("tagName") + "'>" + text + "</a>





<div id="toc"></div>


#toc {

display: table;

border: 1px solid #aaa;

background-color: #f9f9f9;

font-size: 15px;

padding: 7px;


#toc #tocHeader {

font-size: 18px;

font-weight: bold;

text-align: left;


#toc a:before { /* content:"• "; */ }

#toc a { line-height: 10px; margin: 5px; }

#toc .toc_Level1 { margin-left: 5px !important; }

#toc .toc_Level2 { margin-left: 10px !important; }

#toc .toc_Level3 { margin-left: 25px !important; }

#toc .toc_Level4 { margin-left: 35px !important; }

Place all the code in a .js file and refer that file in the Content editor web part.





Breadcrumb using Java/JQuery, HTML and css (SharePoint)

Requirement: To create the breadcrumb which shows the location of the current page on top and user should be able to navigate to any parent page from the current page. All were pages here, so we had to show the navigation of the pages than the site hierarchy.

We implemented a custom bread crumb as shown below using JQery, HTML and CSS.



Since the navigation path for all pages was static, we

  • Stored the navigation details in a list as shown below (Page name and the navigation path to that page)
  • List name used – “BreadCrumbList”, you can change it to anything. Change the name in the code as well.


Note: Page name in the above list and actual page name should be same

  • Then on the respective page, we processed the current link for retrieving the page name
  • By using the page name retrieved above, queried the list get the navigation path and display it on the page

Below is the code

  • Add a content editor web part or the script editor on the page and add the below code.

JQuery –

$(document).ready(function () {

function LoadBreadCrumb()
// Get current page Name
var currentPage = document.location.href;
var s = currentPage.split("/");
var i = s.length-1var currentPageName = s[i];
currentPageName=currentPageName.replace(/\%20/gi, ' ');
currentPageName=currentPageName.replace(/\.aspx/gi, '');
var webURL=_spPageContextInfo.webAbsoluteUrl +"/_api/web/lists/getbytitle('BreadCrumbList')/items/?$select=PageURL&amp;$filter=Title eq '"+currentPageName+"'"; 

url: webURL,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
if(data!='undefined' &amp;&amp; data!='')
 var items = data.d.results;
for(var i = 0; i &lt; items.length;i++)
pagePath = items[i].PageURL;
var path = &quot;&quot;;
var href = &quot;https://off365poc.sharepoint.com/sites/NewSite/SitePages/&quot;;
var s = pagePath.split(&quot;/&quot;);
for (var i=0;i&lt;(s.length);i++)
if(s[i]!=&#039;undefined&#039; &amp;&amp; s[i]!=&#039;&#039;)
var url = path;
breadcrumb.innerHTML = url;
} },
error: function (error) { console.log(JSON.stringify(error)); }


<ul id="breadcrumb" class="breadcrumb"></ul>


ul.breadcrumb {
padding: 10px 16px;
list-style: none;
background-color: #eee;
ul.breadcrumb li {
display: inline;
font-size: 18px;
ul.breadcrumb li+li:before {
padding: 8px;
color: black;
content: "/\00a0";
ul.breadcrumb li a {
color: #0275d8;
text-decoration: none;
ul.breadcrumb li a:hover {
color: #01447e;
text-decoration: underline;

Hope this will help.




How to Add Table of Contents on SharePoint page using bookmarks

Requirements – To navigate to the respective content section from the Table of Contents  placed on a SharePoint page. We had lot of content on the page and that content was indexed in the table of contents as shown below. Now when user clicks on the topic, he should be taken to the respective section on the page.


It can be achieved using “Book Marks” property of Link.


  • Edit the page
  • Go to the header of the content
  • Select the Header and click on INSERT -> link -> From Address as shown below


  • In the address give the current page link and click on OK
  • Add bookmark in link properties as shown below (without a hash tag)


  • Go back to the Table of contents on top
  • Select the topic name and click on INSERT -> Link -> From address
  • In address, give the current page address and append with same bookmark name as above with the hash tag e.g. #Verification (shown below)


  • And then save the page.

Now, When you click on Verification, it will take you to the verification content.



Enjoy learning.








SharePoint Search – Reset Index error “Sorry, something went wrong, request time out. “

Error – “Sorry, something went wrong, request time out. ”

Follow below steps –

  1. Start -> Run -> Services.msc
  2. Select and right click on “SharePoint Timer Service”.
  3. Select properties.
  4. Go to the Recovery tab and set all the Failures to “Take No Action”. This is very important.
  5. Stop “SharePoint Timer Service:” service.
  6. Do this for all SharePoint servers in the farm.
  7. Find the cache folder. It’s usually somewhere like C:\ProgramData\Microsoft\SharePoint\Config. Just do a search for the file cache.ini and that will be the right folder.
  8. Delete all the files in that folder EXCEPT Cache.ini.
  9. Open Cache.ini with Notepad and change the number to 1. You can make note of that number for later if you wish.
  10. Do this for all the SharePoint servers in the farm.
  11. No go back and turn on the “SharePoint Timer Service” on all the servers. You can put back the Failures their previous state at this time, too.
  12. Take a look in the cache folders and make sure they are filling up with new files. If you are ultra paranoid, you can compare the cache.ini number to the one you saved and make sure they are the same.

Try doing the Reset Index again and it should work.


Search has encountered a problem that prevents results from being returned. If the issue persists, please contact your administrator.

Error – Search has encountered a problem that prevents results from being returned. If the issue persists, please contact your administrator.


After searching in the internet, found this article helpful –


Ran below commands to check if the search index partition is degraded on the search.

$searchApp= Get-SPEnterpriseSearchServiceApplication

Get-SPEnterpriseSearchStatus –SearchApplication $searchApp[0].Name


And found that Search index partition is degraded.

Then reset the index on the central admin


After Index reset and the full crawl, search started working perfectly.

Thank you Purna for saving my day…


PowerShell – Upload user pictures to AD and user profile

Below script helps to upload pictures to AD

[Code type=”PowerShell”]
function Upload-PhotosToSP

if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
Write-Host “Loading SharePoint assemblies…”
Add-PsSnapin Microsoft.SharePoint.PowerShell

#Get site, web and profile manager objects
$LocalPath = “C:\Scripts\UPLOAD-ProfilePhotos\picture library test\”
$MySiteUrl = “http://mySite.com:82/&#8221;
$mySiteHostSite = Get-SPSite $MySiteUrl
$mySiteHostWeb = $mySiteHostSite.OpenWeb()
$context = Get-SPServiceContext $mySiteHostSite
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
#Get files from local folder
$localPhotosFolder = Get-ChildItem $LocalPath
#Get User Photos document library in the My Site host site
$spPhotosFolder = $mySiteHostWeb.GetFolder(“User Photos”)

#Upload each image file and configure user profiles
$localPhotosFolder | ForEach-Object {

#Generate file path for upload into SharePoint
$spFullPath = $spPhotosFolder.Url + “/” + $_.Name
#$Overwrite= true
$FilePath = $LocalPath + $_.Name

#Check if the file exists and the overwrite option is selected before adding the file
#if ((!$mySiteHostWeb.GetFile($spFullPath).Exists) -or ($Overwrite)) {
#Add file to the User Photos library
write-host “Copying” $_.Name “to” $spFullPath.Replace(“/” + $_.Name,””) “in” $mySiteHostWeb.Title “…” -foregroundcolor Green
$spFile = $spPhotosFolder.Files.Add($spFullPath, $_.OpenRead(), $true)
$spImagePath = $mySiteHostWeb.Url + “/” + $spFile.Url

#Get the domain and user name from the image file name
$domainName = $_.Name.Split(“_”)[0]
$userName = $_.Name.Split(“_”)[1].Replace($_.Extension, “”)
$adAccount = $domainName + “\” + $userName

#Check to see if user profile exists
if ($profileManager.UserExists($adAccount))
#Set picture in AD also
$image = [Byte[]](Get-Content $FilePath -Encoding byte)
Set-ADUser -Identity $userName -replace @{thumbnailPhoto=$image}
Set-ADUser -Identity $username -replace @{jpegPhoto=$image}
write-host “Uploading” $_.Name “picture to AD ” -foregroundcolor Green

#Get user profile and change the Picture URL value
$up = $profileManager.GetUserProfile($adAccount)
$up[“PictureURL”].Value = $spImagePath
write-host “Profile for user”$adAccount “cannot be found”
# write-host “`nFile”$_.Name “already exists in” $spFullPath.Replace(“/” + $_.Name,””) “and shall not be uploaded” -foregroundcolor Red

#Run the Update-SPProfilePhotoStore cmdlet to create image thumbnails and update user profiles
write-host “Waiting to update profile photo store – Please wait…”
Start-Sleep -s 60
Update-SPProfilePhotoStore –MySiteHostLocation $MySiteUrl
write-host “Profile photo store update run – please check thumbnails are present in Profile Pictures folder.”
write-host “The script has stopped because there has been an error: “$_
#Dispose of site and web objects


PowerShell – DownLoad pictures from SharePoint

Below script helps to download the files from SharePoint library.

[Code type=”PowerShell”]

Remove-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

######################## Variables #####################
$destination = “C:\Scripts\UPLOAD-ProfilePhotos\”
$webUrl = “http://mySite/IntranetServices/&#8221;
$listUrl = “http://mySite/IntranetServices/pictures/&#8221;

$web = Get-SPWeb -Identity $webUrl
$list = $web.GetList($listUrl)
function parseUser([string] $m ){
# function takes a lastname, firstname MI string and parses to match manager info. returns email address.

if ($m -ieq “”)
return $null
$split = $m.split(” “)
$fn = $split[0]
$ln = $split[1]
#$splitfn = $fnmi.split(” “)
#$fn = $splitfn[1]
$fi = $fn.substring(0,1)
$em = $fi + $ln #+ “@healthgrades.com”
#$validatedManager = checkManager($em)
return $em

function DownLoadImages($folderUrl)
$folder = $web.GetFolder($folderUrl)
foreach ($file in $folder.Files)
$UserID = parseUser($file.Name)
$UserID = “_” + $UserID

#Ensure destination directory
$destinationfolder = $destination + “/” + $folder.Url
if (!(Test-Path -path $destinationfolder))
$dest = New-Item $destinationfolder -type directory
#Downloading file
$binary = $file.OpenBinary()
$stream = New-Object System.IO.FileStream($destinationfolder + “/” + $UserID), Create
$writer = New-Object System.IO.BinaryWriter($stream)
#Download root files
#Download files in folders
foreach ($folder in $list.Folders) {
write-host $_.exception
if($web -ne $null)



WorkFlow Error: The root of the certificate chain is not a trusted root authority

Error while running the command “Register-SPWorkflowService” in SharePoint 2013

I was not getting SharePoint 2013 workflow template type in SharePoint Designer 2013, so configured workflow manager and was trying to register SPWorkflowService by running below command but received below error .

Command – Register-SPWorkflowService –SPSite “http://server/sites/” –WorkflowHostUri “https://server:12290/”


did multiple trial and errors but nothing worked, then got the solution in below blog.


Steps –

There are 2 things to check.

  1. Check if the WorkflowHostUri is having a Fully Qualified Domain (FQD) instead of machine name.
  2. Check if the SharePoint server trusts the workflow site’s certificate

1. Use FQD. Hence instead of using machine name for WorkflowHostUri, use full domain name, like https://wfserver.domain.com:12290/
2. Make sure the SharePoint Server trusts the certificate of Workflow site. For that do the following

  1. In the server browse the site https://wfserver.domain.com:12290/ and check if you get Certificate trust error, if so proceed to next point
  2. Start Management Power Shell as Administrator in the workflow server and run the following 2 commands
  3. $rootCert = (Get-SPCertificateAuthority).RootCertificate
  4. $rootCert.Export(“Cert”) | Set-Content C:\SharePointRootAuthority.cer -Encoding byte
  5. Navigate to the SharePoint Server and open run or command prompt and type MMC and hit Enter. This will open Console1.
  6. In Console1 navigate to file in the ribbon menu and select “Add/Remove snap-in”
  7. Add “Certificates” to the right hand side and then click “OK”. You will prompted with the Certificates snap-in. I selected “Computer account”>Next>Local computer>Finish>OK
  8. Import the certificate “C:\SharePointRootAuthority.cer” into “Trusted root certification authority” location. You can complete this by right clicking on “Trusted root certification authority” and selecting All Tasks > Import
  9. Then run the register command again and check the Designer for SharePoint 2013 template.

Register-SPWorkflowService -SPSite “http://server/site ” -WorkflowHostUri “http://server:12290/” -AllowOAuthHttp -Force -ScopeName “SharePoint”

Enjoy exploring…


Workflow error – System.InvalidOperationException: Operation failed with error Microsoft.Workflow.Client.ScopeNotFoundException: Scope ‘/SharePoint/default’ was not found. HTTP headers received from the server – ActivityId: . NodeId: server1. Scope: /SharePoint/default/. Client ActivityId : . —> System.Net.WebException: The remote server returned an error: (404) Not Found. at Microsoft.Workflow.C

Error – In SharePoint 2013 on premises, I was trying to publish the workflow and received below error

“System.InvalidOperationException: Operation failed with error Microsoft.Workflow.Client.ScopeNotFoundException: Scope ‘/SharePoint/default’ was not found.  HTTP headers received from the server – ActivityId: 0f2a45dd-abc8-4c5b-bd44-229f27e1090a. NodeId: server1. Scope: /SharePoint/default/c02de6f4-c3ce-405b-8d51-3be3fbf0755a. Client ActivityId : 7c53c79d-f6f8-a073-cc84-45a75a835626. —> System.Net.WebException: The remote server returned an error: (404) Not Found.    at Microsoft.Workflow.C”

Solution: Register the workflow by setting the scope as shown below and it worked like a charm 🙂


Steps – Open SharePoint 2013 Management shell and run below command to register the workflow by setting the scope.

Register-SPWorkflowService -SPSite “http://server/site ” -WorkflowHostUri “http://server:12291/” -AllowOAuthHttp -Force -ScopeName “SharePoint”

Thank you so much to Karthick https://social.msdn.microsoft.com/Forums/sharepoint/en-US/fe913695-fb3e-4b5a-a229-f5bcd80fbbc9/sharepoint-2013-workflow-error?forum=sharepointcustomization

Enjoy learning…




Error – Import-Csv : Exception setting “Replace”: Object reference not set to an instance of an object

While running a Powershell script, faced below problem. If you get the same issue, check the CSV header names which you have used in Powershell to retrieve the csv data. Referring to a wrong name doesn’t give any error but throws error when you perform any action that variable.


$supervisor = $_.Supervisor
$dept = $_.Dept

Error powershell-error1