Ads

Friday, 17 February 2017

REST API to get user news feeds in SharePoint 2013

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
var feedManagerEndpoint;

$(document).ready(function () {
    var appweburl;
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var param = params[i].split("=");
        if (param[0] === "SPAppWebUrl") appweburl = param[1];
    }
    feedManagerEndpoint = decodeURIComponent(appweburl)+ "/_api/social.feed";
    postToMyFeed();
});

function postToMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/Feed/Post",
        type: "POST",
        data: JSON.stringify( {  
            'restCreationData':{
                '__metadata':{  
                    'type':'SP.Social.SocialRestPostCreationData'
                },
                'ID':null,  
                'creationData':{  
                    '__metadata':{  
                        'type':'SP.Social.SocialPostCreationData'
                    },
                'ContentText':'This post was published using REST.',
                'UpdateStatusText':false
                }  
            }  
        }),
        headers: {  
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: getMyFeed,
        error: function (xhr, ajaxOptions, thrownError) {  
            alert("POST error:\n" + xhr.status + "\n" + thrownError);
        }
    });
}

function getMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/Feed",
        headers: {  
            "accept": "application/json;odata=verbose"
        },
        success: feedRetrieved,
        error: function (xhr, ajaxOptions, thrownError) {  
            alert("GET error:\n" + xhr.status + "\n" + thrownError);
        }
    });    
}

function feedRetrieved(data) {
    var stringData = JSON.stringify(data);
    var jsonObject = JSON.parse(stringData);  
    var feed = jsonObject.d.SocialFeed.Threads;  
    var threads = feed.results;
    var newscontent = "";
    for (var i = 0; i < threads.length; i++) {
        var thread = threads[i];
        var participants = thread.Actors;
        var owner = participants.results[thread.OwnerIndex].Name;
        newscontent += '<p>' + owner +  
            ' said "' + thread.RootPost.Text + '"</p>';
    }  
    $("#message").html(newscontent);  
}

REST API to retrieve list/libraries from sharepoint

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
$(document).ready(function () {
  //Get the URI decoded URLs.
  hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
  appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
 
  // Load the SP.RequestExecutor.js file.
  $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js", runCrossDomainRequest);
});
 
// Build and send the HTTP request.
function runCrossDomainRequest() {
  var executor = new SP.RequestExecutor(appweburl);  
  executor.executeAsync({
      url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists?@target='" + hostweburl + "'",
      method: "GET",  
      headers: { "Accept": "application/json; odata=verbose" },  
      success: getlistfromsite,  
      error: errorHandler  
  });
}    
//retrive all lists from site    
 function getlistfromsite(data) {
        var jsonObject = JSON.parse(data.body);
        var oists = document.getElementById("lists");
        if (oists.hasChildNodes())
        {
            while (oists.childNodes.length >= 1) {
                oists.removeChild(oists.firstChild);
            }
        }
        var results = jsonObject.d.results;
        for (var i = 0; i < results.length; i++)
        {
            var listcombined = document.createElement("option");
            listcombined.value = results[i].Title;
            listcombined.innerText = results[i].Title;
            oists.appendChild(listcombined);
        }
    }
     
    //error handler
function errorHandler(){
alert('error');
}

REST API to create list in SharePoint

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function createSPList() {  
   $.ajax(  
   {  
      url: appweburl +  
      "/_api/SP.AppContextSite(@target)/web/lists?@target='" +  
      hostweburl + "/sites/apps'",  
      type: "POST",  
      data: JSON.stringify({  
      '__metadata': { 'type': 'SP.List' },  
      'AllowContentTypes': true,  
      'BaseTemplate': 100,  
      'ContentTypesEnabled': true,  
      'Description': 'My TestCustomList description',  
      'Title': 'TestCustomList'  
   }),  
   headers: {  
      "accept": "application/json;odata=verbose",  
      "content-type": "application/json;odata=verbose",  
      "X-RequestDigest": $("#__REQUESTDIGEST").val()  
   },  
   success: successHandler,  
   error: errorHandler  
   });  
}  
function successHandler() {  
   $('#message').text('Success');  
}  
function errorHandler(data, errorCode, errorMessage) {  
   $('#message').text('Error ' + errorMessage);  
}    

