How to Update the Taxonomy Field (Single Value or Multiple Value) using C# Patterns and Practices in SharePoint Office 365

Sathish Nadarajan
 
Solution Architect
February 11, 2018
 
Rate this article
 
Views
16100

In the earlier article, we saw how to create the terms in the Termstore and subsequently, now, we are going to update the List Item with the new terms created.

The below piece of code will update the Single Value Managed Metadata Column with the newly created Terms. The EnsureTerms method, I request the readers to go to the earlier article.

 public static void AddTaxonomyEntry()
         {
             try
             {
                 OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
                 string siteUrl = "https://*****.sharepoint.com/sites/DeveloperSite";
                 string userName = "Sathish@*********.onmicrosoft.com";
                 string password = "******";
 
                 using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                 {
                     Web web = ctx.Web;
                     ctx.Load(web);
                     ctx.Load(web.Lists);
                     ctx.ExecuteQueryRetry();
                     List list = web.Lists.GetByTitle("List1");
                     ctx.Load(list);
                     ctx.ExecuteQueryRetry();
 
                     var tags = new string[] { "Term2"};
 
                     var tagsString = EnsureTerms(tags, siteUrl, list.Id, "TaxonomyField",ctx);
 
 
                     ListItem listItem = list.AddItem(new ListItemCreationInformation());
                     listItem["Title"] = "Test Title";
                     listItem.Update();
 
                     ctx.Load(listItem);
                     ctx.ExecuteQuery();
 
                     var clientRuntimeContext = listItem.Context;
                     
                     var field = list.Fields.GetByInternalNameOrTitle("TaxonomyField");
                     var taxKeywordField = clientRuntimeContext.CastTo<TaxonomyField>(field);
 
                     TaxonomyFieldValue termValue = new TaxonomyFieldValue();
                     string[] term = tagsString.Split('|');
                     termValue.Label = term[0];
                     termValue.TermGuid = term[1];
                     termValue.WssId = -1;
                     taxKeywordField.SetFieldValueByValue(listItem, termValue);
 
                     taxKeywordField.Update();
 
                     listItem.Update();
                     ctx.Load(listItem);
                     ctx.ExecuteQuery();
                 }
             }
             catch (Exception ex) { }
         }
 
 

This will update the Taxonomy Field.

To update the Multi Value Taxonomy Field, the below lines needs to be replaced.

 //TaxonomyFieldValue termValue = new TaxonomyFieldValue();
                     //string[] term = tagsString.Split('|');
                     //termValue.Label = term[0];
                     //termValue.TermGuid = term[1];
                     //termValue.WssId = -1;
                     //taxKeywordField.SetFieldValueByValue(listItem, termValue);
 
                     taxKeywordField.SetFieldValueByValueCollection(listItem, new TaxonomyFieldValueCollection(clientRuntimeContext, tagsString, taxKeywordField));
                     taxKeywordField.Update();
 

Happy Coding,

Sathish Nadarajan.

Category : CSOM, Office 365, PNP, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Update the Shared Data Source Information of a RDL RDLX files in SharePoint using PowerShell Script

Sathish Nadarajan
 
Solution Architect
January 22, 2018
 
Rate this article
 
Views
3440

In the earlier article, we saw how to read the Data Source and Update the Custom Data Sources. In this article, let us see how to update the Shared Data Source using PowerShell Script.

The below script is self-explanatory.

