Daily Archives: August 18, 2018

Update Webpart view in a Page programmatically using PowerShell

For a SharePoint Administrator managing the changes in the view for a webpart is a very tiresome job. If a single view changes in the library or list then a page which uses the webpart view has to be manually changed. To change the view in the webpart the administrator has to edit the page, modify webpart and save the page. Imagine if you have 5 pages and each page have 5 webparts and a view is changed. You have to open each page in edit mode and the each webpart edit, change view and save one by one.

To effectively change the webpart view in a page, CSOM have an api to get the webpart in a page as a XML. Manipulate the XML and get the webpart name and view name from xml. Usually when a webpart is added to the page the view xml is cached to the page. So when the view is changed in the library / list the updated view will not be reflected in the page. The PowerShell code will get the webpart and update the view xml

The full code is here you can download

#### To change the webpart view
#### Get the webpart from the page. get the WebPart XmlDef and find the View ID
### List has hidden view for the web part added. So get the view from the List and change that view.
### Its all about that hidden View

Add-Type -Path ".\CSOM\Microsoft.SharePoint.Client.dll"
Add-Type -Path ".\CSOM\Microsoft.SharePoint.Client.Runtime.dll"

$now=Get-Date -format "dd-MMM-yy,HH:mm:ss"
$fileFormat = Get-Date -format "dd-MMM-yy_HHmmss"
Write-Host "Script Start : '$($now)'" -ForegroundColor Yellow

$username = ""
$password = ""
$srcUrl = "" # full url like hhtp://my.sharepoint.com/
$sitePath = "/SitePages/"
$srcLibrary = "Documents"
$pagesList = @("Home.aspx") # you can specify many pages to be changed array here
$wepPartChangeList = @{"Documents" = "All Documents" ; } ### dictionary value Key = Web part Title seen on page, Value = View Name from the Library

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)

Write-Host "Authenticating ..." -ForegroundColor White
$srcContext = New-Object Microsoft.SharePoint.Client.ClientContext($srcUrl)
$srcContext.Credentials = $credentials
$srcWeb = $srcContext.Web
$srcList = $srcWeb.Lists.GetByTitle($srcLibrary)

$srcContext.Load($srcWeb)
$srcContext.Load($srcList)

try{
    $srcContext.ExecuteQuery()
}catch{
    Write-Host $_.Exception.Message -ForegroundColor Red
    exit
}
Write-Host "Connected to the web..." -ForegroundColor Green

foreach($page in $pagesList)
{
    $filePath = $sitePath + $page
    $pageObject = $srcWeb.GetFileByServerRelativeUrl($filePath)
    $srcContext.Load($pageObject)
    $srcContext.ExecuteQuery()
    $WPM = $pageObject.GetLimitedWebPartManager("Shared")

    $webParts = $WPM.WebParts
    $srcContext.Load($WPM)
    $srcContext.Load($webParts)
    $srcContext.ExecuteQuery()

    foreach($wp in $webParts)
    {
        $srcContext.Load($wp.WebPart)
        $srcContext.Load($wp.WebPart.Properties)
        $srcContext.ExecuteQuery()

        if( $wepPartChangeList[$wp.WebPart.Title] -ne $null)
        #if($wp.WebPart.Title.IndexOf("Documents") -gt 0)
        {
            Write-Host "---------- Processing Page  = $($pageObject.Name) Webpart = $($wp.WebPart.Title) ------- " -ForegroundColor Yellow

            $wpXmlContent = $wp.WebPart.Properties["XmlDefinition"]
            $wpXml = New-Object -TypeName XML
            $wpXml.LoadXml($wpXmlContent)
            $viewGUID = $wpXml.View.Name

            $viewName = $null
            $viewName = $wepPartChangeList[$wp.WebPart.Title]
            if($viewName)
            {
                $view = $srcList.Views.GetByTitle($viewName)
                $wpView = $srcList.Views.GetById($viewGUID)
                $srcContext.Load($wpView)
                $srcContext.Load($view)
                $srcContext.ExecuteQuery()
                #$viewXml = New-Object -TypeName XML
                #$viewXml.LoadXml($view.ListViewXml)
                write-host "### WebPart Xml -------Before Xml Change -----" -foreground cyan
                write-host "$($wpView.ListViewXml)"              

                $wpViewFields = $wpView.ViewFields
                $viewFields = $view.ViewFields
                $srcContext.Load($viewFields)
                $srcContext.Load($wpViewFields)
                $srcContext.ExecuteQuery()

                $wpViewFields.RemoveAll()
                foreach($vField in $viewFields)
                {
                    $wpView.ViewFields.Add($vField)
                }

                $wpView.RowLimit = $view.RowLimit
                $wpView.ViewQuery = $view.ViewQuery
                $wpView.Update()
                $srcContext.Load($wpView)
                $srcContext.ExecuteQuery()
                write-host "### WebPart Xml -------After Xml Change -----" -foreground cyan
                write-host "$($wpView.ListViewXml)"
                write-host "*******************************************************************" -foreground cyan
            }
            else
            {
                Write-Host "Unable to fing view for " $wp.WebPart.Title -ForegroundColor Cyan
            }
            #$wp.SaveWebPartChanges()

        }
    }
    #Write-Host "Next Page " 

}
#>

$srcContext.Dispose()
$now=Get-Date -format "dd-MMM-yy,HH:mm:ss"
Write-Host "END : '$($now)'" -ForegroundColor Yellow<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

webpart

Set SharePoint folder level permission using C# & PowerShell

The PowerShell script here will set the permission to the folder inside the document library. The PowerShell script uses the C# code for permission. The C# code will add mandatory Full Control access and break the inheritance. The code uses the lambda function to find the unique permission. Since PowerShell natively does not support lambda expression the C# code is embedded within the PowerShell

The full script is below

$cSharp = @”

using System;

using System.Security;

using System.Linq;

using System.Collections.Generic;

using Microsoft.SharePoint.Client;

namespace SPClient

{

public class Permission

{

private static string username = “”;

private static string password = “”;

private static string srcUrl = “”;

private static string[] groupNames = { “Team Site Members” };

private static string srcFolder = “folder path(/sites/dev/shared documents/folder1)”;

private static string permissionType = “Edit”;

private static string mandatoryGroupName = “Developer Owners”;

public static void ApplyPermission()

{

try

{

var securePassword = new SecureString();

foreach (char c in password)

{

securePassword.AppendChar(c);

}

using (var clientContext = new ClientContext(srcUrl))

{

Console.WriteLine(“Authenticating…” + srcUrl);

clientContext.Credentials = new SharePointOnlineCredentials(username, securePassword);

Web srcWeb = clientContext.Web;

Folder applyFolder = srcWeb.GetFolderByServerRelativeUrl(srcFolder);

clientContext.Load(srcWeb);

clientContext.Load(applyFolder,f=>f.ListItemAllFields.HasUniqueRoleAssignments);

clientContext.ExecuteQuery();

Console.WriteLine(“Connected.”);

Console.WriteLine(“Applying to folder : ” + srcFolder);

GroupCollection groups = srcWeb.SiteGroups;

clientContext.Load(groups);

clientContext.ExecuteQuery();

var myGroups = (from a in groupNames

from w in groups

where a == (w.Title)

select w).ToArray();

Console.WriteLine(“Groups…”);

var coordinator = (from a in groups where a.Title == mandatoryGroupName select a).FirstOrDefault();

RoleDefinitionCollection rdc = srcWeb.RoleDefinitions;

RoleDefinition myRole = rdc.GetByName(permissionType);

RoleDefinition coordinateRole = rdc.GetByName(“Full Control”);

clientContext.Load(rdc);

clientContext.Load(myRole);

clientContext.Load(coordinateRole);

clientContext.ExecuteQuery();

Console.WriteLine(“Role definitions…”);

if (!applyFolder.ListItemAllFields.HasUniqueRoleAssignments)

{

Console.WriteLine(“Breaking inheritance…”);

applyFolder.ListItemAllFields.BreakRoleInheritance(true, false);

}

else

{

Console.WriteLine(“Inheritance broken already…”);

}

var folderRoles = applyFolder.ListItemAllFields.RoleAssignments;

Console.WriteLine(“Applying the role assignments …”);

RoleDefinitionBindingCollection coordinateRdb = new RoleDefinitionBindingCollection(clientContext);

coordinateRdb.Add(coordinateRole);

RoleDefinitionBindingCollection collRdb = new RoleDefinitionBindingCollection(clientContext);

collRdb.Add(myRole);

//clientContext.Load(folderRoles);

//clientContext.ExecuteQuery();

folderRoles.Add(coordinator, coordinateRdb);

foreach (Group eachGroup in myGroups)

{

Console.WriteLine(“Applying Group: ” + eachGroup.Title);

folderRoles.Add(eachGroup, collRdb);

}

applyFolder.Update();

clientContext.ExecuteQuery();

Console.WriteLine(“Successfully applied”);

Console.Read();

}

}

catch(Exception ex)

{

Console.WriteLine(ex.Message);

//Console.Read();

}

}

}

}

“@

$assemblies = @(

“C:\Documents\PS\CSOM\Microsoft.SharePoint.Client.dll”,

“C:\Documents\PS\CSOM\Microsoft.SharePoint.Client.Runtime.dll”,

“System.Core”

)

Add-Type -TypeDefinition $cSharp -ReferencedAssemblies $assemblies

[SPClient.Permission]::ApplyPermission()