Not able to view result while building Search Query


Hello SharePointers ;),

Here is another quick finding which I just thought should be shared to save someone precious time. If you are dealing with SharePoint 2013 search and Result sources, you must try to test the query template before saving it. If you are not able to see any results instead just a red error saying below text don’t get scared I have quick solution for you.

“The Search display templates are not present on this site collection. To add them, you need to activate the “Search Server Web Parts and Templates” feature on the Site Collection Features page.

Display Error: The display template had an error. You can correct it by fixing the template or by changing the display template used in either the Web Part properties or Result Types.

Template ‘~sitecollection/_Catalogs/masterpage/DisplayTemplates/System/Control_QueryBuilderPreview.js’ not found or has sytax errors. (Load Template: ) ”

Search_Error

You must get frustrated because your search is properly configured, its crawling the data and you are able to see results while searching.  After looking at what was missing I found that in fact there was a feature missing on the Central Administration site collection. The feature is called Search WebParts.

But its not so quick that you just navigate to Site collection feature and activate it. As this feature is present at central admin site collection level so it requires extra privileges to activate it. To fix the problem, simply run the following command in an elevated SharePoint Management Shell:

Enable-SPFeature SearchWebParts -url http://<central admin url>

Bingo!! Just, re-open the “build your query” page, and everything should work properly!

Search_Error

Hope that post was able to help you. Please press like button it that saved your time.

Happy SharePointing 🙂

SharePoint PowerShell: Upload multiple documents to sharepoint document library


Hi,

I was creating a script to replicate document library structure similar to Prod just in order to test the ShareGate Migration. Let me take a brief description about my scenario:

Description:

There is a document library present on Prod, which contains bulk document (~3000). Now I need to update metadata for all those documents using Excel sheet and ShareGate. I don’t have access to the Production library and not even replicate the Library to my Dev environment as it contains some very confidential documents.

Solution:

I have decided to create a script which will take one template document from file system and read name of document from one of columns of excel. The script will take some time(~hours in case of thousand documents) to upload the template with the new file name. The inputs to the script will be

  1. Path of the excel which contains name of documents in one column
  2. Path of the file where the template is placed on file system
  3. Url of the sharepoint web site
  4. Name of the document library

2

Code: 

# Add SharePoint Snapin to PowerShell            
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)             
{            
 Add-PSSnapin Microsoft.SharePoint.PowerShell            
}
$exlFile = "D:\Work\Book2 - Copy.xlsx"
$fileExt = ".pdf"
#$filePath =  "D:\Work\IAEA.docx"  
$filePath = "D:\Work\pdf.pdf"
$webUrl = "http://server/sites/site"            
$docLibName = "Library Name"      

try {    
    $xl = New-Object -COM "Excel.Application"
    #$xl.Visible = $true
    $wb = $xl.Workbooks.Open($exlFile)
    #$ws = $wb.Sheets.Item('Log')
    $ws = $wb.Sheets.Item('Sheet1')
    $lines = $ws.UsedRange.Rows.Count

    $spWeb = Get-SPWeb -Identity $webUrl             
    $spWeb.AllowUnsafeUpdates = $true;            
    $lib = $spWeb.Lists[$docLibName]            
    $folder = $lib.RootFolder            
    #$sourceFileName = $filePath.Substring($filePath.LastIndexOf("\")+1)             
    $file= Get-ChildItem $filePath  
    
    $docLibraryUrl = $lib.RootFolder.ServerRelativeUrl
    $uploadfolder = $spWeb.getfolder($docLibraryUrl + $folderPathWithinDocLibrary)
            
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()     

    for ($line = 2; $line -le $lines; $line ++) {       
        $fileName = $ws.Columns.Item(1).Rows.Item($line).Text
        
        if($fileName -ne "")
        {
            $fileName
            #Check if File exist
            $item = $uploadfolder.Files | where{$_.Name -eq $fileName}
            if(!$item)
            {                
                #Add file            
                write-host -NoNewLine -f yellow "Addin file " $fileName " to " $folder.ServerRelativeUrl "..."                    
                $newFilePath = $docLibraryUrl + $folderPathWithinDocLibrary + "/" + $fileName
                write-host "Creating document: $newFilePath ..."
                $spFile = $uploadfolder.Files.Add($newFilePath, [System.IO.Stream]$fileStream, $true)  
                
                write-host -f Green "...Success!" 
            }
        }
    }
     #Close file stream            
    $fileStream.Close()
    $spWeb.AllowUnsafeUpdates = $false;
    $spWeb.Dispose();
    $xl.Quit()
}
finally { 
    $wb.Close()
    $xl.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
}

Output:

1

Hope that code help you finding solution.

Happy SharePointing 🙂

Mohit Vashishtha

Clear SharePoint Config Cache with PowerShell


Hi,

In my previous post, I have explained about issue “An update conflict has occurred, and you must re-try this action”. That issue occurs because of cache issues. I have already explained the manual way to clear cache. In this blog, I do same thing using the poweshell script. Following code of PowerShell will clear the cache of the server:

Add-PSSnapin -Name Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