# This script will update the Shared data source info for all the reports in a document library

 # This script will update the Shared data source info for all the reports in a document library 
 
 ##================================================================================================
 ## Description	: 
     #This script will update the Shared data source info for all the reports in a document library 
  
 ## Author		: Sathish Nadarajan
 ## Date			:  
 ##================================================================================================
 
 # ============================================ Setup Input Paths ================================= 
 
 cls
 
  
 $Host.UI.RawUI.WindowTitle = "-- Update Data Source for Reports Library --"
 
 $StartDate = Get-Date
 Write-Host -ForegroundColor White "------------------------------------"
 Write-Host -ForegroundColor White "| Update the reports file with datasource url |"
 Write-Host -ForegroundColor White "| Started on: $StartDate |"
 Write-Host -ForegroundColor White "------------------------------------"
 
 $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
 
 ################# Set the Current Path as Execution Path ####################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 Set-Location $scriptBase
 
 ############# set the Error Preference ################
 
 $ErrorActionPreference = "SilentlyContinue"
 
 
 # Create Log File Folder
 if(!(TEST-PATH ".Logs-$LogTime")) 
 {
    NEW-ITEM ".Logs-$LogTime" -type Directory
 }
 
 
 
  # Assign the Log and Progress Files
 $TranscriptFile = ".Logs-$LogTimeGetSiteInfo.Transcript.rtf"
 $ProgressFile = ".Logs-$LogTimeGetSiteInfo.Progress.rtf"
 
 try{
   stop-transcript|out-null
 }
 catch [System.InvalidOperationException]{}
 
 start-transcript $TranscriptFile
 
 
 function AddCSOM(){
      #Load SharePoint client dlls 
      $a = [System.Reflection.Assembly]::LoadFile(    "$scriptBaseClientLibrariesMicrosoft.SharePoint.Client.dll") 
      $ar = [System.Reflection.Assembly]::LoadFile(    "$scriptBaseClientLibrariesMicrosoft.SharePoint.Client.Runtime.dll") 
      
      if( !$a ){
          $a = [System.Reflection.Assembly]::LoadWithPartialName(        "Microsoft.SharePoint.Client")
      }
      if( !$ar ){
          $ar = [System.Reflection.Assembly]::LoadWithPartialName(        "Microsoft.SharePoint.Client.Runtime")
      }
      
      if( !$a -or !$ar ){
          throw         "Could not load Microsoft.SharePoint.Client.dll or Microsoft.SharePoint.Client.Runtime.dll"
      }
      
      
      #Add overload to the client context.
      #Define new load method without type argument
      $csharp =     "
       using Microsoft.SharePoint.Client;
       namespace SharepointClient
       {
           public class PSClientContext: ClientContext
           {
               public PSClientContext(string siteUrl)
                   : base(siteUrl)
               {
               }
               // need a plain Load method here, the base method is a generic method
               // which isn't supported in PowerShell.
               public void Load(ClientObject objectToLoad)
               {
                   base.Load(objectToLoad);
               }
           }
       }"
      
      $assemblies = @( $a.FullName, $ar.FullName,     "System.Core")
      #Add dynamic type to the PowerShell runspace
      Add-Type -TypeDefinition $csharp -ReferencedAssemblies $assemblies
 }
 
 
 AddCSOM
 
 $credentials = Get-Credential
 
  
 
 
 cls
 
  
     
     Write-Host "Processing the Site : " "https://mysitecollection" -ForeGroundColor Yellow
         
     $context = New-Object SharepointClient.PSClientContext("https://mysitecollection")
    
      
     $context.Credentials = $credentials
     
     #Load the basic information about the web and site
     $context.Load($context.Web)
     $context.Load($context.Site)
     $context.Load($context.Web.Lists)
     $context.ExecuteQuery()
 
     #SSRS
     $SSRSurl = "$($context.Web.Url)/_vti_bin/ReportServer/ReportService2010.asmx"; 
     $SSRS = New-WebServiceProxy -uri $SSRSurl -UseDefaultCredential; 
 
     $($ssrs.url); 
 
     # Iterate through the Lists
     foreach ($list in $context.Web.Lists) 
     {
         #Load the information about the List
         $context.Load($list)
         $context.Load($list.BaseType)
         $context.Load($list.Items)
         $context.ExecuteQuery()
         
         
         # validate for Document Library
         if ($list.BaseType -eq “DocumentLibrary”) 
         {
           
             $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
             $camlQuery.ViewXml ="<View Scope='RecursiveAll' />";
             $allItems=$list.GetItems($camlQuery)
             $context.Load($allItems)
             $context.ExecuteQuery()
            
             foreach($item in $allItems)
             {
                 if($item.FileSystemObjectType -eq "File")
                 {
                     $file = $item.File
                     $fItem = $file.ListItemAllFields
                     $context.Load($file)
                     $context.Load($fItem)
                                    
                     $context.ExecuteQuery()    
                      
                      #Read .rdl files available in the library  
                       
                       if($file.Name.ToLower().Contains(".rdl") -or $file.Name.ToLower().Contains("rdlx"))
                        
                        {                   
                         $fullURL = 'https://mysitecollection' + $file.ServerRelativeUrl
                         $dataSources = $SSRS.GetItemDataSources($fullURL); 
                         Write-Host "Count : "  $dataSources.Count
 
                         if ($datasources.count -gt 0)
                         { 
                             for ($i = 0; $i -lt $dataSources.count; $i++) 
                             { 
                                    
                                   #The below Lines will update the Shared Data  Source
                                   $proxyNamespace = $DataSources[$i].GetType().Namespace; 
                                   $DataSources[$i].Item = New-Object ("$proxyNamespace.DataSourceReference"); 
                                   $DataSources[$i].Item.Reference = "https://mysitecollection/documentlibrary/RSDSFile.rsds";
                                   $SSRS.SetItemDataSources($fullURL, $DataSources[$i]) 
                                   write-output "Done";
                                     
                                  
 
                 }
                  
             }
           
         
          }
                    
        }
      }
     }
        
   }
        
    
  
 
  try{
   stop-transcript|out-null
 }
 catch [System.InvalidOperationException]{}   
 

