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.

 

PowerShell to install uninstall dll from GAC

Most of the we need to install and uninstall dll from GAC,so here is the simple set of script to simplify this task.

#replace it with your dll path 
$dllPath ="C:\temp\FileName.dll" 
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")            
$publish = New-Object System.EnterpriseServices.Internal.Publish      

#to unistall dll from GAC
$publish.GacRemove($dllPath)
iisreset

#to install dll from GAC
$publish.GacInstall($dllPath)
iisreset

Download Source code

Tabs in Nintex forms ???

Can we have TABS in Nintex form 🤔 ??

So Answer is “Yes”, we can tweak it to get the Tabs on Nintex form. Lets start, I am considering you already have basic knowledge of Nintex forms. How to create it and how it behaves, add custom CSS and JavaScript code..

Open your form in Nintex form editor, Add a choice control, and edit properties > Enter the Name of Control , Display Format =”Option buttons”, Choice options , Default value(it will decide your default selected tab),and last & important is “Render as button=’Yes'”. as below image.



In my case, I wanted to add three tabs (tab1, tab2, and tab3). I have added three sections for 3 tabs, we will enable it as per the selection of tabs. Select each section one by one and add rule to hide. Condition for Tab1 Not(TabHeader==”Tab-1″) , Tab2 Not(TabHeader==”Tab-2″) and Tab3 Not(TabHeader==”Tab-3″).


Now add below style code and javascript to Nintex form.

.nf-outer .nf-choiceAsTabs span label{    background: #3a3a3a;    color: white !important;    font-size: 17px !important;} .nf-outer .nf-choiceAsTabs input[type="radio"]:checked + label {     background: #87d29e !important}
//here just replace 3 with number of tabs to adjusted as per the width of your form.
NWF$(document).ready(function(){      NWF$('.nf-outer .nf-choiceAsTabs span label').css('width',NWF$('.ms-formtable').width()/3)});

Once you publish our tabs will looks like below 😉

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

Deactivate multiple accounts from EPM/Project Server

Sometimes it required to deactivated multiple accounts in EPM. So here is the script which can help you to deactivate multiple accounts. Account deactivation takes so much time so it is recommended to do this activity non business hour.

<# Below is CSV sample which I am using for this code. First Column is headers. #>;
<#
ResourcesEmail
kuldeep.verma@xyz.com
rajdeep.sardesai@xyz.com
Jaydeep.prajapat@xyz.com
#>

#Download and install Microsoft Client Component from https://www.microsoft.com/en-in/download/details.aspx?id=42038
#Microsoft SharePoint Client Component is mandatory to move further.
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.ProjectServer.Client.dll"

#replace CSV path
$path = "<Path of input CSV file>"
$siteURL = "<Replace With PWA URL>"  
$loginname = "<User Account>"  
$pwd = "<Password>"  
$securePassword = ConvertTo-SecureString $pwd -AsPlainText -Force
$creds = New-Object System.Management.Automation.PsCredential $loginname, $securePassword
$projContext = New-Object Microsoft.ProjectServer.Client.ProjectContext($siteURL)
$projContext.Credentials = $creds
$resources = $projContext.EnterpriseResources
$projContext.Load($resources)
$projContext.ExecuteQuery()
Import-Csv $path | ForEach-Object {
    $UserEmail=$_.ResourcesEmail
    <#Check user is available or not in resource center#>
    $resourcesToDeactivate = $resources | ? { $_.Email -eq $UserEmail -and $_.IsActive -eq $true }
    if($null -ne $resourcesToDeactivate)
    {
        $Name =$resourcesToDeactivate.Name
        Write-Host "$Name started to deactivating" -foreground yellow
        $resourcesToDeactivate.IsActive = $false
        $projContext.EnterpriseResources.Update()
        $projContext.ExecuteQuery()
        Write-Host "$Name account has been deactivated" -foreground green
    }
}
Write-Host "All users has been deactivated successfully" -foreground blue

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.