Reset unique permission for SharePoint document library and files

Sometime we need to reset the unique permission for document library, sub folders and files. If the document library has only 1-2 documents then we can handle it manually, but if you have thousands of files and folder so its quite difficult to reset it for all one by one. Below piece of code can help to reset unique permission for document library and its content. This script will take the top level permission from document library.


function ResetUniquePermission {
Param(
[Parameter(Mandatory = $true, HelpMessage="Enter the site url")][ValidateNotNullorEmpty()][string] $SiteURL ,
[Parameter(Mandatory = $true, HelpMessage="Enter the library name")][ValidateNotNullorEmpty()][string] $LibraryName,
[Parameter(Mandatory = $true, HelpMessage="Total number of files")][ValidateNotNullorEmpty()][int] $TotalFiles

)

$Web = Get-SPWeb $SiteURL 
$List= $Web.Lists[$LibraryName]
$Query = New-Object Microsoft.SharePoint.SPQuery
$Query.ViewXml =  @"
<View Scope="RecursiveAll">
    <Query>
        <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
    </Query>
    <RowLimit Paged="TRUE">$TotalFiles</RowLimit>
</View>
"@;

$Items = $List.GetItems($Query)
for($j=0;$j -lt $Items.Count ;$j++)
{
    $Items[$j].ResetRoleInheritance()
    Write-Host "Permission reset done for file "$Items[$j]["Title"] -ForegroundColor Green
}
}

Create modern page using defined template

SharePoint onprem and SharePoint online updates never been same.Most of required feature which are available in SPOnline is not available in SharePoint On-prem. One of them is template based page creation.As of today you can create page with provided template in communication site but not available in Team site. So here is the small solution, by using we can provide plenty of predefined template to end users for their easiness.
Lets start:

Step 1: Create a empty page, just add your columns and widgets into into , like I have created. Refer below screenshot.

So here I have added few widget and created a blank page page, once you page created just save that page.

Step 2: After saving the page just run below script to get the Canvas content of the page.

$templatePageName= "demo-page.aspx"
$oWeb = Get-SPWeb "&lt;Site URL&gt;"
$pageLibrary = $oWeb.Lists["Site Pages"]
$page = $pageLibrary.GetItems() | select Name, ID | where { $_.Name -eq $templatePageName }
if ($null -ne $page.ID) {
    $canvasContent = $pageLibrary.GetItemByID($page.ID)["CanvasContent1"]
    $canvasContent | Out-File -FilePath C:\canvasContent.txt
}
else { Write-Host "Page Id not found" -ForegroundColor DarkCyan }

Step 3: After running above script you will find the Canvas content text in text file with name “canvasContent.txt” which is generated in C drive of your machine.Now copy that text and pass it to “CanvasContent1” property.

Step 4: Refer article Create Modern page using C# in SharePoint’19 on-prem and pass text of canvasContent.txt file to “CanvasContent1” property.

That’s it, like this you can provide functionality to create page with your own template.

“Sign as different user” for SharePoint site

By default, you won’t find “Sign as different user” option in SharePoint, but most of them as a developer or superuser need to log in with different users to see the content rendering based on different permission and role. So there are two ways to open the SharePoint site in different users.

Method-1

You need to just append “_layouts/closeConnection.aspx?loginasanotheruser=true”  to your Site Absolute Url and just hit enter, it will show you the pop up for credentials. There is no browser restriction for the same.

URL: _layouts/closeConnection.aspx?loginasanotheruser=true

Method-2

This method is only applicable in the SharePoint on-prem site.

The second method is to run a user browser to “Run as different user” mode. So to open any browser as the different user just simply press shift and right-click on the browser exe file, it will show you the option “Run as different user”, select this option and it will pop up for credentials. Enter the credentials for the user which you trying to log in and open your SharePoint site.

 

Create Modern page using C# in SharePoint’19 on-prem

Here I am just demonstrating to you, how we can create a page using the server object model in SharePoint’19 on-prem. There are many things we control through C# while creating the Pages like disable comment, publish the page, custom templates, embedded pre-defined web part, and many more.

There are three types of Page Layout available, so you can choose based on your requirement. By default, you can only create Article Page from UI, but after doing some customization you can do much more on pages.

  • Home
  • Article

Another parameter is “PromotedState”, if you pass 2 then your page is a news page and 0 generic pages.

We can also use customize canvas or we can say multiple page templates to create the Modern page. By default on the team site, the Page template option is not available so you can achieve it through us this small customization.

Refer article: Create modern page using defined template

string PageLibName = "Site Pages";
string PageName = "demo-page.aspx";
SPUser PageAuthor = "&lt;Pass SPUser Object&gt;";
string SiteURL = "&lt;Pass Site URL&gt;";
using (SPSite oSPsite = new SPSite(SiteURL))
{
    using (SPWeb oWeb = oSPsite.OpenWeb())
    {
        SPList oList = oWeb.Lists[PageLibName];
        SPListItem oItem = oList.RootFolder.Files.Add(String.Format("{0}/{1}", oList.RootFolder.ServerRelativeUrl, PageName), SPTemplateFileType.ClientSidePage).ListItemAllFields;
        oItem["Title"] = System.IO.Path.GetFileNameWithoutExtension(PageName);
        oItem["ContentTypeId"] = "0x0101009D1CB255DA76424F860D91F20E6C4118";
        oItem["ClientSideApplicationId"] = "b6917cb1-93a0-4b97-a84d-7cf49975d4ec";
        
        //Home
        oItem["PageLayoutType"] = "Article";

        //Promoted State 2 is for News and 0 for Generic Page
        oItem["PromotedState"] = 2;

        //comment below if you don't want to change page author or editor -- Created by and Modfied by field
        oItem[SPBuiltInFieldId.Author] = oWeb.EnsureUser(PageAuthor.LoginName);
        oItem[SPBuiltInFieldId.Editor] = oWeb.EnsureUser(PageAuthor.LoginName);
        
        //this is also key factor while create the page , you can change it if you want custom page layout. 
        oItem["CanvasContent1"] = "&lt;div&gt; &lt;/div&gt;";

        //False to enable comment and True if you wanted to disable the comment 
        oItem.SetCommentsDisabled(false);
        oItem.Update();
    }
}

Publish multiple pages in SharePoint

As a SharePoint admin most of the time we are getting requirement to publish pages or while working on migration for some cases we would require to publish pages. Here is the small piece of code which can help to publish single page or multiple pages using Powershell.

This piece of code is required for both

$LibraryTitle = "<Replace with Page Library Name>"
$SiteURL = "<Replace with your site URL>"
$oWEb = Get-SPWeb $SiteURL
$PublishingComment ="Published using powershell"

Use below block if you wanted to publish a single page, replace with your page url.

<# Single page publish #>
$pageURL = "https://digiboek.net/sites/demo/SitePages/Sample.aspx"
$file = $oWEb.GetFile($pageURL)
$file.Publish($PublishingComment);

If you wanted to publish multiple pages then use below piece of code

<# Publish all pages from library #>
$oLib = $oWEb.GetFolder($LibraryTitle)
$files = $oLib.Files | select Name, Url
foreach ($file in $files) {
    $ofileURL = $SiteURL + "/" + $file.Url
    $oFile = $oWEb.GetFile($ofileURL)
    if ($oFile.Exists -eq $true) {
        $oFile.Publish($PublishingComment);
        Write-Host $file.Name" Page published successfully..." -foreground Green
    }
}

Happy Coding 😊

Horizontal radiobutton in SharePoint classic list form.

By default SharePoint Classic has vertical radio buttons. Sometime we are getting requirement to make it horizontal. There many ways to do that, one of them you can inject jQuery using content editor webpart on the new and edit form.
For example our default OOTB form as below :

Here is piece of code which you need to add on content editor, it will automatically make all radio buttons of the page to horizontal.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $( document ).ready(function() {
        $(".ms-formtable .ms-RadioText:eq(0)")
        $fields = $('.ms-formbody table');
        $.each($fields, function (i, e) {
                var getRadio = $(e).find('.ms-RadioText:gt(0)');
                $(e).find('.ms-RadioText:eq(0)').append(getRadio);
        }); 
    });
</script>

Once you add your output will be like below :

Upload list item attachment using Jquery and rest call

Most of the time we require to upload SharePoint list item attachment from the custom interface. So here is the simplest way to upload list item attachment. It requires jQuery to execute this code.

Call “fnUpload” just pass List title, Item ID that’s it.  I am assuming here you already created HTML with file upload control.

function fnUpload() {
    var allFiles = [];
    var input = document.getElementById('<ReplaceWithFileUploadID>');
    var file = input.files[0];
    if (file != null && file.size > 0) {
        allFiles.push(file);
    }
    if (allFiles.length > 0) {
        // replace list item name ,and list item id. 
        fnUploadFile('[Replace with List Name]', parseInt('[Replace with Item ID]'), allFiles[0]);
    }
    else {
        alert("There is no file selected, please select file...");
    }
}

function fnGetFileBuffer(file) {
    var deferred = $.Deferred();
    var reader = new FileReader();
    reader.onload = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(file);
    return deferred.promise();
}

function fnUploadFile(listName, itemID, file) {
    var deferred = $.Deferred();
    var fileName = file.name;
    fnGetFileBuffer(file).then(
        function (buffer) {
            var bytes = new Uint8Array(buffer);
            var binary = '';
            for (var b = 0; b < bytes.length; b++) {
                binary += String.fromCharCode(bytes[b]);
            }
            var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
            $.getScript(scriptbase + "SP.RequestExecutor.js", function () {
                var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
                createitem.executeAsync({
                    url: siteurl + "/../_api/web/lists/GetByTitle('" + listName + "')/items(" + itemID + ")/AttachmentFiles/add(FileName='" + fileName + "')",
                    method: "POST",
                    binaryStringRequestBody: true,
                    body: binary,
                    success: function (data) {
                        alert("file Uploaded Succesfully.");
                        deferred.resolve(data);
                    },
                    error: function (data) {
                        alert(data + "There is a error while uploading..")
                        deferred.reject(data);
                    },
                    state: "Update"
                });
            });
        },
        function (err) {
            deferred.reject(err);
        }
    );
    return deferred.promise();
}