Happy Coding,

Sathish Nadarajan.

Category : CSOM, PowerShell, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Update the Custom Data Source Information of a RDL RDLX files in SharePoint using PowerShell Script

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Views
2839

 

In the earlier article, we saw how to read the Data Source. In this article, let us see how to update the Custom Data Source using PowerShell Script.

The below script is self-explanatory.

 # This script will update the data source info for all the reports in a document library 
 
 ##================================================================================================
 ## Description	: 
     #This script will update the data source info for all the reports in a document library 
  
 ## Author		: Sathish Nadarajan
 ## Date			: 
 ##================================================================================================
 
 # ============================================ Setup Input Paths ================================= 
 
 cls
 
  
 $Host.UI.RawUI.WindowTitle = "-- Update Data Source for Reports Library --"
 
 $StartDate = Get-Date
 Write-Host -ForegroundColor White "------------------------------------"
 Write-Host -ForegroundColor White "| Update the reports file with datasource url |"
 Write-Host -ForegroundColor White "| Started on: $StartDate |"
 Write-Host -ForegroundColor White "------------------------------------"
 
 $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
 
 ################# Set the Current Path as Execution Path ####################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 Set-Location $scriptBase
 
 ############# set the Error Preference ################
 
 $ErrorActionPreference = "SilentlyContinue"
 
 
 # Create Log File Folder
 if(!(TEST-PATH ".Logs-$LogTime")) 
 {
    NEW-ITEM ".Logs-$LogTime" -type Directory
 }
 
 
 
  # Assign the Log and Progress Files
 $TranscriptFile = ".Logs-$LogTimeTranscript.rtf"
 $ProgressFile = ".Logs-$LogTimeProgress.rtf"
 
 try{
   stop-transcript|out-null
 }
 catch [System.InvalidOperationException]{}
 
 start-transcript $TranscriptFile
 
 
 function AddCSOM(){
      #Load SharePoint client dlls 
      $a = [System.Reflection.Assembly]::LoadFile(    "$scriptBaseClientLibrariesMicrosoft.SharePoint.Client.dll") 
      $ar = [System.Reflection.Assembly]::LoadFile(    "$scriptBaseClientLibrariesMicrosoft.SharePoint.Client.Runtime.dll") 
      
      if( !$a ){
          $a = [System.Reflection.Assembly]::LoadWithPartialName(        "Microsoft.SharePoint.Client")
      }
      if( !$ar ){
          $ar = [System.Reflection.Assembly]::LoadWithPartialName(        "Microsoft.SharePoint.Client.Runtime")
      }
      
      if( !$a -or !$ar ){
          throw         "Could not load Microsoft.SharePoint.Client.dll or Microsoft.SharePoint.Client.Runtime.dll"
      }
      
      
      #Add overload to the client context.
      #Define new load method without type argument
      $csharp =     "
       using Microsoft.SharePoint.Client;
       namespace SharepointClient
       {
           public class PSClientContext: ClientContext
           {
               public PSClientContext(string siteUrl)
                   : base(siteUrl)
               {
               }
               // need a plain Load method here, the base method is a generic method
               // which isn't supported in PowerShell.
               public void Load(ClientObject objectToLoad)
               {
                   base.Load(objectToLoad);
               }
           }
       }"
      
      $assemblies = @( $a.FullName, $ar.FullName,     "System.Core")
      #Add dynamic type to the PowerShell runspace
      Add-Type -TypeDefinition $csharp -ReferencedAssemblies $assemblies
 }
 
 
 AddCSOM
 
 $credentials = Get-Credential
  
 
 
 cls
 
 
     
     Write-Host "Processing the Site : " "https://mysitecollection" -ForeGroundColor Yellow
         
     $context = New-Object SharepointClient.PSClientContext("https://mysitecollection")
    
      
     $context.Credentials = $credentials
     
     #Load the basic information about the web and site
     $context.Load($context.Web)
     $context.Load($context.Site)
     $context.Load($context.Web.Lists)
     $context.ExecuteQuery()
 
     #SSRS Proxy
     $targeturl="$($context.Web.Url)/_vti_bin/ReportServer/ReportService2010.asmx";
     $targetProxy = New-WebServiceProxy -Uri  $targeturl -UseDefaultCredential;
 
     $targetNS = $targetProxy.GetType().Namespace
     $targetDataType = $targetNS + '.DataSourceDefinition'
    
 
     # Iterate through the Lists
     foreach ($list in $context.Web.Lists) 
     {
         #Load the information about the List
         $context.Load($list)
         $context.Load($list.BaseType)
         $context.Load($list.Items)
         $context.ExecuteQuery()
         
         
         # validate for Document Library
         if ($list.BaseType -eq “DocumentLibrary”) 
         {
           
             $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
             $camlQuery.ViewXml ="<View Scope='RecursiveAll' />";
             $allItems=$list.GetItems($camlQuery)
             $context.Load($allItems)
             $context.ExecuteQuery()
            
             foreach($item in $allItems)
             {
                 if($item.FileSystemObjectType -eq "File")
                 {
                     $file = $item.File
                     $fItem = $file.ListItemAllFields
                     $context.Load($file)
                     $context.Load($fItem)
                                    
                     $context.ExecuteQuery()    
                      
                      #Read .rdl files available in the library  
                       
                       if($file.Name.ToLower().Contains(".rdl") -or $file.Name.ToLower().Contains("rdlx"))
                        
                        {                   
                         $fullURL = 'https://MySiteCollection.nee.com' + $file.ServerRelativeUrl
                         $dataSources = $targetProxy.GetItemDataSources($fullURL)
                         Write-Host "Count : "  $dataSources.Count
 
                         foreach($dataSource in $dataSources)
                         {
                             Write-Host $dataSource.Name
                             Write-Host $dataSource.Item.ConnectString
 
                              #The below line is where actual updation is happening
                                         $dataSource.item.ConnectString = "Updated Connection String Value"
                                         $targetProxy.SetItemDataSources($fullURL, $dataSource)
                                    
                                   
                         }
         
                        }
                    
                     }
                }
             }
        
         }
    
    
    
 
 
  try{
   stop-transcript|out-null
 }
 catch [System.InvalidOperationException]{}   
 

