SharePoint Tips

Showing posts with label JSOM. Show all posts
Showing posts with label JSOM. Show all posts

Sunday, June 24, 2018

Deploy SharePoint Add-In as App Part


In previous post ‘SharePoint hosted Add-In : Read list data : JSOM’, we saw how to create SharePoint hosted Add-In to read data from SharePoint. In this post, we will see how to deploy SharePoint Add-In as App Part. So that, this Add-In can be added to any page in SharePoint.
Step 1- Add new Client Web Part to your Add -In project.


Step 2- Create a new page or you can also use existing Default.aspx page of Add-In for client web part content.


Step 3- Create a blog subsite ‘Vendor’. In App part, we will read data from this blog posts.


Step 4- Open Client web part Element.xml file and update Title and Description.


Step 5- Deploy your Add-In


Step 6- Add your App Part from Apps category as shown below.


Step 7- Now you can see your Add-In as App part in your SharePoint sites page.


Code of App Part
<%@ Page language="C#" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<WebPartPages:AllowFraming ID="AllowFraming" runat="server" />

<html>
<head>
    <title></title>

    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <script type="text/javascript">
        // Set the style of the client web part page to be consistent with the host web.
        (function () {
            'use strict';

            var hostUrl = '';
            var link = document.createElement('link');
            link.setAttribute('rel', 'stylesheet');
            if (document.URL.indexOf('?') != -1) {
                var params = document.URL.split('?')[1].split('&');
                for (var i = 0; i < params.length; i++) {
                    var p = decodeURIComponent(params[i]);
                    if (/^SPHostUrl=/i.test(p)) {
                        hostUrl = p.split('=')[1];
                        link.setAttribute('href', hostUrl + '/_layouts/15/defaultcss.ashx');
                        break;
                    }
                }
            }
            if (hostUrl == '') {
                link.setAttribute('href', '/_layouts/15/1033/styles/themable/corev15.css');
            }
            document.head.appendChild(link);
        })();
    </script>

   
    <script type="text/javascript">
        var hostweburl;
        var appweburl;
        // Load the required SharePoint libraries
        $(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
            var scriptbase = hostweburl + "/_layouts/15/";
            // Load the js files and continue to the successHandler
            $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
        });
        // Function to prepare and issue the request to get
        //  SharePoint data
        function execCrossDomainRequest() {
            // executor: The RequestExecutor object
            // Initialize the RequestExecutor with the app web URL.
            var executor = new SP.RequestExecutor(appweburl);
            // Issue the call against the app web.
            // To get the title using REST we can hit the endpoint:
            //      appweburl/_api/web/lists/getbytitle('listname')/items
            // The response formats the data in the JSON format.
            // The functions successHandler and errorHandler attend the
            //      sucess and error events respectively.
            executor.executeAsync(
                {
                    url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Posts')/items?@target='" + hostweburl + "/Vendor'&$top=3",
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: successHandler,
                    error: errorHandler
                }
            );
        }
        // Function to handle the success event.
        // Prints the data to the page.
        function successHandler(data) {
            var jsonObject = JSON.parse(data.body);
            var blogsHTML = "";
            var results = jsonObject.d.results;
            for (var i = 0; i < results.length; i++) {
                blogsHTML = blogsHTML + "<div><a href=\"" + hostweburl + "/Vendor/Lists/Posts/Post.aspx?ID=" + results[i].ID + "\" target=\"_blank\">" + results[i].Title + "</a></div><br>";
            }
            $('#myDiv').append(blogsHTML);
        }
        // Function to handle the error event.
        // Prints the error message to the page.
        function errorHandler(data, errorCode, errorMessage) {
            document.getElementById("myDiv").innerText =
                "Could not complete cross-domain call: " + errorMessage;
        }
        // Function to retrieve a query string value.       
        function getQueryStringParameter(paramToRetrieve) {
            var params =
                document.URL.split("?")[1].split("&");
            var strParams = "";
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve)
                    return singleParam[1];
            }
        }
    </script>

</head>
<body>
    <div>
        <div><strong> Vendors</strong></div>
        <div id="myDiv"></div>
       
    </div>
</body>
</html>


Saturday, June 23, 2018

SharePoint hosted Add-In : Read list data : JSOM


In last post (Step by step guide to create “SharePointHosted Add-In” in SharePoint Online (Office 365)), I created a basic SharePoint hosted Add-In as shown below.


Now, I’ll add logic to this Add-In to read data from a SharePoint list (VendorList) as shown below.


Step 1- Open Default.aspx file and add new div as shown below.


Step 2- Open App.js file. Replace code in js file with code given below.


Changes in App.js file
var Items = null;
'use strict';
var listItems;
var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', ListItems)
});

function ListItems() {
    var context = new SP.ClientContext(appweburl);
    var ContextSite = new SP.AppContextSite(context, hostweburl);
    var web = ContextSite.get_web();
    context.load(web);
    var list = web.get_lists().getByTitle('VendorList');
    var caml = new SP.CamlQuery();
    caml.set_viewXml("<View><Query></Query></View>"); // U can change the query for getting desired result  
    Items = list.getItems(caml);
    context.load(Items);
    context.executeQueryAsync(onSucceededCallback, onFailedCallback);
}

function onSucceededCallback(sender, args) {
    var enumerator = Items.getEnumerator();
    var myText = 'Items in VendorList: <br><br>';
    while (enumerator.moveNext()) {
        var listItem = enumerator.get_current();
        myText += 'Title: ' + listItem.get_item('Title') + '<br>';
        myText += 'Address: ' + listItem.get_item('Address') + '<br><br>';
    }
    myDiv.innerHTML = myText;
}

function onFailedCallback(sender, args) {
    var myText = '<p>The request failed: <br>';
    myText += 'Message: ' + args.get_message() + '<br>';
    myDiv.innerHTML = myText;
}

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];
    }
}

Step 3 – Deploy your Add-In after all changes.


Step 4- You may get below error as your Add-In don’t have enough permissions.


Step 5- For simplicity we are providing Full Control at Site Collection level. You can also provide only Read access.


Step 6- Now deploy Add-In again and you’ll get below screen.


Step 7- Trust Add-In by clicking ‘Trust It’ button.

Here is the Add-In with data from VendorList