Stop-Service SPTimerV4
$folders = Get-ChildItem C:\ProgramData\Microsoft\SharePoint\Config
foreach ($folder in $folders)
{
$items = Get-ChildItem $folder.FullName -Recurse
foreach ($item in $items)
{
if ($item.Name.ToLower() -eq “cache.ini”)
{
$cachefolder = $folder.FullName
}

}
}
$cachefolderitems = Get-ChildItem $cachefolder -Recurse
foreach ($cachefolderitem in $cachefolderitems)
{
if ($cachefolderitem -like “*.xml”)
{
$cachefolderitem.Delete()
}

}

$a = Get-Content  $cachefolder\cache.ini
$a  = 1
Set-Content $a -Path $cachefolder\cache.ini

read-host “Do this on all your SharePoint Servers – and THEN press ENTER”
start-Service SPTimerV4

Thanks and Happy SharePointing 🙂

 

SharePoint: An update conflict has occurred, and you must re-try this action


Hi,

I have faced this issue while trying to modify list items of a list. This issue encounters if the file system cache content on the SharePoint server is newer than the content present in the configuration database. One have to clear the cache manually to get rid of this issue. Sometimes it get solved by restarting, if luck is with you, otherwise this issue will always bugs.

Timer service restart could be one another option to try. But recommend you must follow one of the two possible ways to solve this issue:

I. Manual Steps:

  1. Need to stop the SharePoint Timer service: Navigate to Start > Administrative Tools > Servicesor go to run(Windows+R) command and type msc.
  2. Locate the SharePoint Timer Service, and right click on this service and click on Stop
  3. Close the Services window (In case you are performing these actions on Production/Test. Do this on each front end server)
  4. In Windows Explorer, locate and then double-click the following hidden folder.

Drive:\ProgramData\Microsoft\SharePoint\Config\GUID

Note:

  • There may be two folders with a GUID name in the config directory.  One has persisted files in it.  You will be working with the one that has XML files and a cache.ini file in it. The Drive placeholder specifies the letter of the drive on which Windows is installed. By default, Windows is installed on drive C.
  • The GUID placeholder specifies the GUID folder.
  • The ProgramData folder may be hidden. To view the hidden folder, Navigaete to Tools > Folder Options > View Tab > Advanced settings. Click Show hidden files and folders under Hidden files and folders, and then click OK.
  1. Take a Backup of the ini file.
  2. Delete all the XML configuration files in the GUID folder. Do this so that you can verify that the GUID folder is replaced by new XML configuration files when the cache is rebuilt.

Note When you empty the configuration cache in the GUID folder, make sure that you do not delete the GUID folder and the Cache.ini file that is located in the GUID folder.

  1. Now delete all contents of Cache.ini. Double-click the Cache.ini file to open it. Click on the Edit menu, click Select All and click Delete.
  2. Type 1, and then click Saveon the File menu.
  3. On the Filemenu, click Exit.
  4. Start the Timer service. To do this, follow these steps: Navigate to Start > Administrative Tools > Servicesor go to run(Windows+R) command and type msc.
  5. Locate the SharePoint Timer Service, and right click on this service and click on Start

Note The file system cache is re-created after you perform this procedure. Make sure that you perform this procedure on all servers in the server farm.

  1. Make sure that the Cache.ini file has been updated. For example it should no longer be 1 if the cache has been updated.

II. Clear SharePoint Config Cache with PowerShell.

Both methods does same thing, choice is all yours depending upon the comparability, permissions, time  and of course ease.

Happy SharePointing 🙂

 

Migrate SP list from SP 2010 to SP 2013 without using any tool


Hi guys,

You might asked to migrate SP list from SP 2010 to SP 2013 environment. This question might be asked that why II now didn’t talk about migration of whole site/site collection. Answer is, as there are number of ways one can adopt for migration of whole environment like:

1) Database attache detach(best in case of 2010>2013)

2) Third party tool(best in case of 2007>2013)

But in case of second option you might not face this challenge but when doing database detach attach process there are chances that user continued updating old portal and then after some time client released that they need to re-migrate the list to new server again.

Any ways don’t know real world cases but I got this requirement from client that they want to move four lists from one sub site of old server to new sub site of new server. So I am explaining the way I performed re-migration of list to new server.

The solution is quite simple but some tricks to achieve what we want. Find the following steps:

1) Export Old list:

There are various ways to get the backup of list with content either using PowerShell or  directly from Central admin. Choice depends on user depends on his/her ease. If choice is Central admin then follow the given steps:

a) Navigate to SP 2010 server and open central admin

b) Backup and Restore > Export a site or list.

c) Choose your list, and click Start Export.

Capture

 

If you are PowerShell expert then try using this command:

Export-SPWeb -Identity <SiteURL> -Path <Path and File Name> [-ItemUrl <URL of Site, List, or Library>] [-IncludeUserSecurity] [-IncludeVersions] [-NoFileCompression] [-GradualDelete] [-Verbose]

2) Update the backup files: 

Now this step is quite important as we are not going to change the backup files in order to make compatible for Version 2015 . It is expected that till this point you must be having exported list in to format .cmp file. Copy the this to any convenient location and change the extension to .cab. Extraction can be done by using a software like WinRar or 7zip.

Now, open the SystemData.XML file with an editor like NotePad++ and change the version from 14.0.0.0 to 15.0.0.0 , and the build version from your 14.0.x.x to 15.0.x.x.

Capture

3) Package the files again: 

Backup file is converted in to cab format which can not be used for import the list. There is a freeware available which can be used to create .cab file. Name of that tool is CabPack. Download and install this tool and select your Source and Destination. Change the CabinetNameTemplate if you want, and click on OK.

Capture

Now file extensions have to be changed to .cmp. Simply rename the .cab file created by tool and change the extension from .cab to .cmp.

4) Import the list

Last and final step is to import the file to SP 2013 server and get the list created at new location by just executing one PowerShell command. So start by copying the .cmp file back on the network share or directly on the SharePoint 2013 Server.

Open SharePoint 2013 Management Shell as an administrator. Run this command by changing the parameters of course!

“Import-SPWeb -Identity http://sp2013/ -Path c:\\MyCustomList.cmp -Verbose”

Capture

That All!!

Now open the site contents and check if SP2010 list has been migrated perfectly or not.

Thanks for your time. Happy SharePointing 🙂

 

Powershell: Change Like and comments settings of a library


Hi,

Recently I was working on the requirement to enable the like and comments settings of any library. So I prefer to use PowerShell script for same. I am sharing the code as below:

function Change-SettingsForLikeComment()
{
# Change page library settings for Likes and comments
$list=$web.Lists[“Pages”];
if($list -ne $null)
{
Write-Host $list.Title “not null”;
$assembly=[System.Reflection.Assembly]::Load(“Microsoft.SharePoint.Portal, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”)
$reputationHelper =$assembly.GetType(“Microsoft.SharePoint.Portal.ReputationHelper”);

$bindings = @(“EnableReputation”, “NonPublic”, “Static”);
[System.Reflection.BindingFlags]$flags = [System.Reflection.BindingFlags]::Static -bor [System.Reflection.BindingFlags]::NonPublic;

$methodInfo = $reputationHelper.GetMethod(“EnableReputation”, $flags);

#For enabling Ratings
#$values = @($list, “Ratings”, $false);

#OR for enabling Likes
$values = @($list, “Likes”, $false);

$methodInfo.Invoke($null, @($values));

#For disable Rating or Likes
<#$methodInfo = $reputationHelper.GetMethod(“DisableReputation”, $flags);
$disableValues = @($list);
$methodInfo.Invoke($null, @($disableValues));#>
}
}

 

This code will work for Pages library as in most of the cases we prefer to use pages library as a news library. One just have to create a $web object by using the command:

$url= “<url of your sute>“;
$web=Get-SPWeb $url;

and call the method:

Change-SettingsForLikeComment

Thatz it for now. Thanks for time.

Will be back with more scripts!!

Powershell: Update “Subsite Templates” under AreaTemplateSettings.aspx


Hi,

This time I am discussing about how one can update the “AvailableWebTemplates” once you have created a site. Just for the information, we can define this property in Onet.xml while creating any new site. But what if you have created sites, sub sites underneath and sub sub sites underneath, in that case you need a power shell script to update all those values.

Background: This property is defined in Onet as shown below:

<Feature ID=”22A9EF51-737B-4ff2-9346-694633FE4416″>

—————–

<Property Key=”AvailableWebTemplates” Value=”*-CMSPUBLISHING#0;*-BLANKINTERNET#2;*-ENTERWIKI#0;*-SRCHCEN#0″/>

———————

</Feature>

But once site is created using this site template, we have to dig down to update this. Using power shell its quite easy task provided you must know the Id and template name.

Work Arround:

We using the below mention code we can override the web template property. In order to update that we must know the name of template which we want to update its like CMSPUBLISHING#0 ,it follows the rule of <template name>#<configuration id>. How to get the web template

So after that run the following code in power shell:

$url = ‘http://sgtspweb01/&#8217;

$SPSite = Get-SPSite -Identity $url

foreach ($SPWeb in $SPSite.AllWebs)
{
$SPWeb.AllProperties[“__WebTemplates”] = ‘<webtemplates><lcid id=”all”><webtemplate name=”CMSPUBLISHING#1″ /><webtemplate name=”CMSPUBLISHING#0″ /></lcid></webtemplates>’
$SPWeb.Update();
$SPWeb.Dispose();

write-host “Template ‘” $templateName “‘succesfuly added to web on ” $SPWeb.Url
}

Notice that “__WebTemplates” property stores the value in the xml template, so sometimes you have to just add one template then you must get the existing value of the property first then update it with the desired one.

Some times you may need to know the site template of the existing site. The code to get the title and Id of web template for any site is as follows:

$web = Get-SPWeb http://portal
write-host “Web Template:” $web.WebTemplate ” | Web Template ID:” $web.WebTemplateId
$web.Dispose()

Hope that helped you.

Happy SharePointing :)…