Happy Coding,

Sathish Nadarajan.

Category : CSOM, PowerShell, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Update Navigation (Quick Launch and Top NavigationBar) URLs in SharePoint 2010 using PowerShell CSOM

Sathish Nadarajan
 
Solution Architect
December 28, 2017
 
Rate this article
 
Views
5606

During the Migration from SP2010 to SP2016, if the Quick Launch or the Top Navigation of the Source Sites were having the Full URL, (e.g., https://mySP2010Site.com/Sites/SiteCollection/MyList/Forms/AllItems.aspx), then any Migration tool will migrate the Navigation URLs as it is. Hence, in the Target, if we click on the Link, then it will go to the Source Link, not the Target Link. For that, before migrating the content, we can update the URLs with relating Path. i.e., /sites/sitecollection/MyList/Forms/AllItems.aspx. By doing this, when we migrate, the Target will also have the relative path which will be the corresponding target site collection’s path. Though this may not work for different web applications/different tenants, but somehow this will fix the initial problem statement.

Let us see the detailed script, which will update the Quick Launch and the Navigation Bars using PowerShell CSOM in SP2010 Environment. The below script, I wrote it for two levels only. We can make the update statement as a recursive method, so that it will update any level of the Links.

 # Update the Navigation (QuickLaunch and TopNavigationBar) URLs
 
 ##================================================================================================
 ## Description	: 
     #Update the Navigation (QuickLaunch and TopNavigationBar) URLs
  
 ## Author		: Sathish Nadarajan
 ## Date			: 
 ##================================================================================================
 
 # ============================================ Setup Input Paths ================================= 
 
 cls
 
  
 $Host.UI.RawUI.WindowTitle = "-- Update QuickLaunch and TopNavigationBar URLs--"
 
 $StartDate = Get-Date
 Write-Host -ForegroundColor White "------------------------------------"
 Write-Host -ForegroundColor White "| Update QuickLaunch and TopNavigationBar URLs |"
 Write-Host -ForegroundColor White "| Started on: $StartDate |"
 Write-Host -ForegroundColor White "------------------------------------"
 
 $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
 
 ################# Set the Current Path as Execution Path ####################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 Set-Location $scriptBase
 
 ############# set the Error Preference ################
 
 $ErrorActionPreference = "SilentlyContinue"
 
 # Create Log File Folder
 if(!(TEST-PATH ".Logs-$LogTime")) 
 {
    NEW-ITEM ".Logs-$LogTime" -type Directory
 }
 
 # Assign the Log and Progress Files
 $TranscriptFile = ".Logs-$LogTimeUpdateNavigationLinks.Transcript.rtf"
 
 try{
   stop-transcript|out-null
 }
 catch [System.InvalidOperationException]{}
 
 start-transcript $TranscriptFile
 
 
 function AddCSOM(){
      #Load SharePoint client dlls 
      $a = [System.Reflection.Assembly]::LoadFile(    "$scriptBaseClientLibrariesMicrosoft.SharePoint.Client.dll") 
      $ar = [System.Reflection.Assembly]::LoadFile(    "$scriptBaseClientLibrariesMicrosoft.SharePoint.Client.Runtime.dll") 
      
      if( !$a ){
          $a = [System.Reflection.Assembly]::LoadWithPartialName(        "Microsoft.SharePoint.Client")
      }
      if( !$ar ){
          $ar = [System.Reflection.Assembly]::LoadWithPartialName(        "Microsoft.SharePoint.Client.Runtime")
      }
      
      if( !$a -or !$ar ){
          throw         "Could not load Microsoft.SharePoint.Client.dll or Microsoft.SharePoint.Client.Runtime.dll"
      }
      
      
      #Add overload to the client context.
      #Define new load method without type argument
      $csharp =     "
       using Microsoft.SharePoint.Client;
       namespace SharepointClient
       {
           public class PSClientContext: ClientContext
           {
               public PSClientContext(string siteUrl)
                   : base(siteUrl)
               {
               }
               // need a plain Load method here, the base method is a generic method
               // which isn't supported in PowerShell.
               public void Load(ClientObject objectToLoad)
               {
                   base.Load(objectToLoad);
               }
           }
       }"
      
      $assemblies = @( $a.FullName, $ar.FullName,     "System.Core")
      #Add dynamic type to the PowerShell runspace
      Add-Type -TypeDefinition $csharp -ReferencedAssemblies $assemblies
 }
 
 
 AddCSOM
 
 $credentials = Get-Credential
 
 #Get inthe Input CSV File
 $SubSiteURLCSV = $scriptBase + "" + "SubSiteURLs.csv"
 
  
 
 cls
 
 $originalURL = " https://mySP2010Site.com/"
 
 #Read and Iterate through all the Sites Given in the SubSiteURLs.CSV
 import-csv $SubSiteURLCSV | where{
     Write-Host "Processing the Site : " $_.SubSiteURL -ForeGroundColor Green
                 
     $context = New-Object SharepointClient.PSClientContext($_.SubSiteURL)
     $totalDocLibSize =0
     
     $totalListSize=0
     $totalWebSize=0
      
     $context.Credentials = $credentials
     
     #Load the basic information about the web and site
     $context.Load($context.Web)
     $context.Load($context.Web.Navigation.QuickLaunch)
     $context.Load($context.Web.Navigation.TopNavigationBar)
     $context.Load($context.Site)
     $context.Load($context.Web.Lists)
     $context.ExecuteQuery()
     
     
     
     ############### BEGIN QUICK LAUNCH ################################
     Write-Host "Processing the Quick Launch (Left Navigation)"
     foreach($quickLaunch in $context.Web.Navigation.QuickLaunch)
     {
         $context.Load($quickLaunch)
         $context.Load($quickLaunch.Url)
         $context.Load($quickLaunch.Children)
         $context.ExecuteQuery()
         
         ############### PARENT LINKS #################################
         if($quickLaunch.Url -like  ('*'+$originalURL+'*'))
         {
             Write-Host "Updating the Link : " $quickLaunch.Title
             $temp = $quickLaunch.Url
             $temp = $temp.Replace($originalURL, "")
             
             $quickLaunch.Url = $temp
             $quickLaunch.Update()
             $context.Load($quickLaunch)
             $context.ExecuteQuery()
         }
         
         ########### FIRST LEVEL CHILD LINKS ##########################
         foreach($quickLink in $quickLaunch.Children)
         {
             $context.Load($quickLink)
             $context.Load($quickLink.Url)
             $context.ExecuteQuery()
         
             if($quickLink.Url -like ('*'+$originalURL+'*'))
             {
                 Write-Host "Updating the Child Link : " $quickLink.Title
                 $temp = $quickLink.Url
                 $temp = $temp.Replace($originalURL, "")
                 
                 $quickLink.Url = $temp
                 $quickLink.Update()
                 $context.Load($quickLink)
                 $context.ExecuteQuery()
             }
         }        
     }
     
     ############ END QUICK LAUNCH ####################################
     
     ############### BEGIN TOPNAVIGATIONBAR ################################
     Write-Host "Processing the NavigationBar (Top Navigation)"
     
     foreach($quickLaunch in $context.Web.Navigation.TopNavigationBar)
     {
         $context.Load($quickLaunch)
         $context.Load($quickLaunch.Url)
         $context.Load($quickLaunch.Children)
         $context.ExecuteQuery()
         
         ############### PARENT LINKS #################################
         if($quickLaunch.Url -like  ('*'+$originalURL+'*'))
         {
             Write-Host "Updating the Top Link : " $quickLaunch.Title
             $temp = $quickLaunch.Url
             $temp = $temp.Replace($originalURL, "")
             
             $quickLaunch.Url = $temp
             $quickLaunch.Update()
             $context.Load($quickLaunch)
             $context.ExecuteQuery()
         }
         
         ########### FIRST LEVEL CHILD LINKS ##########################
         foreach($quickLink in $quickLaunch.Children)
         {
             $context.Load($quickLink)
             $context.Load($quickLink.Url)
             $context.ExecuteQuery()
         
             if($quickLink.Url -like ('*'+$originalURL+'*'))
             {
                 Write-Host "Updating the top Child Link : " $quickLink.Title
                 $temp = $quickLink.Url
                 $temp = $temp.Replace($originalURL, "")
                 
                 $quickLink.Url = $temp
                 $quickLink.Update()
                 $context.Load($quickLink)
                 $context.ExecuteQuery()
             }
         }        
     }
     
     ############ END QUICK LAUNCH ####################################
      
 }
 
 Write-Host "Process Completed..  Press Enter to Exit" -ForeGroundColor Green
 
  try{
   stop-transcript|out-null
 }
 catch [System.InvalidOperationException]{}       
 

Happy Coding,

Sathish Nadarajan.

Category : CSOM, PowerShell, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Delete/Update List/Library View in SharePoint Office 365 Programmatically using Patterns and Practices PNP

Sathish Nadarajan
 
Solution Architect
September 16, 2017
 
Rate this article
 
Views
2970

In the earlier article, we saw, how to Create a List View. In the same manner, we may come across a scenario to delete/update the existing views. The below snippet will be handy for the developers.

 using Microsoft.SharePoint.Client;
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Reflection;
 
 namespace Office365.Console
 {
     class Program
     {
         static void Main(string[] args)
         {
             DeleteUpdateView();
         }
 
          
 
         public static void DeleteUpdateView()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
 
 
             string siteUrl = "https://************.sharepoint.com/sites/DeveloperSite/";
             //string siteUrl = item.TargetSiteUrl;
             string userName = "sathish@****.onmicrosoft.com";
             string password = "********";
 
             
             using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 try
                 {
                     Web web = clientContext.Web;
                     
                     clientContext.Load(web);
                     clientContext.Load(web.Lists);
                     clientContext.ExecuteQuery();
 
                     List list = web.Lists.GetByTitle("Test List");
                     clientContext.Load(list);
                     clientContext.Load(list.Views);
                     clientContext.ExecuteQuery();
 
                     //To Delete the View 
                     var lstViewToBeDeleted = list.Views.GetByTitle("Created By Me");
                     lstViewToBeDeleted.DeleteObject();
                     clientContext.ExecuteQuery();
 
                     //To Update the View
                     var lstViewToBeUpdated = list.Views.GetByTitle("All Items Test");
                     lstViewToBeUpdated.ViewQuery = "<OrderBy><FieldRef Name="Modified" Ascending="FALSE" /></OrderBy>";
                     lstViewToBeUpdated.Update();
                     clientContext.ExecuteQuery();
                 }
                 catch (Exception ex)
                 {
                     System.Console.ForegroundColor = ConsoleColor.Red;
                     System.Console.WriteLine("Exception Occured : " + ex.Message);
                     System.IO.File.AppendAllText("C:\Temp\UpdatePropertyBagIndexed.txt", ex.Message + " - " + siteUrl + Environment.NewLine);
                 }
 
 
             }
 
 
             System.Console.WriteLine("Completed....");
             System.Console.WriteLine("Press Any Key to Exit ....");
             System.Console.ReadLine();
         }
          
 
          
     }
 }
 

