Tuesday, February 25, 2020

Update Workflow Task Outcome, % Complete and Status task columns using SharePoint rest api


var taskItemmetadata = {
            '__metadata': { 'type': $scope.wrkflstNameItemType },
            'Status': 'Completed',
            'PercentComplete': 1,
            'Task_x0020_Outcome': 'Approved'
        };
        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + ListName + "')/items(" + ItemID + ")",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(taskItemmetadata),
            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('Task Approved');
            },
            error: function (data) {
                alert("Error");
            }
        });

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>