Thursday, July 14, 2016

SharePoint 2013 REST API - Basic Operations

In earlier blogpost I had covered SharePoint REST implementation with Jquery Ajax. Below example was created based on SharePoint based js library. I had created a simple aspx page using SharePoint designer that would perform following activities listed below that are targeted towards specific list called as 'PersonInformation' that contains mainly three columns called as Name, Age, Country. • Insert an item • Retrieve items • Search based on list item Id • Update an item • Delete an iem The aspx page is created with html controls and are attached to javascript button click events that would execute SharePoint REST API calls on button click. For debugging purpose one can use fiddler to identify the reqest and response generated. Various keywords that are used while creating REST API request are detailed in MSDN article. [code] <%@ Page Inherits="System.Web.UI.Page" MasterPageFile="~masterurl/default.master" Title="REST Demo" meta:progid="SharePoint.WebPartPage.Document" meta:webpartpageexpansion="full" %>
[/code]

Saturday, July 9, 2016

SharePoint 2013 REST API folder/file operations

Below example shows the usage of REST API to create folder, delete folder, add text to folder, fetch the content/update content of file. Below example is taken from pluralsight as reference for my practise.

[code]
<%@ Page Inherits="System.Web.UI.Page" MasterPageFile="~masterurl/default.master" Title="REST Demo"  meta:progid="SharePoint.WebPartPage.Document" meta:webpartpageexpansion="full" %>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script type='text/javascript'>
        var formdigest;
        $(document).ready(function () {
            $("#createFolderButton").click(function (event) {
                createFolder();
                event.preventDefault();
            });

            $("#deleteFolderButton").click(function (event) {
                deleteFolder();
                event.preventDefault();
            });

            $("#createFileButton").click(function (event) {
                createFile();
                event.preventDefault();
            });

            $("#deleteFileButton").click(function (event) {
                deleteFile();
                event.preventDefault();
            });

            $("#getFileButton").click(function (event) {
                getFile();
                event.preventDefault();
            });

            $("#updateFileButton").click(function (event) {
                updateFile();
                event.preventDefault();
            });
            $.getScript("/_layouts/15/SP.RequestExecutor.js", loadPage);
        });

        function loadPage() {
            getFormDigest();
            getFolders();
        }

        //Folders
        //Retrieve all of the site's folders.
        function getFolders() {
            var executor;
            // Initialize the RequestExecutor with the app web URL.
            executor = new SP.RequestExecutor("/sites/Practise/");
            executor.executeAsync({
                url: "/sites/Practise/_api/web/Folders",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: getFoldersSuccessHandler,
                error: getFoldersErrorHandler
            });
        }

        //Create a new folder.
        function createFolder() {
            getFormDigest();
            var executor;
            // Initialize the RequestExecutor with the app web URL.
            executor = new SP.RequestExecutor("/sites/Practise/");
            var serverRelativeUrl = $('#createFolderBox')[0].value;
            var metadata = "{ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '" + serverRelativeUrl + "'}"
            executor.executeAsync({
                url: "/sites/Practise/_api/web/Folders",
                method: "POST",
                body: metadata,
                headers: { "Accept": "application/json; odata=verbose", "content-type": "application/json; odata=verbose", "X-RequestDigest": formdigest, "content-length": metadata.length },
                success: createFolderSuccessHandler,
                error: createFolderErrorHandler
            });
        }

        //Delete the selected folder.
        function deleteFolder() {
            getFormDigest();
            var executor;
            executor = new SP.RequestExecutor("/sites/Practise");
            var selectedFolder = $('#selectFolderBox')[0].value;
            executor.executeAsync({
                url: "/sites/Practise/_api/web/GetFolderByServerRelativeUrl('" + selectedFolder + "')",
                method: "POST",
                headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": formdigest, "X-HTTP-Method": "DELETE", "IF-MATCH": "*" },
                success: deleteFolderSuccessHandler,
                error: deleteFolderErrorHandler
            });
        }

        //Files

        //Retrieve all of the files for the selected folder.
        function getFiles() {
            var executor;
            executor = new SP.RequestExecutor("/sites/Practise");
            var selectedFolder = $('#selectFolderBox')[0].value;

            executor.executeAsync({
                url: "/sites/Practise/_api/web/GetFolderByServerRelativeUrl('" + selectedFolder + "')/Files",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: getFilesSuccessHandler,
                error: getFilesErrorHandler
            });
        }

        //Create a new file.
        function createFile() {
            getFormDigest();
            var executor;
            // Initialize the RequestExecutor with the app web URL.
            executor = new SP.RequestExecutor("/sites/Practise");
            var serverRelativeUrl = $("#selectFolderBox")[0].value;
            var fileUrl = $("#createFileBox")[0].value;
            var fileContent = $("#submitTextFile")[0].value;
            executor.executeAsync({
                url: "/sites/Practise/_api/web/GetFolderByServerRelativeUrl('" + serverRelativeUrl + "')/Files/add(url='" + fileUrl + "',overwrite='true')",
                method: "POST",
                body: fileContent,
                headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": formdigest, "content-length": fileContent.length },
                success: createFileSuccessHandler,
                error: createFileErrorHandler
            });
        }

        //Update a file.
        function updateFile() {
            getFormDigest();
            var executor;
            executor = new SP.RequestExecutor("/sites/Practise");
            var serverRelativeUrl = $('#selectFolderBox')[0].value;
            var fileUrl = $('#selectFileBox')[0].value;
            var fileContent = $('#submitTextFile')[0].value;
            executor.executeAsync({
                url: "/sites/Practise/_api/web/GetFileByServerRelativeUrl('/sites/Practise/" + serverRelativeUrl + "/" + fileUrl + "')/$value",
                method: "POST",
                body: fileContent,
                headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": formdigest, "content-length": fileContent.length, "X-HTTP-Method": "PUT" },
                success: updateFileSuccessHandler,
                error: updateFileErrorHandler
            });
        }

        //Retrieve the selected file and save it locally.
        function getFile() {
            var executor;
            executor = new SP.RequestExecutor("/sites/Practise");
            var serverRelativeUrl = $('#selectFolderBox')[0].value;
            var fileUrl = $('#selectFileBox')[0].value;
   var url = "/sites/Practise/_api/web/GetFileByServerRelativeUrl('/sites/Practise/" + serverRelativeUrl + "/" + fileUrl + "')/$value";
            executor.executeAsync({
                url: url,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: getFileSuccessHandler,
                error: getFileErrorHandler
            });
        }

        //Delete a file.
        function deleteFile() {
            getFormDigest();
            var executor;
            executor = new SP.RequestExecutor("/sites/Practise");
            var serverRelativeUrl = $('#selectFolderBox')[0].value;
            var fileUrl = $('#selectFileBox')[0].value;

            executor.executeAsync({
                url: "/sites/Practise/_api/web/GetFileByServerRelativeUrl('/sites/Practise/" + serverRelativeUrl + "/" + fileUrl + "')",
                method: "POST",
                headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": formdigest, "X-HTTP-Method": "DELETE", "IF-MATCH": "*" },
                success: deleteFileSuccessHandler,
                error: deleteFileErrorHandler
            });
        }

        //Store the value of the form digest.
        function contextSuccessHandler(data) {
            var jsonObject = JSON.parse(data.body);
            formdigest = jsonObject.d.GetContextWebInformation.FormDigestValue;
        }

        //Populate the selectFolderBox control after retrieving all of the site's folders.
        function getFoldersSuccessHandler(data) {
            var jsonObject = JSON.parse(data.body);
            $('#selectFolderBox').empty();
            $.each(jsonObject.d.results, function (val, result) {
                $('#selectFolderBox').append(
                    $('<option></option>').val(result.Name).html(result.Name)
                );
            });
            getFiles();
        }

        //Save the file locally after it has been retrieved.
        function getFileSuccessHandler(data) {
        alert(data.body);
        $('#submitTextFile').val(data.body);
            //save_content_to_file(data.body, $('#selectFileBox')[0].value);
        }

        //Populate the selectFileBox control after retrieving all of the files in the selected folder.
        function getFilesSuccessHandler(data) {
            var jsonObject = JSON.parse(data.body);
            $('#selectFileBox').empty();
            $.each(jsonObject.d.results, function (val, result) {
                $('#selectFileBox').append(
                    $('<option></option>').val(result.Name).html(result.Name)
                );
            });
        }

        //Reload the page information after creating a new folder.
        function createFolderSuccessHandler(data) {
            getFolders();
            getFiles();
        }

        //Reload the page information after deleting a folder.
        function deleteFolderSuccessHandler(data) {
            getFolders();
            getFiles();
        }

        //Reload the files after creating a new file.
        function createFileSuccessHandler(data) {
            getFiles();
        }

        //Reload the files after deleting a file.
        function deleteFileSuccessHandler(data) {
            getFiles();
        }

        //Reload the files after updating a file.
        function updateFileSuccessHandler(data) {
            getFiles();
        }


        //Error handlers
        function createFolderErrorHandler(data, errorCode, errorMessage) {
            alert("Could not create folder: " + errorMessage);
        }

        function deleteFolderErrorHandler(data, errorCode, errorMessage) {
            alert("Could not delete folder: " + errorMessage);
        }

        function getFoldersErrorHandler(data, errorCode, errorMessage) {
            alert("Could not get folders: " + errorMessage);
        }

        function getFilesErrorHandler(data, errorCode, errorMessage) {
            alert("Could not get files: " + errorMessage);
        }

        function contextErrorHandler(data, errorCode, errorMessage) {
            alert("Could not get context info: " + errorMessage);
        }

        function deleteFileErrorHandler(data, errorCode, errorMessage) {
            alert("Could not delete file: " + errorMessage);
        }

        function createFileErrorHandler(data, errorCode, errorMessage) {
            alert("Could not create file: " + errorMessage);
        }

        function updateFileErrorHandler(data, errorCode, errorMessage) {
            alert("Could not update file: " + errorMessage);
        }

        function getFileErrorHandler(data, errorCode, errorMessage) {
            alert("Could not get file: " + errorMessage);
        }


        //Retrieve the form digest value.
        function getFormDigest() {
            var executor;
            // Initialize the RequestExecutor with the app web URL.
            executor = new SP.RequestExecutor("/sites/Practise");
            executor.executeAsync(
                {
                    url: "/sites/Practise/_api/contextinfo",
                    method: "POST",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: contextSuccessHandler,
                    error: contextErrorHandler
                }
            );
        }

        //Save the contents of a file to a file on the local computer.
        function save_content_to_file(content, filename) {
            var dlg = false;
            with (document) {
                ir = createElement('iframe');
                ir.id = 'ifr';
                ir.location = 'about.blank';
                ir.style.display = 'none';
                body.appendChild(ir);
                with (getElementById('ifr').contentWindow.document) {
                    open("text/plain", "replace");
                    charset = "utf-8";
                    write(content);
                    close();
                    document.charset = "utf-8";
                    dlg = execCommand('SaveAs', false, filename);
                }
                body.removeChild(ir);
            }
            return dlg;
        }
    </script>
    <div id="MainContent">
        <input type="text" value="Folder name here" id="createFolderBox" />
        <button id="createFolderButton">Create Folder</button>
        <p>Folders
        <br />
            <select id="selectFolderBox" onchange="getFiles()"></select>
            <button id="deleteFolderButton">Delete Selected Folder</button>
        </p>
        <p>Files
     <br />
            <input type="text" value="File name here" id="createFileBox" />
            <button id="createFileButton">Create File</button>
        </p>
        <p>
            <select id="selectFileBox"></select>
            <button id="deleteFileButton">Delete Selected File</button>
            <button id="getFileButton">Get Selected File</button>
        </p>
        <textarea name="submitTextFile" id="submitTextFile" rows="10" cols="40">Type file text here.</textarea>
        <button id="updateFileButton">
            Replace file contents</button>
        <label id="Error"></label>
    </div>
[/code]