How to get list items in SharePoint 2013 Online using CSOM

In this post, we’ll see how we can fetch the list items of a SharePoint list in SharePoint 2013 online using REST. For the purpose of demonstration, I’ll be using a SharePoint hosted app.

Launch Visual Studio 2013.

File –> New –> Office/SharePoint –> Apps and name it as ‘GetListItemsREST’

I will be accessing the following REST endpoint for getting a web title

https://yoursite.sharepoint.com/_api/web/lists/GetByTitle(‘Shared%20Assets’)/items.

Since the call is initiating from AppWeb to HostWeb, it will present a classical cross-domain scenario, where I will be using the SP 2013 javascript cross-domain libraries to manage this call.

After creating the App project in Visual Studio 2013, the following points need to be considered.

a)The App Permission need to be left with default setting of Internal.

<AppPrincipal>
    <Internal/>
  </AppPrincipal>
  

With this setting, the SharePoint hosted app will have access to the Host Web by default.

b)The App need to be given full-control permission for site-collection. Otherwise, it will not be able to fetch the fields collection.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

<AppPermissionRequests>
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="Read" />
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read" />
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Read" />
  </AppPermissionRequests>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

c)The executor object need to be instantiated with the parameter of ‘AppWebUrl’, not the ‘HostWebUrl.  (you’ll see more detailed code in the coming sections). If you instantiate it with ‘HostWebUrl, you will get an error like ‘App web not found’

var executor = new SP.RequestExecutor(AppWebUrl);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

d)To access the HostWeb rest end points the url property in the cross-domain call need to be set in this fashion.

AppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('Site%20Assets')/items?@target='" + HostWebUrl

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Open the App.js and paste the following code

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    //getUserName();

    HostWebUrl =
                decodeURIComponent(
                    RetrieveQueryStringParameter("SPHostUrl")
            );
    AppWebUrl =
        decodeURIComponent(
            RetrieveQueryStringParameter("SPAppWebUrl")
    );

    var scriptbase = HostWebUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);

});


function successHandler(data) {

    var jsonObj = JSON.parse(data.body);
    var results = jsonObj.d.results;
    var resultcount = results.length;
    var finalresult;

    var i;
    var tempobject;


    for (i = 0; i < resultcount - 1; i++)
    {
        tempobject = results[i];
        finalresult = finalresult+ "Item title is" + tempobject["Title"] + "Item id is " + tempobject["Id"];
        
    }
   
    document.getElementById("message").innerText = finalresult;
  

   
    
   
    
}



function errorHandler(data, errorCode, errorMessage) {


    document.getElementById("message").innerText = "failure";

}

function RetrieveQueryStringParameter(ParamsforRetrieval) {
    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] == ParamsforRetrieval)
            return singleParam[1];
    }
}

function execCrossDomainRequest() {

    var executor = new SP.RequestExecutor(AppWebUrl);

    executor.executeAsync({
        url: AppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('Site%20Assets')/items?@target='" + HostWebUrl + "'",
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            
        },
        success: successHandler,
        error: errorHandler
    });

}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Run the above piece of code and you will be see the below result.

image

 Subscribe to my blog

How to get a SharePoint group in SharePoint 2013 Online using REST

In this post, we’ll see how to get a SharePoint Group in SharePoint Online using REST. I’ll be using a SharePoint hosted app for the purpose of demonstration.

Launch Visual Studio 2013.

I will be accessing the following REST endpoint for getting a web title

https://yoursite.sharepoint/_api/web/sitegroups(index)

index – an integer that refers a group uniquely in the site.

Since the call is initiating from AppWeb to HostWeb, it will present a classical cross-domain scenario, where I will be using the SP 2013 javascript cross-domain libraries to manage this call.

After creating the App project in Visual Studio 2013, the following points need to be considered.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

a)The App Permission need to be left with default setting of Internal.

<AppPrincipal>
    <Internal/>
  </AppPrincipal>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

With this setting, the SharePoint hosted app will have access to the Host Web by default.

b)The App need to be given the following permission.

<AppPermissionRequests>
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="Read" />
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read" />
  </AppPermissionRequests>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

c)The executor object need to be instantiated with the parameter of ‘AppWebUrl’, not the ‘HostWebUrl.  (you’ll see more detailed code in the coming sections). If you instantiate it with ‘HostWebUrl, you will get an error like ‘App web not found’.

var executor = new SP.RequestExecutor(AppWebUrl);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

d)To access the HostWeb rest end points the url property in the cross-domain call need to be set in this fashion.

AppWebUrl + "/_api/SP.AppContextSite(@target)/web/sitegroups(index)?@target='" + HostWebUrl + "'",

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

e)Copy and paste the following code in the App.js (replace Ii t the existing code over there)

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    //getUserName();

    HostWebUrl =
                decodeURIComponent(
                    RetrieveQueryStringParameter("SPHostUrl")
            );
    AppWebUrl =
        decodeURIComponent(
            RetrieveQueryStringParameter("SPAppWebUrl")
    );

    var scriptbase = HostWebUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);

});


function successHandler(data) {

    var jsonObj = JSON.parse(data.body);
    var results = jsonObj.d;
    document.getElementById("message").innerText = "Field title is" + results["Title"] + "Field Id is" + results["Id"];

}

function errorHandler(data, errorCode, errorMessage) {


    document.getElementById("message").innerText = "failure";

}

function RetrieveQueryStringParameter(ParamsforRetrieval) {
    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] == ParamsforRetrieval)
            return singleParam[1];
    }
}

function execCrossDomainRequest() {

    var executor = new SP.RequestExecutor(AppWebUrl);

    executor.executeAsync({
        url: AppWebUrl + "/_api/SP.AppContextSite(@target)/web/sitegroups(3)?@target='" + HostWebUrl + "'",
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose"
        },
        success: successHandler,
        error: errorHandler
    });

}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Run the above piece of code, now you will be able to get the title and id for the site collection group (no: 3).

image

 Subscribe to my blog

 

How to get SharePoint fields collection in SharePoint 2013 Online using REST

In this post, we’ll see how we can fetch the fields collection of a SharePoint web in SharePoint 2013 online using REST. For the purpose of demonstration, I’ll be using a SharePoint hosted app.

Launch Visual Studio 2013.

File –> New –> Office/SharePoint –> Apps and name it as ‘GetFieldsREST’

I will be accessing the following REST endpoint for getting a web title

https://yoursite.sharepoint/_api/web/fields

Since the call is initiating from AppWeb to HostWeb, it will present a classical cross-domain scenario, where I will be using the SP 2013 javascript cross-domain libraries to manage this call.

After creating the App project in Visual Studio 2013, the following points need to be considered

a)The App Permission need to be left with default setting of Internal.

<AppPrincipal>
    <Internal/>
  </AppPrincipal>
  

With this setting, the SharePoint hosted app will have access to the Host Web by default.

b)The App need to be given full-control permission for site-collection. Otherwise, it will not be able to fetch the fields collection.

 <AppPermissionRequests>
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
  </AppPermissionRequests>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

c)The executor object need to be instantiated with the parameter of ‘AppWebUrl’, not the ‘HostWebUrl.  (you’ll see more detailed code in the coming sections). If you instantiate it with ‘HostWebUrl, you will get an error like ‘App web not found’

var executor = new SP.RequestExecutor(AppWebUrl);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

d)To access the HostWeb rest end points the url property in the cross-domain call need to be set in this fashion.

AppWebUrl + "/_api/SP.AppContextSite(@target)/web/fields?@target='" + HostWebUrl + "'",

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Open the App.js and paste the following code

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    //getUserName();

    HostWebUrl =
                decodeURIComponent(
                    RetrieveQueryStringParameter("SPHostUrl")
            );
    AppWebUrl =
        decodeURIComponent(
            RetrieveQueryStringParameter("SPAppWebUrl")
    );

    var scriptbase = HostWebUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);

});


function successHandler(data) {

    var jsonObj = JSON.parse(data.body);
    var results = jsonObj.d;
    document.getElementById("message").innerText = "Field title is" + results["Title"] + "Field Id is" + results["Id"];

}

function errorHandler(data, errorCode, errorMessage) {


    document.getElementById("message").innerText = "failure";

}

function RetrieveQueryStringParameter(ParamsforRetrieval) {
    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] == ParamsforRetrieval)
            return singleParam[1];
    }
}

function execCrossDomainRequest() {

    var executor = new SP.RequestExecutor(AppWebUrl);

    executor.executeAsync({
        url: AppWebUrl + "/_api/SP.AppContextSite(@target)/web/fields?@target='" + HostWebUrl + "'",
        method: "POST",
        body: "{ '__metadata': { 'type': 'SP.Field' }, 'Title': 'Comments', 'FieldTypeKind': 3 }",
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose"
        },
        success: successHandler,
        error: errorHandler
    });

}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

image

This completes this demo.

 Subscribe to my blog

How to get SharePoint 2013 web property using REST in SharePoint Online

In this post, we’ll see how we can access the property of a SharePoint web in SharePoint 2013 online using REST. For the purpose of demonstration, I’ll be using a SharePoint hosted app.

Launch Visual Studio 2013.

File –> New –> Office/SharePoint –> Apps and and name it as ‘GetWebdetailsREST’

I will be accessing the following REST endpoint for getting a web title

https://yoursite.sharepoint/_api/web/title

Since the call is initiating from AppWeb to HostWeb, it will present a classical cross-domain scenario, where I will be using the SP 2013 javascript cross-domain libraries to manage this call.

After creating the App project in Visual Studio 2013, the following points need to be considered

a)The App Permission need to be left with default setting of Internal.

<AppPrincipal>
    <Internal/>
  </AppPrincipal>
  

With this setting, the SharePoint hosted app will have access to the Host Web by default.

b)The App need to be given read permission for site-collection

<AppPermissionRequests>
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="Read" />
  </AppPermissionRequests>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

c)The executor object need to be instantiated with the parameter of ‘AppWebUrl’, not the ‘HostWebUrl.  (you’ll see more detailed code in the coming sections). If you instantiate it with ‘HostWebUrl, you will get an error like ‘App web not found’

var executor = new SP.RequestExecutor(AppWebUrl);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

d)To access the HostWeb rest end points the url property in the cross-domain call need to be set in this fashion.

AppWebUrl + "/_api/SP.AppContextSite(@target)/web/title?@target='" + HostWebUrl + "'",

Open the App.js and paste the following code

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    //getUserName();

    HostWebUrl =
                decodeURIComponent(
                    RetrieveQueryStringParameter("SPHostUrl")
            );
    AppWebUrl =
        decodeURIComponent(
            RetrieveQueryStringParameter("SPAppWebUrl")
    );

    var scriptbase = HostWebUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);

});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
   
}



function successHandler(data)
{
    
    var jsonObj = JSON.parse(data.body);
    document.getElementById("message").innerText = "Web title from REST call is"+ jsonObj.d["Title"];

}

function errorHandler(data, errorCode, errorMessage) {
   

    document.getElementById("message").innerText = "failure";

}

function RetrieveQueryStringParameter(ParamsforRetrieval) {
    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] == ParamsforRetrieval)
            return singleParam[1];
    }
}

function execCrossDomainRequest() {

    var executor = new SP.RequestExecutor(AppWebUrl);
    executor.executeAsync(
        {
            url: AppWebUrl + "/_api/SP.AppContextSite(@target)/web/title?@target='" + HostWebUrl + "'",
            type: "GET",
            crossDomain:true,

            headers: {
                "accept": "application/json; odata=verbose",
                "content-type": "application/json;odata=verbose",
                "content-length": 1028,
                "X-RequestDigest": $("#__REQUESTDIGEST").val()

            },
            success: successHandler,
            error: errorHandler
        }
        );

}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

image

Now you can see the updated site title in the App. This completes this demo.

 Subscribe to my blog

Understanding App Only Permission policy in SharePoint 2013 App model

In this post, we’ll understand what is an App Only Permission policy in SharePoint 2013 App model with a sample app project. The SharePoint 2013 App permissions are of three types and they are as follows :-

  • App Only
  • User Only
  • App+User

When the logged in user does not have enough privileges to perform a certain action or set of actions, the App Only permission comes into picture. The App can elevate its permission using the App Only permission or context. A SharePoint 2013 App configured with App Only permission or context can only installed by the site-collection administrator at this point of time.

I’ll be using a Provider hosted app for the purpose of this demonstration. I have a user called ‘User A’ who does not have permission to modify the Title of SharePoint lists in the site-collection. I will be using App Only context to elevate the App’s permission and change the List Title.

I have a list called ‘Announcements’ and I will be changing its Title using App Only permission or context.

image

Launch Visual Studio 2013.

File –> New –> Office/SharePoint –> Apps and name it as ‘AppOnlyContextApp’

Select the app hosting type as Provider hosted apps.

In order to update the Title of the SharePoint List (at the root of the site-collection), provide the Full Control to Site-Collection.

image

Set App Only permission in the AppManifest.XML file

<?xml version="1.0" encoding="utf-8" ?>
<!--Created:cb85b80c-f585-40ff-8bfc-12ff4d0e34a9-->
<App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest"
     Name="AppOnlyContext"
     ProductID="{b5e637d0-8a34-498c-b8cf-c40b3d0e9ef3}"
     Version="1.0.0.0"
     SharePointMinVersion="15.0.0.0"
>
  <Properties>
    <Title>AppOnlyContext</Title>
    <StartPage>~remoteAppUrl/Pages/Default.aspx?{StandardTokens}</StartPage>
  </Properties>

  <AppPrincipal>
    <RemoteWebApplication ClientId="*" />
  </AppPrincipal>
  <AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
  </AppPermissionRequests>
</App>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Copy and paste the following code for the default.aspx.cs file and I have added the necessary logic in the page_load method to update Title of a particular list.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AppOnlyContextWeb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Uri redirectUrl;
            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
            {
                case RedirectionStatus.Ok:
                    return;
                case RedirectionStatus.ShouldRedirect:
                    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
                    break;
                case RedirectionStatus.CanNotRedirect:
                    Response.Write("An error occurred while processing your request.");
                    Response.End();
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // The following code gets the client context and Title property by using TokenHelper.
            // To access other properties, the app may need to request permissions on the host web.
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
         
                //Load the sharepoint web
                clientContext.Load(clientContext.Web, web => web.Title);
                clientContext.ExecuteQuery();
                Response.Write(clientContext.Web.Title);

                //Load the list-collection in the sharepoint web
                clientContext.Load(clientContext.Web.Lists);                
                clientContext.ExecuteQuery();

                //Change the title of announcment list to some arbitrary title
                clientContext.Web.Lists[1].Title = "SundarAnnouncements";
                clientContext.Web.Lists[1].Update();
                clientContext.ExecuteQuery();


            }
        }
    }
}

Hit F5 and run the App in Visual Studio. Now we can verify the elevation of App permission by using App Only policy, by validating the change in List title.

image

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 Subscribe to my blog

How to create a SharePoint 2013 Site by invoking SP 2013 REST endpoints

In this post, we would see on how to create a SharePoint 2013 site using the SharePoint 2013 RESTful endpoints available in HostWeb. I would be using a SharePoint hosted app to demonstrate this scenario.

File –> New –> Office/SharePoint –> Apps and name it as ‘CreateSiteApp’.

image

In the SharePoint hosted app, I’d be making a call to the /_api/web/webinfos/add available in HostWeb to create a sub-site under HostWeb.

Open App.js file.

Copy and paste the following code. The following snippet leverages Cross Domain library of SharePoint 2013 to make

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;



// This code runs when the DOM is ready and creates a context object which is needed
 to use the SharePoint object model
$(document).ready(function () {
    HostWebUrl =
                decodeURIComponent(
                    RetrieveQueryStringParameter("SPHostUrl")
            );
    AppWebUrl =
        decodeURIComponent(
            RetrieveQueryStringParameter("SPAppWebUrl")
    );

    var scriptbase = HostWebUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);


});

function RetrieveQueryStringParameter(ParamsforRetrieval) {
    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] == ParamsforRetrieval)
            return singleParam[1];
    }
}


function execCrossDomainRequest() {

    var executor = new SP.RequestExecutor(AppWebUrl);
    executor.executeAsync(
        {
            url:  AppWebUrl +"/_api/web/webinfos/add",
            type: "POST",
            data: JSON.stringify(
                {
                    'parameters': {
                        '__metadata': { 'type': 'SP.WebInfoCreationInformation' },
                        'Url': 'SundarSite',
                        'Title': 'SundarSite',
                        'Description': 'Site created using REST',
                        'Language': 1033,
                        'WebTemplate': 'sts',
                        'UseUniquePermissions': false
                    }
                }
            ),
            headers: {
                "accept": "application/json; odata=verbose",
                "content-type": "application/json;odata=verbose",
                "content-length": 1028,
                "X-RequestDigest": $("#__REQUESTDIGEST").val()

            },
            success: successHandler,
            error: errorHandler
        }
        );




       

}

function successHandler(data) {
    document.getElementById("message").innerText =
        "Site Created Successfully";

}

function errorHandler(data, errorCode, errorMessage) {
    document.getElementById("message").innerText =
        "Could not complete cross-domain call " + errorMessage;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 Subscribe to my blog

How to access data in Host Web from SharePoint 2013 App

When we build SharePoint 2013 Apps, one of the common scenario that we will have is to read the data from Host Web.  This presents a classical Cross-Domain call scenario (where the fully-qualified domain for App Web and Host Web are different). By default, when we access the Host Web resources from App Web either using Java Script Model or Client Object Model, we’d get an access denied error. This fix for this scenario is to leverage javascript client-side solution in the form of (SP.RequestExecutor.JS) file. The cross domain libraries helps us to interact with more one domain in the SharePoint 2013 App through the Proxy. Let’s jump on to the steps.

Open Visual Studio 2013

File –> New –> Project –> Apps for SharePoint 2013 –> SharePoint hosted apps and name the App as ‘ReadHostWeb;

Set the site for debugging, in this case I’m using my Office 365 developer tenant ‘https://mytenant.sharepoint.com’

I’ve created an Announcement list in my Host Web and it has three Columns Title, Body and Version.

Open Default.aspx and paste the following snippet of code inside

 

<div id="ListFieldDiv"></div>

    <script type="text/javascript">
        var HostWebUrl;
        var AppWebUrl;
        var ListFieldHtml;

        // Load the required SharePoint libraries
        $(document).ready(function () {
            //Get the URI decoded URLs.
            HostWebUrl =
                decodeURIComponent(
                    RetrieveQueryStringParameter("SPHostUrl")
            );
            AppWebUrl =
                decodeURIComponent(
                    RetrieveQueryStringParameter("SPAppWebUrl")
            );

            
            var scriptbase = HostWebUrl + "/_layouts/15/";

            
            $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
            
        });


        
        
        function execCrossDomainRequest() {
            
            var executor = new SP.RequestExecutor(AppWebUrl);

            
            executor.executeAsync(
    {
        url:
            AppWebUrl +
            "/_api/SP.AppContextSite(@target)/web/lists('5fabe2a3-7a5f-4444-ba3e-a684558d1e27')/fields?@target='" +
            HostWebUrl + "'",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: successHandler,
        error: errorHandler
    }
);

        }

        
        function successHandler(data) {

            var jsonObject = JSON.parse(data.body);
            var results = jsonObject.d.results;

            for (i = 0; i < results.length; i++)
            {
                if (results[i].Hidden == false) {

                    

                    if ((results[i].TypeDisplayName == "Single line of text") || (results[i].TypeDisplayName == "Multiple lines of text")) {

                        
                        if (results[i].Title == "undefined" || results[i].Title == "Version")
                        {


                        }
                        else
                        {
                            ListFieldHtml = ListFieldHtml + "<p>" + results[i].Title;

                        }

                        
                    }
                }
                

            }
            
            document.getElementById("ListFieldDiv").innerHTML = ListFieldHtml;

            
            


            
        }

       
        function errorHandler(data, errorCode, errorMessage) {
            document.getElementById("AnnouncementsDiv").innerText =
                "Could not complete cross-domain call " + errorMessage;
        }

       
        function RetrieveQueryStringParameter(ParamsforRetrieval) {
            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] == ParamsforRetrieval)
                    return singleParam[1];
            }
        }
        </script>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 image

 Subscribe to my blog

How to create a simple Remote Event Receiver for a Custom List in Office 365 SharePoint 2013 site

In this article, we’ll see how to create a remote event receiver for a custom list (in App Web) in SharePoint 2013 Online.  The Remote Event Receivers are components (classes) that makes SharePoint Apps to respond to events that occur in SharePoint lists or items.

Create a new App in Visual Studio 2012 and name it as ‘CustomListEventReceiver’

image

Set the Office 365 SharePoint site for debugging the App and select App Type as SharePoint Hosted App

image

Now the app project is created. The next step is to create or set up a Custom List in the App.

Right Click –> Add New Item –> List  and name it as ‘TestCustomList’

image

Select ‘Default(CustomList)’ for Create a custom list template and list instance of it –> Finish

image

Now the Custom List is created. The next step is to add the Remote Event Receiver.

Right Click –> Add New Item –> RemoteEventReceiver and name it as TestEventReceiver.

image

This creates a RemoteWeb Project containing .svc file listening for remote events . The whole ideas is that in SharePoint 2013, the event handling for Lists and Items happened outside of SharePoint in the WCF Service (inside RemoteWeb Project).

Select the following 3 events  to be handled

image

Now you’ll see a remote event receiver project (.svc file inside it) created as the part of the Solution.

image

Remove the ClientId and ClientSecret from Web.Config file

<add key="ClientId" value="b0b7eb35-8980-4910-a3f6-f7129bb16466" />
<add key="ClientSecret" value="oVS2tUbGHbnWEQMPk2i5VvwdyOH04iiWJZmp0N9HXSE=" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Open the AppManifest.xml file and change the AppPrincipal to internal

<AppPrincipal>
   <Internal/>   
 </AppPrincipal>

Go to Project Properties in Visual Studio 2012 and set the following properties

image

Since this App is running in Office 365, we need to set an Azure Service Bus connection string is required for debugging the remote event receiver (.svc component). Otherwise, we’ll get this debugging error mentioned in one of my previous article.

Go to Elements.xml of default.aspx under Pages.xml.

Remove the following File tag in the Elements.xml

<File Path="PagesDefault.aspx" Url="Pages/Default.aspx" ReplaceContent="TRUE" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Add the following File tag inside Elements.xml

 <File Path="PagesDefault.aspx" Url="Pages/Default.aspx" >
      <AllUsersWebPart WebPartZoneID="full" WebPartOrder="0">
        <![CDATA[ 
      <webParts>
      <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
      <metaData>
      <type
    name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart,
    Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,
    PublicKeyToken=71e9bce111e9429c" />
      <importErrorMessage>
      Cannot import this Web Part.
      </importErrorMessage>
      </metaData>
      <data>
        <properties>
          <property name="Title"
           type="string">TestCustomList</property>
          <property name="ListDisplayName"
           type="string">TestCustomList</property> 
           <property name="ChromeType"
           type="chrometype">TitleOnly</property>
        </properties>
      </data>
    </webPart>
  </webParts>
]]>
      </AllUsersWebPart>
    </File>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The above File element inserts an XSLST List View web part to render the list items of TestCustomList with the column name Title.

Open default.aspx and add the following webpart definition inside the  PlaceHolderMain (just outside of the div containing <p> with id as message)


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

<WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="full" Title="loc:full" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Open TestEventReceiver and implement the ProcessEvent(SPRemoteEventProperties properties) method for the ItemAdding and ItemDeleted events

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;

namespace CustomListEventReceiverWeb.Services
{
    public class TestEventReceiver : IRemoteEventService
    {
        public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            SPRemoteEventResult oResult = new SPRemoteEventResult();
                       
            

            switch (properties.EventType)
            {
                case SPRemoteEventType.ItemAdding:


                   
                    
                    oResult.ChangedItemProperties.Add("Title", properties.ItemEventProperties.AfterProperties["Title"] += "Sundar");
                    break;

                case SPRemoteEventType.ItemDeleting:
                    oResult.ErrorMessage = "You cannot delete this list item";
                    oResult.Status = SPRemoteEventServiceStatus.CancelWithError;
                    break;
            }


            return oResult;
        }

        public void ProcessOneWayEvent(SPRemoteEventProperties properties)
        {
            if (properties.EventType == SPRemoteEventType.ItemAdded)
            {
                //Do something here ...
            }
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Hit F5 and run the CustomListEventReceiver app

Now we’ll see the  item Title appended with “Sundar” (execution of ItemAdding event)

image

 

image

When we try to delete the item, it throws an error message “You cannot delete this list item” (execution of item deleted event).

image

 Subscribe to my blog

How SharePoint 2010 customizations can be mapped to SP 2013 App Model

I tried to do a mapping on how the SharePoint 2010 server-side customization can be mapped to SP 2013 App Model, here is the list below.

No SP 2010 Farm Solution SP 2013 App Model
1

Alternate CSS in hive

Apps cannot deploy files to SharePoint’s root files/hive. Instead, css can be deployed to SharePoint using a module or app installed event

2

Alternate CSS in Module

Apps cannot deploy files to SharePoint’s root files/hive. Instead, css can be deployed to SharePoint using a module or app installed event

3 Application Page

Apps cannot deploy files to SharePoint’s root files/hive, which includes the layouts folder. As an alternative, web part pages can be deployed through a module or app installed event receiver

4 Custom Column

Declarative columns can only be deployed to the app web. To deploy columns to Host Web leverage App Installed Event

5 Content Type

Declarative content types can only be deployed to the app web. To deploy content types to App Web leverage App Installed Event

6 Custom Action Apps support specific types of custom actions, including ribbon commands and context menus in both the app web and host web.
7 Delegate Control

Apps for SharePoint do not support delegate controls. Add custom HTML snippet to the Master Page to achieve the effect of delegate controls

8 Feature Receiver

Apps have remote events for “App Installed”, “App Uninstalling”, and “App Upgraded”. All of these can be used in a similar way to feature receivers in farm solutions.

9 Feature Stapling

Apps can be “stapled” through the app catalog, leverage the concept of App Stapling

10 Images (in hive)

Apps cannot deploy files to SharePoint’s root files/hive. Instead, images can be deployed to SharePoint using a module or app installed event

11 List definition

Apps can deploy custom list definitions, but only to the app web and not the host web

12 List Event Receiver

Leverage Remote Event Receivers to address on-premise List Event Receivers for Cloud

13 List Instance

Declarative list instances can only be deployed to the app web and not the host web. `

14

Master Page (in hive)

Apps cannot deploy files to SharePoint’s root files/hive. Instead, master pages can be deployed to SharePoint using a module or app installed event
15

Master Page (Module)

Apps can use modules to deploy master pages to SharePoint, but only to the app web…not the host web. Leverage app installed event can be used to deploy a master page to a host web

16 Module

Apps can leverage modules to declaratively deploy files into SharePoint

17

Script (in hive)

Apps cannot deploy files to SharePoint’s root files/hive. Instead, script can be deployed to SharePoint using a module or app installed event

18 Search Configuration Apps for SharePoint can be used to consistently and efficiently deploy a search configuration to a number of sites
19 Site Definition

Site definitions deploy files into SharePoint’s root files/hive, which is not a capability of apps for SharePoint

20 Timer Jobs

Timer Jobs cannot be addressed in App Model

21

User Controls (Control Templates

Apps cannot deploy user controls to SharePoint hive, consider other alternatives

24 Webpart Apps can deploy App Parts to SharePoint
25 Web Part Page Leverage App Installed event to provision a web part page to the Host Web. However for App Web, leverage Modules.
26 Web Template Web Templates can be installed to the host web’s site collection root using the App Installed event
27 Workflow Workflow is supported in SP 2013 App Model
28 Workflow Activity Workflow activity is supported in SP 2013 App Model

 Subscribe to my blog

You can’t remotely debug events Windows Azure Service Bus connection string is missing

I was trying to debug a SharePoint 2013 remote event receiver running against a SharePoint Hosted App in Visual Studio 2012. I got the following error.

pic1

I learnt that I need to create a Windows Azure Service Bus and configure the end point of Azure Service Bus in the Visual Studio project property.

Create a new service bus object in Azure Management Portal

pic3

Go to project property in Visual Studio 2012 –> SharePoint Tab –> Enable Remote Debugging by providing the endpoint of the Azure Service Bus

pic4

Now we’re able to debug the remote event receiver in Visual Studio 2012.

pic2

 Subscribe to my blog