In the above snippet, I have deleted a view and updated a view. The Update, I have done only the ViewQuery property. Like that, we can update many properties of a view and the ViewQuery itself, can have many CAML Queries.

The Output of the Update will be something like,

clip_image002

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to update a SharePoint list item using Express JS

Krishna KV
 
Team Leader, Aspire Systems
June 24, 2017
 
Rate this article
 
Views
2882

In this article we can see how to update a SharePoint list item using Express JS, by passing the request digest header. For adding item and configuration steps, refer the previous article https://www.sharepointpals.com/post/How-to-add-a-SharePoint-List-Item-using-Express-JS-by-passing-Request-Digest

package.json

 {
    "name": "exp",
    "version": "1.0.0",
    "main": "index.js",
    "repository": {},
    "license": "MIT",
    "dependencies": {
      "body-parser": "^1.16.1",
      "compression": "^1.6.2",
      "cookie-parser": "^1.4.3",
      "express": "^4.14.1",
      "httpntlm": "1.7.4", 
      "cors": "2.8.1",
      "async": "2.1.5",
      "agentkeepalive": "3.1.0",
      "httpreq": "0.4.23", 
      "express-api-helper": "0.0.5",
      "request": "2.79.0"
    },
    "devDependencies": {}
  }
 

app.js

 const express = require('express');
 const bodyParser = require('body-parser');
 const compression = require('compression');
 const port = 3000;
 const app = express();
 const router = express.Router();
 const httpntlm = require('httpntlm');
 const async = require('async');
 const httpreq = require('httpreq');
 const ntlm = require('httpntlm').ntlm;
 const HttpsAgent = require('agentkeepalive').HttpsAgent;
 const keepaliveAgent = new HttpsAgent();
 
 app.use(compression());
 app.use(bodyParser.json());
 app.use('/api', router); // Adding router middleware in the express js 
  function getSPConfig() {
         return {
             url: "https://your-sp-url/",
             username: '[User Name]',
             password: '[Password]',
             domain: '[Domain Name]',
             workstation: '',
             headers: {
                 "Accept": "application/json;odata=verbose",
                 "content-type": "application/json;odata=verbose;"
             }
         }
     };
 
     // method to get the RequestDigest header 
 function getDigest(returnfun) {
    
     let spConfig = getSPConfig();
     async.waterfall([
         function (callback) {
 
             var type1msg = ntlm.createType1Message(spConfig);
 
             httpreq.post(spConfig.url + "_api/contextinfo", {
                 headers: {
                     'Connection': 'keep-alive',
                     'Authorization': type1msg,
                     'accept': 'application/json;odata=verbose'
                 },
                 agent: keepaliveAgent
             }, callback);
         },
 
         function (res, callback) {
 
             if (!res.headers['www-authenticate'])
                 return callback(new Error('www-authenticate not found on response of second request'));
 
             var type2msg = ntlm.parseType2Message(res.headers['www-authenticate']);
             var type3msg = ntlm.createType3Message(type2msg, spConfig);
 
             setImmediate(function () {
                 httpreq.post(spConfig.url + "_api/contextinfo", {
                     headers: {
                         'Connection': 'Close',
                         'Authorization': type3msg,
                         'accept': 'application/json;odata=verbose'
                     },
                     allowRedirects: false,
                     agent: keepaliveAgent
                 }, callback);
             });
         }
     ], function (err, response) {
         var json = JSON.parse(response.body);
         return returnfun(json);
 
     });
 }
 
 router.put('/:id', (req, res) => {
     let httpResponse = { "statusCode": 500, result: undefined };
     let opt = getSPConfig();
     opt.url = opt.url + "_api/web/lists/getByTitle('Testing')/items(" + req.params["id"] + ")";
 
     httpntlm.get(opt, function (error, resp) {
         let data = JSON.parse(resp.body);
         opt.url = data.d.__metadata.uri;
         getDigest(function (json) {
 
             opt.headers["X-RequestDigest"] = json.d.GetContextWebInformation.FormDigestValue;
             opt.headers["X-HTTP-Method"] = "MERGE";
             opt.headers["If-Match"] = data.d.__metadata.etag;
 
             opt.json = { __metadata: { 'type': 'SP.Data.TestingListItem' }, Title: "Item Update at " + new Date() };
             httpntlm.post(opt, function (error, response) {
                 httpResponse.result = response;
                 res.send(httpResponse);
             });
         });
     });
 });
 
 app.listen(port, (err, req, res, next) => {
     console.log(`server started at ${port}`);
 });
 
 