REST API to upload file in doc lib

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
  1. <input id="getFile" type="file"/><br />  
  2. <input id="displayName" type="text" value="Enter a unique name" /><br />  
  3. <input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>  
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function uploadFile()
{
 
    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '/sites/apps/shared documents';
 
    // Get test values from the file input and text input page controls.
    // The display name must be unique every time you run the example.
    var fileInput = $('#getFile');
    var newName = $('#displayName').val();
 
    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {
 
        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {
 
            // Get the list item that corresponds to the uploaded file.
            var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function (listItem, status, xhr) {
 
                // Change the display name and title of the list item.
                var changeItem = updateListItem(listItem.d.__metadata);
                changeItem.done(function (data, status, xhr) {
                    alert('file uploaded successfully in Library);
                });
                changeItem.fail(onError);
            });
            getItem.fail(onError);
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);
 
    // Get the local file as an array buffer.
    function getFileBuffer()  
    {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[0]);
        return deferred.promise();
    }
 
    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer)  
    {
 
        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        var fileName = parts[parts.length - 1];
 
        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
            "{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')?@target='{3}'",
            appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);
 
        // Send the request and return the response.
        // This call returns the SharePoint file.
        return $.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }
 
    // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
    function getListItem(fileListItemUri)  
    {
 
        // Construct the endpoint.
        // The list item URI uses the host web, but the cross-domain call is sent to the
        // app web and specifies the host web as the context site.
        fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
        fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
         
        var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
            appWebUrl, hostWebUrl);
 
        // Send the request and return the response.
        return $.ajax({
            url: listItemAllFieldsEndpoint,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" }
        });
    }
 
    // Change the display name and title of the list item.
    function updateListItem(itemMetadata)
    {
 
        // Construct the endpoint.
        // Specify the host web as the context site.
        var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
        var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl);
 
        // Define the list item changes. Use the FileLeafRef property to change the display name.  
        // For simplicity, also use the name as the title.
        // The example gets the list item type from the item's metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
            itemMetadata.type, newName, newName);
 
        // Send the request and return the promise.
        // This call does not return response content from the server.
        return $.ajax({
            url: listItemEndpoint,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            }
        });
    }
}
 
// Display error messages.  
function onError(error)  
{
    alert(error.responseText);
}   

REST API to get file versions

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function versionfile()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync
    ({
 
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('/sites/apps/Shared Documents/RESTFolder.docx')/versions?@target='" + hostweburl + "'",
        method: "GET",
 
 
        headers:
 {
            "accept": "application/json; odata=verbose"
        },
        success: SuccessHandlerFileVersions,
        error: ErrorHandlerFileVersions
    });
}
 
/ Success Handler
    Function SuccessHandlerFileVersions (data)  
    {
        var FV;
        var jsonObject = JSON.parse(data.body);
        var results = jsonObject.d.results;
        for (var i = 0; i < results.length; i++)  
        {
            FV += results[i].VersionLabel + '\n';
        }
        / / Display the File versions
alert(FV);
}
// Error Handler
function ErrorHandlerFileVersions(data, errorCode, errorMessage)
{
    alert("Could not get the file versions: " + errorMessage);
}   

REST API to CheckIn file in Doc Lib

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function filecheckin()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/getfilebyserverrelativeurl('/sites/apps/Shared Documents/filename1.txt')/checkin(comment='Check-in comment.',checkintype=0)?@target='" + hostweburl + "'",
        method: "POST",
 
        headers:  
        {
            "accept": "application/json; odata=verbose"
        },
        success: function(data)
        {
            alert("success:File Checked IN");
        },
        error: function(err)  
        {
            alert("error: " + JSON.stringify(err));
        }
    });
}   

REST API to Add Template File in Document Library

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function addfile()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync({
 
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/getfolderbyserverrelativeurl('/sites/apps/Shared Documents')/files/addtemplatefile(urloffile='/sites/apps/Shared Documents/wikipage.aspx',templatefiletype=1)?@target='" + hostweburl + "'",
        method: "POST",
 
        headers:  
        {
            "accept": "application/json; odata=verbose"
        },
        success: function(data)
        {
            alert("success:WIKI PAGE CREATED SUCCESSFULLY ");
        },
        error: function(err)
        {
            alert("error: " + JSON.stringify(err));
        }
    });
}
   

