Monday, August 18, 2014

Adding list items in sharepoint hosted app

On continuation of my last REST API series on how to use the REST API in SharePoint hosted App.


Download source code
Watch the screen cast in YouTube

In this post,We are going to see how to add the SharePoint list Item using simple html form.
For this I used to work on SharePoint hosted App.

I have one list named "Friends" in host web with three columns such as Title,First Name and Last Name.
So if you are not understand what is host web,app domain and cross domain call and about SP.Requestor.js file please read my previous posts where I explained these stuffs.

Simply we split into four manageable and understandable code block to perform this task.
1,Add variable to hold the web app URL and host web URL.

2,Utility function called "getQueryStringParameter" to parse the query string variable which contains the web app URL and host web URL.

3,On document ready, we need to load the SPRequestor.js file from the host web using "$.getScript" function.

4,Main function (addItem) to add the user inputs from UI to SharePoint List.


Step : 1

'use strict';
var hostweburl;
var appweburl;

Step : 2
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];
    }
  
}


Step :3
$(document).ready(function () {
      hostweburl =
        decodeURIComponent(getQueryStringParameter("SPHostUrl"));
     appweburl =
        decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
       var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js");
});

Step : 4


function addItem() {
      var executor = new SP.RequestExecutor(appweburl);
      var rest_data = JSON.stringify({
        '__metadata': { 'type': 'SP.Data.FriendsListItem' },
        'Title': $("#txtTitle").val(),
        'FirstName':$("#txtFirstName").val(),
        'LastName': $("#txtLastName").val()
    });
    executor.executeAsync(
                 {
                    url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Friends')/items/?@target='" +   
           hostweburl + "'",
                     method: "POST",
                     body: rest_data,
                   
                     headers: {"content-type": "application/json; odata=verbose" },
                     success: successHandler,
                     error: errorHandler
                 }
             );
    }

Tuesday, August 05, 2014

REST API SharePoint App Permission - Part 2

Continuation of my first part


REST API - SharePoint App - Part 1

& MERGE

Here we learn how to set the permission for the SharePoint app in the specific scope.
When you tried to execute the code from part 1,you'll get the "Access denied error" or forbidden error in your Response header.

Because of our app doesn't have permission to access the list in the SharePoint.

Brief about "SharePoint App Permission" in simple words,

SharePoint App need to have permission to write or read in the SharePoint Site even though currently logged in user having site collection administrator.

This is an another security layer introduced in app deployment.

Its an analogue to mobile app installation on your devices,before installing them you need grant the access to your storage,location and some time reading your contacts in phone list.

An app for SharePoint has its own identity and is associated with a security principal, called an app principal.
When you granting permission to your sharepoint app through GUI, your AppManifest.xml file will be updated the below scope URI in the "AppPermissionRequests"

//Site collection Permission
http://sharepoint/content/sitecollection
//Subsite permission
http://sharepoint/content/sitecollection/web
//List permission
http://sharepoint/content/sitecollection/web/list
Tenant permission
http://sharepoint/content/tenant

App Permissions are
Read
Write
Manage
FullControl

Monday, August 04, 2014

REST API SharePoint hosted App - Part 1

This post intended for the beginners who wanted to start and learn the REST API in SharePoint app model using JavaScript Object Model (JSOM).

Advantages of using REST API in SharePoint app.

  • You do not require to add any assemblies to your project.
  • Its purely based on SharePoint related supporting java script files.
  • REST API can be used in non Microsoft technologies such as Android and iOS on building the mobile application which needs to be access the SharePoint resources.
  • Supports the cross - domain library call with few lines of code while comparing server side object model.

What is cross domain library ?

Nowadays all browsers enforcing the multiple security policies,restricting the access to different domain call is core features is one of them.

Just think of mash ups application (gathering information from different sources and aggregating and showing in the page or web parts) . It could be dash board in SharePoint.
But in SharePoint app models, all apps running out side of the SharePoint contexts that is baseline for all SharePoint apps. It could be remote web,Windows Azure or Client side.

When you publish or deploy the apps, SharePoint will generate the unique domain for each of your apps with GUID identifiers.
Example

https://codethinker-c83df5dbb5c7ed.sharepoint.com/sites/appsdemo/


app domain : codethinker-c83df5dbb5c7ed
SharePoint domain : SharePoint.com
site collection : appsdemo.


[*Note:- in below example, I am trying to connect the list named friends from the app domain which is located in the SharePoint domain]


So your SharePoint needs to authorize your  apps even though browser restricts the "Cross domain call",SharePoint manage the proxy call using the file  RequestExecute.js file in the  15 hive folder.
You have to pass the app domain URL and hosting web URL parameters to the javascript class SP.RequestExecutor to overcome the cross domain call restrictions in your browsers.

Connecting your SharePoint App through REST API request.

Requirements.

  1. First log on your Office 365 site and create the new site collection based on "Developer Site" template.In later series,I cover the topic "Why you need the developer site to publish the SharePoint apps ?

Open your visual studio New Project ->Select the Apps project template under Office /SharePoint category and choose the "Apps for SharePoint"




In your project explorer open the App.js file and copy the below code snippets.

var appUrl;
var hostWebUrl;
// Reading the query string from the URL
function getQueryStringParameter(param) {
    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] == param) {
            return singleParam[1];
        }
    }
}

$(document).ready(function () {
    appUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

    hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    //cross domain library
        $.getScript(hostWebUrl + "/_layouts/15/SP.RequestExecutor.js",connectREST);
});


function connectREST()
{
 var url = appUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Friends')/items?@target='" + hostWebUrl + "'";
var executor = new SP.RequestExecutor(appUrl);
executor.executeAsync({
url: url,
method: "GET",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
$("#message").html("App connected");
},
error: function (data) {
$("#message").html("To know more about this exception ,hit F12 and analyse the network transmission");
        }
    });
}

When you are working with ajax method in jQuery,there could be chances in constructing incorrect syntax that could lead to result different html status codes such as BAD request (400),Partial Information (203),Accepted (201),No Response (204) and etc.

To overcome these problem its always better to remind the Http Response header key/value.
Accept
application/json; odata=verbose

Accept-Language
en-US
Cache-Control
no-cache
Connection
Keep-Alive
Content-Type
application/json;odata=verbose
Cookie
WSS_FullScreenMode=false
Host
win-g3u94jerf1t

X-RequestDigest
X-RequestDigest value (scrambled)
Request
POST /_api/web/lists/getbytitle('Friends')/items HTTP/1.1

Source download link http://1drv.ms/1odDgtA

When you run this project,you will get the "Access denied error" in script log.
Because the currently logged in user have permission on the site collection,but
your doesn't have permission to access the list "Friends" in the host web.

I covered this topic in the next part : http://intelliview.blogspot.in/2014/08/rest-api-sharepoint-app-permission-part.html