Author Info

Krishna KV
 
Team Leader, Aspire Systems
 
Rate this article
 
Krishna K.V has been working in IT Industry for over 7+ years. He holds a Master Degree in Information Technology. He is more interested to learn and share new technologies, ...read more
 

How to Update/Modify Quick Launch to a Web Site in SharePoint Office 365 Programmatically using CSOM C#

Sathish Nadarajan
 
Solution Architect
January 29, 2017
 
Rate this article
 
Views
4085

 

In the previous article, we saw how to Add a Quick Launch Link. In this article, we will be seeing how to Update Quick Launch to a Web in SharePoint Office 365 Programmatically using CSOM C#

 namespace Console.Office365
 {
     using Microsoft.SharePoint.Client;
     using Microsoft.SharePoint.Client.Taxonomy;
     using Newtonsoft.Json.Linq;
     using System;
     using System.Collections.Generic;
     using System.IO;
     using System.Linq;
     using System.Threading.Tasks;
 
     class Program
     {
         static void Main(string[] args)
         {
             UpdateQuickLaunch();
         }
 
         public static void UpdateQuickLaunch()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://*****.sharepoint.com/sites/communitysite/";
             string userName = "Sathish@*******.onmicrosoft.com";
             string password = "*******";
 
             using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 Web web = ctx.Web;
                 ctx.Load(web);
 
                 NavigationNodeCollection quickLaunchCollection = web.Navigation.QuickLaunch;
                 ctx.Load(quickLaunchCollection);
                 ctx.ExecuteQueryRetry();
 
                 NavigationNode NavigationNode = quickLaunchCollection.Where(n => n.Title == "Heading4").FirstOrDefault();
 
                 NavigationNode.Url = "https://www.sharepointpals.com";
 
                 NavigationNode.Update();
 
                 ctx.ExecuteQueryRetry();
             }
         }
     }
 }
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Update Managed Property as Searchable, Queryable, Sortable, Refinable, Retrievable in SharePoint 2013 using PowerShell

