Ads

Friday, 17 February 2017

REST APIs to play with SharePoint Groups


Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

Source Code in JS file:
Here we can call different methods from html button click as per need to perform action.
------------------------------------------------------------------------------------------------------------------------
    'use strict';
     
    var hostweburl;
    var appweburl;
 
    $(document).ready(function ()
    {
        //Get the URI decoded URLs.
        hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
     
        // Load the js file and continue to load the page with information about the folders.
        // SP.RequestExecutor.js to make cross-domain requests
        $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js",creategroup);
    });
//--------------- ----------------------
     
    //Create Group
    function creategroup()
    {
        var executor;
         // Initialize the RequestExecutor with the app web URL.
        executor = new SP.RequestExecutor(appweburl);
     
        executor.executeAsync({
      url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups?@target= '" + hostweburl + "'",  
            method: "POST",
      body: “{'__metadata':{ 'type': 'SP.Group' }, 'Title':'New Group'}”,
            headers:  
            {  
                "content-type": "application/json; odata=verbose"
            },  
            success: function(data)  
            {  
                alert("Group CREATED SUCCESSFULLY ");  
            },  
            error: function(err)  
            {  
                alert("error: " + JSON.stringify(err));  
            }      });
    }
//--------------- ----------------------     

//Retrieve Groups
function retrivegroup()
{
    var executor;
    // Initialize the RequestExecutor with the app web URL.  
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups?@target= '" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: getGroupsSuccessHandler,
        error: function(err) {
            alert("error: " + JSON.stringify(err));
        }
    });
}

function getGroupsSuccessHandler(data)
{
    var jsonObject = JSON.parse(data.body);
    var Groups = document.getElementById("RetriveGroups");
    if (Groups.hasChildNodes())
    {
        while (Groups.childNodes.length >= 1)
        {
            Groups.removeChild(Groups.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++)
    {
        var allgroups = document.createElement("option");
        allgroups.value = results[i].Title;
        allgroups.innerText = results[i].Title;
        Groups.appendChild(allgroups);
    }
}
//--------------- ----------------------

//Delete Users in groups
function DeleteUser()
{
    var executor;
    var userEmail = "gowthamdev@Gauti.onmicrosoft.com";
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users/getbyemail('" + userEmail + "')?@target='" + hostweburl + "'",
        method: "POST",
        headers: {
            "X-HTTP-Method": "DELETE"
        },
        success: function(data) {
            alert("User Deleted successfully in SharePoint Group");
        },
        error: function(err) {
            alert("error: " + JSON.stringify(err));
        }
    });
}
//--------------- ----------------------

//GetUsers in group
function getuser()
{
    var executor;
    var userEmail = "gowthamdev@Gauti.onmicrosoft.com";
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users?@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: getUsersFromGroupSuccess,
        error: getUsersFromGroupError
    });
}
//Populate the selectUsers control after retrieving all of the users from group.
function getUsersFromGroupSuccess(data)
{
    var jsonObject = JSON.parse(data.body);
    var RetriveUsers = document.getElementById("RetriveUsers");
    if (RetriveUsers.hasChildNodes())
    {
        while (RetriveUsers.childNodes.length >= 1)
        {
            RetriveUsers.removeChild(RetriveUsers.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++)
    {
        var selectOption = document.createElement("option");
        selectOption.value = results[i].LoginName;
        selectOption.innerText = results[i].LoginName;
        RetriveUsers.appendChild(selectOption);
    }
}
function getUsersFromGroupError(data, errorCode, errorMessage)
{
    alert("Could not get users from group: " + errorMessage);
}
//--------------- ----------------------

    //Utilities
    // Retrieve a query string value.
    // For production purposes you may want to use a library to handle the query string.
    function getQueryStringParameter(paramToRetrieve)
    {
        var params = document.URL.split("?")[1].split("&");
        for (var i = 0; i < params.length; i = i + 1)
       {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve) return singleParam[1];
        }
    }

Refer Here: One

No comments:

Post a Comment

Ads