REST API to Checkout File in Document Library

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function filecheckout()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/getfilebyserverrelativeurl('/sites/apps/Shared Documents/filename1.txt')/checkout?@target='" + hostweburl + "'",
        method: "POST",
 
        headers:  
        {
            "accept": "application/json; odata=verbose"
        },
        success: function(data)
        {
            alert("success:File Checked out ");
        },
        error: function(err)  
        {
            alert("error: " + JSON.stringify(err));
        }
    });
}   

REST API to Delete folder from document library

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
    <p>
        <b>Create Folder</b>
        <br />
        <input type="text" value="List Name Here" id=" DeleteFolder " />
        <button id="btnclick"> Delete Folder </button>
    </p>
</div>
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function FolderCreation()
{
    var executor;
 var getfoldername= document.getElementById("DeleteFolder").value;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
   url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('lib/Folder B')?@target='" + hostweburl + "'",
        method: "POST",
}        
          headers:  
            {
              "X-HTTP-Method":"DELETE"  
            },  
success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  
//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    alert("Folder Deleted successfully in Library");
}  
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not Delete a Folder in  Library: " + 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];
    }
}  

REST to create folder in doc libraries

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

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
    <p>
        <b>Create Folder</b>
        <br />
        <input type="text" value="List Name Here" id="CreateFolder" />
        <button id="btnclick">Create Folder</button>
    </p>
</div>
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function FolderCreation()
{
    var executor;
    var getfoldername= document.getElementById("CreateFolder").value;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
  url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('lib')/folders?@target='" + hostweburl + "'",
        method: "POST",
        body: "{ '__metadata':{ 'type': 'SP.Folder' }, 'ServerRelativeUrl':'Folder B' }",
}
          headers:  
           {
             "accept": "application/json; odata=verbose",
    "content-type": "application/json; odata=verbose"
            },  
success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  
//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    alert("Folder Created successfully in Library");
}
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not Create a Folder in  Library: " + errorMessage);
}

Use REST API to play with list & Document library

Here we will use NAPA tool to write the REST scripts.

Open developer site --> Open NAPA office 365 development tool --> Add new project
If you don't have NAPA tool then search and install NAPA App in your site.

In default.aspx page write your HTML like below so that we can trigger the methods as per our need
Ex:
  1. <button id="btn_ID_Here"> Delete Folder </button>  (Here we need jQuery to fire click event) 
  2. <input id="btn_ID_Here" type="button" value="Click" onclick="ButtonClickFunction()"/>  
Now we will replace the default "app.js " file with below codes

------------------------------------------ JS code Start Here --------------------------
'use strict';
var hostweburl;
var appweburl;
 // Get the URLs for the app web the host web URL from the query string.
$(document).ready(function ()
 {
    //Get the URI decoded URLs.
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
 
    // Resources are in URLs in the form:
    // web_url/_layouts/15/resource  
 
    // 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");

//Below one is optional to bind click function to normal html as in example 1 above
         $("#btn_ID_Here").click(function (event)
        {  
            ButtonClickFunction();  
            event.preventDefault();  
        }); 
});

// ------- Your Custom functions Starts Here
//Button Click Calling Function Here
function ButtonClickFunction()
{
     
}
//1. REST API to Upload file in document library
//2. REST API to Get File versions in document library
//3. REST API to CheckIn file
//4. REST API to Add template file in doc lib
//5. REST API to Checkout file
//6. REST to Delete folder from document library
//7. REST to Create folder in doc lib
//8. REST to Get all folders from root site


// ------- Your Custom functions Ends Here    

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];
    }
}
------------------------------------------JS Code End Here --------------------------

Once coding done specify the permissions that your app needs as in the following:
Choose the Properties button at the bottom of the page.

    In the Properties window, choose Permissions.
    In the Content category, set Write permissions for the Tenant scope.
    In the Social category, set Read permissions for the User Profiles scope.
    Close the Properties window.

Publish the App and Click the Trust it Button.









REST to Get all folders from root site

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

I recommend to go through REST for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
        <p>
            <b>Retrive Folders</b>
            <br />
            <select style="height:500px; width:510px" multiple="multiple" id="allFolders"></select>
        </p>
</div
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function getFolders() {
    var executor;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/folders?@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  

//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    var jsonObject = JSON.parse(data.body);
    var allFolders = document.getElementById("allFolders");
    if (allFolders.hasChildNodes()) {
        while (allFolders.childNodes.length >= 1) {
            allFolders.removeChild(allFolders.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++) {
        var Option = document.createElement("option");
        Option .value = results[i].Name;
        Option .innerText = results[i].Name;
        allFolders.appendChild(Option );
    }
}
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not retrieve  Folders: " + errorMessage);
}




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

Few formulas for calculated column in SharePoint list

Conditional formulas
You can use the following formulas to test the condition of a statement and return a Yes or No value, to test an alternate value such as OK or Not OK, or to return a blank or dash to represent a null value.
Use the IF function to perform this comparison.
Formula Description
=[Column1]>[Column2] Is Column1 greater than Column2? (Yes)
IF([Column1]<=[Column2], "OK", "Not OK") Is Column1 less than or equal to Column2? (Not OK)
=AND([Column1]>[Column2], [Column1]<[Column3]) Is 15 greater than 9 and less than 8? (No)
=OR([Column1]>[Column2], [Column1]<[Column3]) Is 15 greater than 9 or less than 8? (Yes)
Date and time formulas
To add a number of days to a date, use the addition (+) operator.
Formula Description
=[Column1]+[Column2]
Example:
Column1=6/9/2007
Colimn2=3
Adds 3 days to 6/9/2007 (6/12/2007)
To add a number of months to a date, use the DATE, YEAR, MONTH and DAY functions.
Formula Description
=DATE(YEAR([Column1]),MONTH([Column1])+[Column2],DAY([Column1]))
Example:
Column1=6/9/2007
Colimn2=3
Adds 3 months to 6/9/2007 (9/9/2007)
To add a number of years to a date, use the DATE, YEAR, MONTH and DAY functions.
Formula Description
=DATE(YEAR([Column1])+[Column2],MONTH([Column1]),DAY([Column1]))Example:
Column1=6/9/2007
Colimn2=3
Adds 3 years to 6/9/2007 (6/9/2010)
Calculate the difference between two dates
Use the DATEDIF function to perform this calculation.
Formula Description
=DATEDIF([Column1], [Column2],"d")
Example:
Column1=01-Jan-1995
Colimn2=15-Jun-1999
Returns the number of days between the two dates (1626)
=DATEDIF([Column1], [Column2],"ym")
Example:
Column1=01-Jan-1995
Colimn2=15-Jun-1999
Returns the number of months between the dates, ignoring the year part (5)
=DATEDIF([Column1], [Column2],"yd")
Example:
Column1=01-Jan-1995
Colimn2=15-Jun-1999
Returns the number of days between the dates, ignoring the year part (165)
Calculate the difference between two times
Formula Description
=TEXT([Column2]-[Column1],"h:mm:ss")
Example:
Column1=06/09/2007 10:35 AM
Colimn2=06/09/2007 3:30 PM
Hours, minutes and seconds between two times (4:55:00)
Mathematical formulas
Add/Subtract and Multipyl/Divide the two column numbers.
Formula Description
=[Column1]+[Column2]+[Column3]
Example:
Column1=4
Colimn2=5
Column3=6
Adds the values in the first three columns (15)
=[Column1]-[Column2]
Example:
Column1=7
Column2=5
Subtracts 5 from7 (2)
=[Column1]*[Column2]
Example:
Column1=7
Column2=5
Multiplies the numbers in the first two columns
=[Column1]/[Column2]
Example:
Column1=15
Column2=5
Divides
Change the case of text.
Formula Description
=UPPER([Column1])
Example:
Column1=Gowtham RAJAMANICKAM
Changes text to uppercase (GOWTHAM RAJAMANICKAM)
=LOWER([Column1])
Example:
Column1=Gowtham RAJAMANICKAM
Changes text to uppercase (gowtham rajamanickam)
Combine first and last names
Formula Description
==[Column1]&[Column2]
Example:
Column1=Gowtham
Column2= RAJAMANICKAM
Combines the two strings (GOWTHAM RAJAMANICKAM)
Notes

  • Calculated columns can only interact with data in the same “item” such as an item is a single task, event, document and so on
  • Calculated columns cannot interact with another row, or summaries (total and so on) of all of the lists
  • The formulas you write are basically Excel compatible formulas
  • Calculated columns can be reused by creating them as Site Columns (but this column can only reference other Site Columns!)
  • Column names with spaces or symbols must be enclosed in brackets “[Sale Amount']”
  • The [TODAY] and [ME] functions do not work in a calculated column, but can be used in columns referenced by a calculated column 
Refer Here: One,


New features in Sharepoint 2016


I will give my summarized points in my future post.
For the time being you can refer below external link.

Refere Here: One

Use REST API & Angular JS Implement custom search for lookup & person/group

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Create 2 custom lists
    Product Sales
    Phone

In Phone Custom list, I created  Title,Priority, and Demo single line text data type columns. And in second List i.e Produc Sales, I have created Product,Total_x0020_Sales,Sales_x0020_Target,SalesPerson,LPhone and SalesName.
    Here,"LPhone" is Lookup Field link with our Phone Custom list field of Title.
    "SalesName" is person/Group filed type and Show Field is FirstName.

angularGet.js (Upload it in Site Asset library of SharePoint along with angular js file)
var spApp = angular
                .module("spApp", [])
                .controller("viewItemController", function ($scope, $http) {
                    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Product%20Sales')/items?$select=Product,Total_x0020_Sales,Sales_x0020_Target,SalesPerson,SalesName/FirstName,LPhone/Title&$expand=LPhone,SalesName";
                    $http(
                    {
                        method: "GET",
                        url: url,
                        headers: { "accept": "application/json;odata=verbose" }
                    }
                    ).success(function (data, status, headers, config) {
      var dataResults=data.d.results;
      var item = data.d.results[1];  
         
                        $scope.contacts = dataResults;
       $scope.productItems = function(item)
      {
       
        if($scope.searchText==undefined)
       {
         return true;
        }
        else{
         if((item.SalesPerson.toLowerCase().indexOf($scope.searchText.toLowerCase())!=-1)||(item.Product.toLowerCase().indexOf($scope.searchText.toLowerCase())!=-1))
         {
          return true;
         }
        }
        return false;
       }
                    }).error(function (data, status, headers, config) {
                    });
                   
                })

Create.HTML file: (Upload in site asset library or write in content editor webpart)
<html>

<head>
    <script type="text/javascript" src="/SiteAssets/angular.min.js"></script>
    <script type="text/javascript" src="/SiteAssets/angularGet.js"></script>
</head>

<body>
    <h3>View Contacts</h3>
    <hr/>
    <div ng-app="spApp">
        <div ng-controller="viewItemController"> <input type="text" placeholder="Product&SalesPerson" ng-model="searchText" /> <br/><br/>
            <table>
                <tr>
                    <th>Product</th>
                    <th>Total Sales</th>
                    <th>Sales Target</th>
                    <th>Sales Peron</th>
                    <th>LookUPFieldData</th>
                    <th>Person/GroupField</th>
                </tr>
                <tr ng-repeat="contact in contacts|filter:productItems">
                    <td>{{contact.Product}}</td>
                    <td>{{contact.Total_x0020_Sales}}</td>
                    <td>{{contact.Sales_x0020_Target}}</td>
                    <td>{{contact.SalesPerson}}</td>
                    <td>{{contact.LPhone.Title}}</td>
                    <td>{{contact.SalesName.FirstName}}</td>
                </tr> <br /> </table>
        </div>
        <hr /> </body>

</html>

Now finally add this in share point page add see the result. or open that html page if uploaded in site asset library and check.


News Tickers in SharePoint 2013 using JQuery

Lets create a custom list called "News"
We will get news text from title of this list and display in SharePoint page page

VS --> New Project --> SP 2013 empty project --> Deploy as a farm solution
Add new item --> Visual web part
Add jQuery reference to layout folder & add its reference in ascx page of web part

Add script in same page:
< script > $(document).ready(function() {
    $('#NewsTicker').vTicker({
        speed: 500,
        pause: 3000,
        showItems: 1,
        animation: 'fade',
        mousePause: true,
        direction: 'up' /*Text direction*/
    });
}); < /script>

Add style CSS in same page:
<style type="text/css" media="all">
    #NewsTicker
    {
        width: 844px;
        margin: auto;
    }

    #NewsTicker ul li div
    {
        height:30px;
        background: Yellow;
    }

    <div style="width:1310px; height:30px; border-style:solid; border-width:2px; border-color:#FFCB05">
        <div style="float:left;background-color:White; height: 27px; width: 118px;">
            <h2 style="font-family:Arial; font-size:22px; background-color:#FFCB05; color:Black;">News</h2>
        </div>
        <div id="NewsTicker" style="float:left; padding-left:15px; font-size:24px; font-family:Arial; height: 29px;">
            <ul style="width: 920px">
                <asp:Literal ID="ltNews" runat="server" Text=""></asp:Literal>
            </ul>
        </div>
    </div>
</style>

Now write C# code in page load to bind data:
private void BindData()
{
    Guid siteId = SPContext.Current.Site.ID;
    Guid webId = SPContext.Current.Web.ID;
    StringBuilder sb = new StringBuilder();
    SPSecurity.RunWithElevatedPrivileges(delegate
    {
        using(SPSite site = new SPSite(siteId))
        {
            using(SPWeb web = site.OpenWeb(webId))
            {
                SPList list = web.Lists.TryGetList("News"); /*Create the list*/
                if (list != null)
                {
                    foreach(SPListItem item in list.Items)
                    {
                        sb.AppendLine("<li>");
                        sb.AppendLine("<div>");
                        sb.AppendLine(item.Title); /*Get the title column*/
                        sb.AppendLine("</div>");
                        sb.AppendLine("</li>");
                    }
                }

            }
        }
    });
    ltNews.Text = sb.ToString();
}

Finally deploy and add this webpart in page to see the result

Initiation form in SharePoint designer workflows

It is the king of form used to get user inputs before stating of the workflow.

Lets create one workflow to claim expense for approval.
    If an expense amount is <= Max-Limit, then set Status = Approved
    If an expense amount is > Max-Limit then set Status = Not-Approved
Here we create a Max-Limit parameter that will be captured on each workflow start.

Steps:

  1. Create one custom list called "Expense"
    1. Columns like Description, Amount, Status
  2. Create one list workflow on this list
  3. Click "Initiation Form Parameters" in ribbon 
  4. In page add one parameter "Max-Limit" --> set values like default, min & Max
  5. Now in designer workflow create the logic like below

Now save and publish the workflow

Testing:
  1. Now add one item in list
  2. Then try to run the workflow. While you start it will show up one form to provide max expense parameter value. 





AngularJS in a SharePoint 2013 page to add list item using CSOM

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Lets create one simple list form in angular to submit list item.

  1. Create one custom list "Employee Details"
    • FirstName, LastName, Location 
  2. Add one script editor web part to add script in page
    • Add web part --> Media & Content --> Script Editor --> ok to Add it
  3. Edit webpart in "edit Snippet" and write below codes

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  
<script>  
    function ContactsCtrl($scope) {  
        $scope.contact = { firstName: "", lastName: "", location: "" };  
        $scope.addContact = function ($event) {  
            var x = $scope.contact;  
            $event.preventDefault();  
            var clientContext = new SP.ClientContext.get_current();  
            var web = clientContext.get_web();  
            var list = web.get_lists().getByTitle('Employee Details');  
  
            // create the ListItemInformational object  
            var listItemInfo = new SP.ListItemCreationInformation();  
            // add the item to the list  
            var listItem = list.addItem(listItemInfo);  
            // Assign Values for fields  
            listItem.set_item('Title', x.firstName);  
            listItem.set_item('LastName', x.lastName);  
            listItem.set_item('FullName', x.firstName + " " + x.lastName);  
            listItem.set_item('Location', x.location);  
  
            listItem.update();  
  
            clientContext.executeQueryAsync(  
                Function.createDelegate(this, onQuerySucceeded),  
                Function.createDelegate(this, onQueryFailed)  
            );  
  
        };  
  
        onQuerySucceeded = function () {  
            alert('Successfully updated the contact');  
        }  
  
        onQueryFailed = function (sender, args) {  
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
        }  
    }  
</script>  
   
<h1>Employee Information:</h1>  
<br />  
<div ng-app="">  
    <div ng-controller="ContactsCtrl">  
        <strong>Emp First Name</strong>  
        <input type="text" ng-model="contact.firstName" /><br />  
        <br />  
        <strong>Emp Last Name</strong>   
        <input type="text" ng-model="contact.lastName" /><br />  
        <br />  
        <strong>Emp Location </strong> 
        <input type="text" ng-model="contact.location" /><br />  
        <br />  
        <input type="submit" value="Submit" ng-click="addContact($event)" />  
    </div>  
</div>  


Wednesday, 15 February 2017

Enable developer dashboard using powershell in SharePoint 2013


$content = ([Microsoft.SharePoint.Administration.SPWebService]::ContentService)
$dashboardSettings =$content.DeveloperDashboardSettings
$dashboardSettings.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::On
$dashboardSettings.Update()

Tuesday, 14 February 2017

Start list workflow from powrshell

$siteURL="Site URL"
$listName="List Name"
$site=Get-Spsite $siteURL
$web=$site.RootWeb
$list=$web.Lists[$listName]
$item=$list.Items[0]
$manager=$site.WorkFlowManager
$association=$list.WorkFlowAssociations[0]
$data=$association.AssociationData
$wf=$manager.StartWorkFlow($item,$association,$data,$true)

Get "CreatedBy" and "ModifiedBy" from list using client coding

<script language="ecmascript" type="text/ecmascript">

        var listItem;
        var list;
        var clientContext;

        function getFieldUserValue() {

            this.clientContext = SP.ClientContext.get_current();
            if (this.clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("CustomList");
                this.listItem = list.getItemById(1);
                clientContext.load(this.listItem);
                this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }

        function OnLoadSuccess(sender, args) {
            var fieldUserValueCreatedBy = this.listItem.get_item("Author");
            var fieldUserValueModifiedBy = this.listItem.get_item("Editor");
            alert("Created By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n Modified By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n");
        }


        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>

    <input id="btnGetFieldUserValue" onclick="getFieldUserValue()" type="button" value="Get Created by and Modified by" />

Connect SharePoint online using CSOM from console application


Create new console application project in VS 2013
R-click on References in the Solution Explorer --> click on Manage NuGet Packages.
Search for Microsoft.SharePointOnline.CSOM and then click on Install

Code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Security;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.SharePoint.Client;
    namespace CSOMOffice365  
    {
        class Program  
        {
            static void Main(string[] args)  
          {
                string userName = "BlaBla.onmicrosoft.com";
                Console.WriteLine("Enter password.");
                SecureString password = GetPassword();  
                using(var clientContext = new ClientContext("SharePoint site URL"))  
                {
                    // SharePoint Online Credentials
                    clientContext.Credentials = new SharePointOnlineCredentials(userName, password);  
                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                    Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
                    Console.ReadLine();
                }
            }
            private static SecureString GetPassword()
          {
                ConsoleKeyInfo info;
                SecureString securePassword = new SecureString();
                do  
                {
                    info = Console.ReadKey(true);
                    if (info.Key != ConsoleKey.Enter)  
                    {
                        securePassword.AppendChar(info.KeyChar);
                    }
                }
                while (info.Key != ConsoleKey.Enter);
                return securePassword;
            }
        }
    }


List search using Angular JS

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Lets assume to do search in a custom list called "ListA"

Create one js file "ListSearch.js" and upload in any library
var spApp = angular.module("spApp", []).controller("viewItemController", function($scope, $http) {
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('ListA')/items";
    $http({
        method: "GET",
        url: url,
        headers: {
            "accept": "application/json;odata=verbose"
        }
    }).success(function(data, status, headers, config) {
        var dataResults = data.d.results;
        $scope.contacts = dataResults;
    }).error(function(data, status, headers, config) {});
})

Create one html file with below html or we can put it in a content editor to get the result.

    <html>
   
    <head>
        <script type="text/javascript" src="/SiteAssets/jquery-3.0.0.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/angular.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/listSearch.js"></script>
    </head>
   
    <body>
        <h3>View Contacts</h3>
        <hr/>
        <div ng-app="spApp">
            <div ng-controller="viewItemController"> Search Items:<input type="text" placeholder="searchItems" ng-model="searchText" />
                <table>
                    <tr>
                        <th>Product</th>
                        <th>Total Sales</th>
                        <th>Sales Target</th>
                    </tr>
                    <tr ng-repeat="contact in contacts|filter:searchText">
                        <td>{{contact.Product}}</td>
                        <td>{{contact.Total_x0020_Sales}}</td>
                        <td>{{contact.Sales_x0020_Target}}</td>
                    </tr> <br /> </table>
            </div>
            <hr /> </body>
   
    </html>



Ads