Sathish Nadarajan
 
Solution Architect
February 3, 2015
 
Rate this article
 
Views
20352

In the previous article, we saw How to create a Managed Property in SharePoint 2013 using PowerShell.

In this article, let us see how to Update Managed Property with various properties.

The script is as follows.

 $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
 $LogFile = ".UpdateManagedPropertyPatch-$LogTime.rtf"
 
 #start-transcript $logfile
 
 # Add SharePoint PowerShell Snapin
 
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
     Add-PSSnapin Microsoft.SharePoint.Powershell
 }
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 Set-Location $scriptBase
 
 $OutputPath = $scriptBase + "" + "ManagedPropErrors.txt"
 
 
 if (test-path $OutputPath)
 {
     remove-item $OutputPath
 }
 
 
 $csvfile = $scriptBase + "" + "EditManagedProp.csv"
 Import-csv $csvfile | where {
 
 $searchapp = Get-SPEnterpriseSearchServiceApplication
 
 $ManagedProperty = Get-SPEnterpriseSearchMetadataManagedProperty -SearchApplication $searchapp -Identity $_.ManagedPropertyName -ea silentlycontinue
 
 if($ManagedProperty)
 {
     $ManagedProperty.Searchable = $true
     $ManagedProperty.Queryable = $true
     $ManagedProperty.Sortable = $true
     $ManagedProperty.Retrievable = $true
     $ManagedProperty.Refinable = $true
     $ManagedProperty.SafeForAnonymous = $true
     $ManagedProperty.update()
     write-host "The searchable, queryable, Sortable, Retrievable and Refinable for the managed property" $_.ManagedPropertyName "has been enabled successfully ...... Done !" -fore green
 }
 else
 {
     Write-Host -f Yellow "The specified managed property " $_.ManagedPropertyName " does not exists... Please check whether you have given valid managed property name"
     $a = "The specified managed property " + $_.ManagedPropertyName + " does not exists... Please check whether you have given valid crawled property name"| out-file $OutputPath -append
 }
 
 
 }
 #stop-transcript 
 

DOWNLOAD HERE

Happy Coding.

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment