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
}
}

“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.

 

Change Look for SharePoint List using Datatable JS

Here I am showing you to change the look of SharePoint list view using datatabse js and SharePoint JS link. If your SharePoint list having more items than performance will be quite slow, but still manageable.

So, here are the steps:

    • Create a view in your target SharePoint List. If you want “Edit” button on view then add “Edit (link to edit item)” field to that view.
    • Now edit the view Page and add script editor web part to the header of the page and add below references to script editor.
<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    • Now edit the List view web part > Navigate to open web part properties > expand “Miscellaneous” and under JSLink > set your file URL as below. In my case, I kept the file under SiteAssets. Download source code from GitHub
~sitecollection/SiteAssets/dataTablesListView.js

Your output will be like this.

 

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();
}

Export SharePoint List schema to CSV file

In this article I am going to demonstrates How to Export SharePoint custom list schema to CSV file. This example applies to SharePoint 2010 and SharePoint 2013 environment.


[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$listName="DemoList";
$siteURL="http://localhost/";
$csvPath="C:PowerOutput"+ $listName + ".csv";
$oSite= New-Object Microsoft.SharePoint.SPSite($siteURL)
$oWeb=$oSite.OpenWeb()
$oList=$oWeb.Lists[$listName]
#Get only custom fields which are created by user
$oList.Fields | ?{$_.CanBeDeleted -eq $true -and $_.Hidden -eq $false} | select Title,Internalname,Type |Sort-Object title| Export-Csv -Path $csvPath -Encoding ascii -NoTypeInformation
$oWeb.Dispose()
$oSite.Dispose()

PowerShell script to Upload multiple Custom List template and create custom list instances

I this article I am going to present you to create multiple SharePoint Custom list instances using PowerShell.It is very helpful when we are working on migrating SharePoint environment.

In below example list name is same as the template which we are uploading to template gallery.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

# Custom template path
$Path = "C:\CustomTemplate"

# Your site url
$oSite = Get-SPSite("htpp://localhost/")

# Get the root web
$oWeb = $oSite.RootWeb

# Get the list template gallery
$spLTG = $oWeb.GetFolder("List Template Gallery")

# Get the list template gallery Collection
$spcollection = $spLTG.files

# loop all stp files and upload/create custom list
Get-ChildItem $Path -Filter "*.STP" |
ForEach-Object {
$Templatefile = get-item $_.FullName
$catlogs="_catalogs/lt/" + $_.Name
$lstDesc="Description :" + $_.BaseName
$spcollection.Add($catlogs, $Templatefile.OpenRead(), $true)
$CustomlistTemplates = $oSite.GetCustomListTemplates($oWeb)
$oWeb.Lists.Add($_.BaseName, $lstDesc, $CustomlistTemplates[$_.BaseName])
Write-Host $_.BaseName+" List has been created" -foregroundcolor green
}

$oWeb.Dispose()
$oSite.Dispose()

Download multiple list templates from SharePoint Template Gallary.

When we are working on migrating SharePoint Custom list to other SharePoint site.We have to save that list as template and restore again to another server.But suppose you are having so many list then ???

So, In this article I am going to help to you to download all SharePoint list template from Template gallery to local drive and in my another article we will work on upload multiple Custom List templates from local drive and create custom list instances.

Here is my scenario, today I have saved multiple list as template to template gallery and now I wanted to download that.Now by using below code you can simply download the all stp files which you created today.

#Function to copy file from SharePoint template gallary to lo drive
Function DownloadStp($SPFolderURL, $localFolderPath)
{
	$SPFolder = $oWeb.GetFolder($SPFolderURL)
	foreach ($File in $SPFolder.Files)
	{
		#By using below if condition you will get all the templates which are created today.
		if($File.TimeCreated -gt ($(Get-Date).AddDays(-1)))
		{
			$Data = $File.OpenBinary()
			$FilePath= Join-Path $localFolderPath $File.Name
			[System.IO.File]::WriteAllBytes($FilePath, $data)
		}
	}
	foreach ($SubFolder in $SPFolder.SubFolders)
	{
		if($SubFolder.Name -ne "Forms")
		{
			DownloadStp $SubFolder $localFolderPath
	    }
	}
}
$oWeb = Get-SPWeb "http://localhost/"
$oLTG =  $oWeb.Lists["List Template Gallery"].RootFolder
$localDrivePath = "C:\PowershellOutput\StpFiles"
#calling DownloadStp function to download stp files to localDrivePath
DownloadStp $oLTG $localDrivePath 
#disposing web object 
$oWeb.Dispose()

In my next article I am going to help you to create SharePoint custom list using multiple template which are saved in you local drive.
PowerShell script to Upload multiple Custom List template and create custom list instances

Create custom permission level using C#,PowerShell and JSOM

Today,I am going to present you to create Permission level using C#, Powershell and JavaScript Object Model. Permission levels are predefined sets of permissions that you can assign to individual users, groups of users, or security groups, based on the functional requirements of the users and on security considerations.

Create Permission Level using C#

 public static void CreatePermissionLevel()
        {
            string strURL = "http://optimumview/";
            string CustomPermissionName = "myCustomPermissions";
            using (SPSite site = new SPSite(strURL))
            {
                using (SPWeb web = site.RootWeb)
                {
                    if (web.RoleDefinitions[CustomPermissionName] == null)
                    {
                        SPRoleDefinition role = new SPRoleDefinition();
                        role.Name = CustomPermissionName;
                        role.Description = "Description: It's only permission to ViewListItems,AddListItems and EditListItems";
                        //I'm using below permisson attributes in this code
                        //ViewListItems	View items in lists, documents in document libraries, and view Web discussion comments.
                        //AddListItems	Add items to lists, add documents to document libraries, and add Web discussion comments.
                        //EditListItems	Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries.
                        role.BasePermissions = SPBasePermissions.ViewListItems | SPBasePermissions.AddListItems | SPBasePermissions.EditListItems;
                        web.RoleDefinitions.Add(role);
                        Console.WriteLine("Created Successfully!!");
                        Console.ReadLine();
                    }
                    else
                    {
                        Console.WriteLine("Permisson already exists!!");
                        Console.ReadLine();
                    }
                }
            }
        
        }

Click Here get list of Specifies the built-in permissions available in SharePoint Foundation.

Create Permission Level using Powershell

$spSite = Get-SPSite "http://optimumview/"
$spWeb = $spSite | Get-SPWeb
$customPermissionName="MyPowershellPermission"
if($spWeb.RoleDefinitions[$customPermissionName] -eq $null)
{
    $spRoleDefinition = New-Object Microsoft.SharePoint.SPRoleDefinition
    $spRoleDefinition.Name = $customPermissionName
    $spRoleDefinition.Description = "Description: It's only permission to ViewListItems,AddListItems and EditListItems";
    $spRoleDefinition.BasePermissions = "ViewListItems, AddListItems, EditListItems"
    $spWeb.RoleDefinitions.Add($spRoleDefinition)
	Write-Host $spRoleDefinition.Name "has been created successfully!!" -foregroundcolor green
}
else
{
	Write-Host "Permission already exists!!" -foregroundcolor red
}
$spWeb.Dispose()
$spSite.Dispose()

To get list of Specifies the built-in permissions available in SharePoint Foundation use below PowerShell Command :

[System.Enum]::GetNames("Microsoft.SharePoint.SPBasePermissions")

Create Permission Level using JavaSript

function createCustomPermisionLevel() {
        var clientContext = new SP.ClientContext.get_current();
        var oWeb = clientContext.get_web();
        var customPermissionName='MyJSOMPermission';
        // Set up permissions.
        var permissions = new SP.BasePermissions();
        permissions.set(SP.PermissionKind.viewListItems);
        permissions.set(SP.PermissionKind.addListItems);
        permissions.set(SP.PermissionKind.editListItems);
        // Create a new role definition.
        var roleDefinitionCreationInfo = new SP.RoleDefinitionCreationInformation();
        roleDefinitionCreationInfo.set_name(customPermissionName);
        roleDefinitionCreationInfo.set_description('Its only permission to ViewListItems,AddListItems and EditListItems');
        roleDefinitionCreationInfo.set_basePermissions(permissions);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert(customPermissionName +' : has been created sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }

Click Here to get list of permission available in csom.

SharePoint List CRUD Operation using JavaScript

In order to my last post “SharePoint List CRUD Operation using PowerShell Management”. I am going to help you in learning how to do basic SharePoint List operations (CRUD – Create, Read, Update and Delete) using JavaScript.

Create SharePoint List item

function createSPListItem() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current(); 
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle(listName);

        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);
        this.oListItem.set_item("Title", "Test-Item-2");
        this.oListItem.set_item("DemoLocation", "India");
        this.oListItem.set_item("ProjectName", "CSR-RL-09");
        this.oListItem.update();

        clientContext.load(this.oListItem);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert('Item ' + this.oListItem.get_id() + 'created sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }

Read SharePoint List item

    function readSPList() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current();
        var oWebsite = clientContext.get_web();
        var oList = oWebsite.get_lists().getByTitle(listName);
        var camlQuery = new SP.CamlQuery();
        // set_viewXml function to define a CAML query and return items that meet specific criteria.
        // you can write caml query into below line
        camlQuery.set_viewXml('&lt;View&gt;&lt;RowLimit&gt;100&lt;/RowLimit&gt;&lt;/View&gt;');
        // The getItems(query) function enables you to define a Collaborative Application Markup Language (CAML) query that specifies which items to return
        this.collListItem = oList.getItems(camlQuery);

        clientContext.load(this.collListItem, "Include(Title, DemoLocation, ProjectName)");
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            var listItemInfo;
            var listItemEnumerator;

            listItemEnumerator = this.collListItem.getEnumerator();

            listItemInfo = "";
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                listItemInfo += "Title: " + oListItem.get_item('Title') + "&lt;br/&gt;" +
                "Location: " + oListItem.get_item('DemoLocation') + "&lt;br/&gt;" +
                "Project Name: " + oListItem.get_item('ProjectName') + "&lt;br/&gt;";
            }

            alert(listItemInfo);
        }

        function errorHandler() {
            resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
        }
    }
	

Update SharePoint List item

    function updateSPListItem() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current();
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle(listName);

        this.oListItem = oList.getItemById(1);
        this.oListItem.set_item("Title", "Test-Item-03");
        this.oListItem.set_item("DemoLocation", "SIG");
        this.oListItem.set_item("ProjectName", "NDR-PO-09");
        this.oListItem.update();

        clientContext.load(this.oListItem);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert('Item ' + this.oListItem.get_id() + 'updated sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }
	

Delete SharePoint List item

    function deleteSPListItem() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current();
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle(listName);

        this.oListItem = oList.getItemById(1);
        this.oListItem.deleteObject();

        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert('Item ' + this.oListItem.get_id() + 'deleted sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }