Tuesday, February 25, 2020

Update multi user people picker column using SharePoint rest api

var userid1 = _spPageContextInfo.userId;
var userid2 = 1208;
var multiusersDd = { "results": [userid, userid2] };

var item = {
            '__metadata': { 'type': $scope.ppguaSectionDocumentsItemType },
            'ApprovalStatus': 'Rejected',
           'AssignedToId': userid,
            'Stage': $scope.currentStage
        };

        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + ListName + "')/items(" + ItemID + ")",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": "*"
            },
            success: function (data) {
                //alert(data.d.ID);
                console.log('Section stage updated');
             
            },
            error: function (data) {
                alert("Error");
            }
        });

Update single user people picker column using SharePoint rest api


var userid = _spPageContextInfo.userId;

var item = {
            '__metadata': { 'type': $scope.ppguaSectionDocumentsItemType },
            'ApprovalStatus': 'Rejected',
           'AssignedToId': userid,
            'Stage': $scope.currentStage
        };

        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + ListName + "')/items(" + ItemID + ")",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": "*"
            },
            success: function (data) {
                //alert(data.d.ID);
                console.log('Section stage updated');
               
            },
            error: function (data) {
                alert("Error");
            }
        });

Wednesday, February 19, 2020

Site Collection Backup and Restore process using SharePoint 2010 Management Shell


Click Start
Go to All Programs
Go to Microsoft SharePoint 2010 Products
Open SharePoint 2010 Management Shell
A PowerShell command prompt will appear and you need to format the following to fit the backup for your site.
Backup-SPSite -Identity SiteCollectionURLHere -Path BackupFilePathHere [-Force] [-NoSiteLock] [-UseSqlSnapshot] [-Verbose]
I recommend creating a folder where you can place these backups before starting the backup process so they aren’t just chill in on the C: drive of your SharePoint server; just a thought.  Here is a little explanation of those additional parameters that are inside the braces [ ]
Force – Include this if you want to override a backup with the same name
NoSiteLock – Will prevent the site from going to Read only mode while the backup is being taken.  A small warning, if someone changes content on the site while the backup is being created and according to Microsoft “might lead to possible data corruption”
UseSQLSnapshot – A database snapshot will be taken before the backup begins and the backup will be done off the snapshot. The advantage is that changes can be made to the site while the backup process is running without fear of corruption.  The snapshot will be deleted automatically when the backup is completed.  You don’t need to specify the -NoSiteLock parameter when using this method
Here is a simple example of what the script may look like if you want to just do a backup:

Backup-SPSite -Identity https://contoso/  -Path D:SharePointBackupsBISite20-2-2020.bak
To do site restores the syntax is almost just as easy.  You will need to use the same SharePoint 2010 Management Shell as doing the backup.
Restore-SPSite -Identity NewSiteCollectionURLHere -Path BackupFilePathHere [-DatabaseServer DatabaseServerNameHere] [-DatabaseName ContentDatabaseNameHere] [-HostHeader HostHeaderHere] [-Force] [-Verbose]
DatabaseServer – Specify the server for the content database
DatabaseName – Specify the name of the content database
HostHeader – URL of the Web application that will hold the host-named site collection
Force – Overwrite the site collection if it exists
GradualDelete – Recommended for site collections over 1 Gig in size, existing data is marked as deleted and gradually removed over time by a job rather than all at once to reduce the performance hit of deleting large amounts of data


Friday, February 14, 2020

Copy File using copyTo action from one Library to another Library using JSOM

function copyFiles(sourceLib, destLib) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var file = web.getFileByServerRelativeUrl("/sites/HRD/Test1/Revised%20PDPA.doc");
ctx.load(file);
ctx.executeQueryAsync(
function () {
console.log("Got the source folder right here!");
var title = file.get_name();
alert(title);
var destLibrary = '/sites/HRD/Test2/Test Folder1';
var destLibUrl = destLibrary + "/" + file.get_name();
file.copyTo(destLibUrl, true);
ctx.executeQueryAsync(function () {
console.log("Files moved successfully!");
getFileWithProperties('/sites/HRD/Test2/Test Folder1/Revised%20PDPA.doc',
function (file) {
var listItem = file.get_listItemAllFields(); //get list item for a file
var itemProperties = { 'Title': 'New Order2' };
//update list item
updateListItem(listItem, itemProperties,
function () {
console.log('File is updated succesfully');
},
function (sender, args) {
console.log(args.get_message());
}
);
},
function (sender, args) {
console.log(args.get_message());
});
}, function (sender, args) { console.log("error: ") + args.get_message() });
},
function (sender, args) { console.log("Sorry, something messed up: " + args.get_message()); }
);
}

function updateListItem(listItem, properties, success, error) {
var ctx = listItem.get_context();
for (var propName in properties) {
listItem.set_item(propName, properties[propName])
}
listItem.update();
ctx.executeQueryAsync(
function () {
success();
},
error
);
}

function getFileWithProperties(url, success, error) {
var ctx = SP.ClientContext.get_current();
var file = ctx.get_web().getFileByServerRelativeUrl(url); //get file
ctx.load(file, 'ListItemAllFields');
ctx.executeQueryAsync(
function () {
success(file);
},
error
);
}

Sunday, December 23, 2018

Update SharePoint User Profile work email into specific Web Application

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
$WebAppURL="http://contoso.com"
$UserAccount="i:0#.w|Contoso\Nagaraju.Pattem"
 
#Update Email for all sites in the web application
Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All | Foreach-object {
     
    Write-host "Processing:" $_.Rootweb.URL
 
    #Get the User's Current Display Name and E-mail
    $User = Get-SPUser -Identity $UserAccount -Web $_.Rootweb.URL
 
    if($User -ne $null)
    {
        Set-SPUser -Identity "i:0#.w|Contoso\NAgaraju.Pattem" -Email "Naga@Contoso.com" –Web $_.Rootweb.URL
    }
}

Tuesday, December 11, 2018

How to check if user exists in SharePoint groups or not using JSOM


<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(LoadGroups, "sp.js");

var group;
var users;
var ctx;
var groupCollection;
var user;
var currentuser;
//Add SharePoint Group id into below array
var userGroupIDs = [5,3];
var redirectPage = true;
var currentIndex = 0;
function LoadGroups() {

    IsUserExists(userGroupIDs[0]);
}

function IsUserExists(groupID) {
    ctx = SP.ClientContext.get_current();
    groupCollection = ctx.get_web().get_siteGroups();
    currentuser = ctx.get_web().get_currentUser();

    group = groupCollection.getById(groupID);
    ctx.load(group);
    ctx.load(currentuser);
    ctx.executeQueryAsync(Function.createDelegate(this, this.OnGetGroupSuccess), Function.createDelegate(this, OnFailure));
}

function OnGetGroupSuccess() {
    users = group.get_users();
    ctx.load(users);
    ctx.executeQueryAsync(Function.createDelegate(this, this.OnGetuserSuccess), Function.createDelegate(this, OnFailure));
}

function OnGetuserSuccess() {
debugger
    currentIndex++;
    var userEnumerator = users.getEnumerator();
    while (userEnumerator.moveNext()) {
        var user = userEnumerator.get_current();
        if (user.get_id() == currentuser.get_id()) {
            redirectPage = false;
            //alert("User Exists");
            break;
        }
        else {
        }
    }

    if (currentIndex == userGroupIDs.length) {
        if (redirectPage) {
            redirectLandingPage();
        }
    }else{
        IsUserExists(userGroupIDs[currentIndex]);
}

}

function OnFailure(sender, args) {
    //alert("Failed to execute IsCurrentUserMemberOfGroup method");

    currentIndex++;
    if (currentIndex == userGroupIDs.length) {
        if (redirectPage) {
            redirectLandingPage();
        }
    }else{
        IsUserExists(userGroupIDs[currentIndex]);
}
}

function redirectLandingPage() {
    window.location.href = "https://contoso";
}
</script>  

Monday, January 16, 2017

Configure Manage metadata Top Navigation in SharePoint Online using PowerShell/CSOM

Steps to Create a Top Navigation using Taxonomy.

Create a CSV file with below columns with sample data.


Use the below PowerShell/CSOM script to read the data from CSV file and create term set in Manage metadata navigation.

#Configure meta data navigation
function ConfigureGlobalNavigation()
{

begin{
try
{

Write-Host "Configure a top navigation menu..."  -ForegroundColor Green
Add-Content -Path $LogFileName -Value([string]::Concat("Configure a top navigation menu...")) 

$MMS = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($context)
$context.Load($MMS)
$context.ExecuteQuery()

#Retrieve Term Stores
$TermStores = $MMS.TermStores
$context.Load($TermStores)
$context.ExecuteQuery()

#Bind to Term Store
$TermStore = $TermStores[0]
$context.Load($TermStore)
$context.ExecuteQuery()
$TermStoreId=$TermStore.Id

#Bind to Group
#Update the Group name https://contoso.com/_layouts/15/termstoremanager.aspx
$Group = $TermStore.Groups.GetByName("ContosoSiteCollection")
$context.Load($Group)
$context.ExecuteQuery()

#Bind to Term Set
$TermSets = $group.TermSets
$context.Load($TermSets)
$context.ExecuteQuery()
$TermSet = $TermSets | Where-Object {$_.Name -eq $SelectedNavigationName}  

if($TermSet)
{
Write-Host  $SelectedNavigationName   "Top navigation menu already configured: " $SelectedNavigationName   -foregroundcolor red
Add-Content -Path $LogFileName -Value([string]::Concat("Top navigation menu already configured", $SelectedNavigationName)) 
$TermSet = $group.TermSets.GetByName($SelectedNavigationName)
$context.Load($TermSet)
$context.ExecuteQuery()

}
else
{

$TermSet = $Group.CreateTermSet($SelectedNavigationName, [System.Guid]::NewGuid(), $TermStore.DefaultLanguage)
$TermSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True") 
$TermSet.CustomSortOrder=$true
$context.load($TermSet)
$context.ExecuteQuery()

Add-Content -Path $LogFileName -Value([string]::Concat("Top navigation group is created: ", $SelectedNavigationName))
$TermSetId=$TermSet.Id

#$CSVGlobalNavigationFilePath - Update the CSV file path
$L1Terms = Import-CSV $CSVGlobalNavigationFilePath

Foreach ($row in $L1Terms)
{

if(($row.Level2Title.Trim().Length  -eq 0) -and ($row.Level3Title.Trim().Length  -eq 0) )
{

$Level1TitleAdd = $TermSet.CreateTerm(($row.Level1Title),1033,[System.Guid]::NewGuid().toString())
if($row.Level1Title -eq "Home")
{
$Level1TitleAdd.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl","/"+$SubSiteURL.Split("/")[3]+"/"+$SubSiteURL.Split("/")[4]+"/"+$SubSiteURL.Split("/")[5])
}
else
{
$Level1TitleAdd.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", $row.URL)
}
$context.Load($Level1TitleAdd)
$context.ExecuteQuery()
$GlobalNavigationTermsGuids+=$Level1TitleAdd.Id.ToString()+":"
Add-Content -Path $LogFileName -Value([string]::Concat("Top navigation L1 Title Created: ", $row.Level1Title))
}
if(($row.Level2Title.Trim().Length  -gt 0) -and ($row.Level3Title.Trim().Length  -eq 0))
{
$Level2TitleAdd = $Level1TitleAdd.CreateTerm(($row.Level2Title),1033,[System.Guid]::NewGuid().toString())
$Level2TitleAdd.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", $row.URL)
$context.Load($Level2TitleAdd)
$context.ExecuteQuery()
Add-Content -Path $LogFileName -Value([string]::Concat("Top navigation L2 Title Created: ", $row.Level2Title))
}
if(($row.Level1Title.Trim().Length  -gt 0) -and ($row.Level2Title.Trim().Length  -gt 0) -and ($row.Level3Title.Trim().Length  -gt 0))
{
$Level3TitleAdd = $Level2TitleAdd.CreateTerm(($row.Level3Title),1033,[System.Guid]::NewGuid().toString())
$Level3TitleAdd.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", $row.URL)
$context.Load($Level3TitleAdd)
$context.ExecuteQuery()
Add-Content -Path $LogFileName -Value([string]::Concat("Top navigation L3 Title Created: ", $row.Level3Title))
}
}
$TermSet.CustomSortOrder=$GlobalNavigationTermsGuids;
$context.Load($TermSet)
$context.ExecuteQuery()

#set both current and global navigation settings to managed
$taxonomySession = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($context)
$navigationSettings = New-Object Microsoft.SharePoint.Client.Publishing.Navigation.WebNavigationSettings $context, $context.Web

#set both current and global navigation settings to managed
$navigationSettings.CurrentNavigation.Source = "taxonomyProvider"

$navigationSettings.CurrentNavigation.TermStoreId=$TermStoreId
$navigationSettings.CurrentNavigation.TermSetId=$TermSetId

$navigationSettings.GlobalNavigation.Source = "taxonomyProvider"
$navigationSettings.GlobalNavigation.TermStoreId=$TermStoreId
$navigationSettings.GlobalNavigation.TermSetId=$TermSetId

$navigationSettings.Update($taxonomySession)
$context.ExecuteQuery()

Write-Host "Top navigation menu configuration completed" -foregroundcolor green
Add-Content -Path $LogFileName -Value([string]::Concat("Top navigation menu configuration completed"))

}
}
catch
{
Write-Host  $_.Exception.Message -foregroundcolor Red 
Add-Content -Path $LogFileName -Value([string]::Concat("Configure Global Navigation :",$_.Exception.Message))
}
}
 end {
Write-Host "Top navigation menu configuration completed" -foregroundcolor green     
}

}


Cls
#Specify tenant admin and site URL
$User = "Naga@contoso.com"
$SiteURL = "https://*****.sharepoint.com/"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
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.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$SiteURL'" -ForegroundColor Green
}
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds


ConfigureGlobalNavigation

Happy coding..