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 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

How to setup multi-factor authentication in Office 365

In this post, we’ll see how we can enable multi-factor authentication for Office 365. The concept of multi-factor authentication has be become increasingly popular nowadays for bringing the additional layer of security hardening. Multi-factor authentication is a form of authentication, which enforces more than one form of authentication to verify the legitimacy of the transactions performed by a user. Nowadays, the most common form of second-form of authentication in to validate the Authorization code by sending it to the user’s mobile devices.

Let’s see the steps to enable multi-factor authentication in Office 365.

Log in to Office 365 admin portal, go to Users –> Active Users.

image

Click setup and you will be presented with the following screen.

image

Click ‘Enable’ link on the bottom right and the following screen will pop-up.

 

image

Click ‘enable multi-factor auth’.

Now you will get a confirmation that multi-factor authentication is enabled for selected accounts.

When I log in next time, it asks for me to setup the second form of authentication.

image

Click ‘Set it up now’.

image

It sends a 6 digit verification code to the registered mobile number. You are all set for multi-factor authentication enabled Office 365 tenant. This wraps up my quick how-to article.

At this point of time, the multi-factor authentication is available for Office 365 Midsize Business, Enterprise plans, Academic plans, Nonprofit plans, and standalone Office 365 plans, including Exchange Online and SharePoint Online. It is not available for Office 365 Small Business and Office 365 Dedicated plans as of now. The detailed Faqs about multi-factor authentication is available here. 

 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 get list of Fields in a SharePoint List in SharePoint 2013 Online using CSOM

In this post, we’ll see how we can get the list of Fields in a SharePoint List in SharePoint 2013 Online using CSOM. I’ll be using a Console application for the purpose of demonstration.

Open Visual Studio 2013.

File –> New Project –> Visual C# –> Console Application and name it as ‘GetFieldsCSOM’

Add a reference to the ‘Microsoft.SharePoint.Client’ and ‘Microsoft.SharePoint.Client.Runtime’ assemblies

Import the following namespaces

using Microsoft.SharePoint.Client;
using System.Security;

.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 following code will invoke the GetbyTitle method of Lists class and access the Fields property collection.

namespace GetFieldsCSOM
{
    class Program
    {
        
        private static SecureString GetSecureString(String Password)
        {
            SecureString oSecurePassword = new SecureString();

            foreach (Char c in Password.ToCharArray())
            {
                oSecurePassword.AppendChar(c);

            }
            return oSecurePassword;
        }

        static void Main(string[] args)
        {
            //Replace it with the url of your tenant or your site-collection
            string SiteUrl = "https://yoursite.sharepoint.com";
            System.Uri oUri = new System.Uri(SiteUrl);
            using (ClientContext oClientContext = new ClientContext(SiteUrl))
            {
                //Replace it with your user id for SharePoint Online
                string UserName = "userid@yoursite.onmicrosoft.com";
                //Replace it with your password
                string Password = "password";
                //Create a SecureString object from password string, needed for SharePointOnlineCredentials class
                SecureString SecurePassword = GetSecureString(Password);
                oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);
                oClientContext.Load(oClientContext.Web.Lists.GetByTitle("TestList").Fields);
                oClientContext.ExecuteQuery();
                FieldCollection oFieldCollection = oClientContext.Web.Lists.GetByTitle("TestList").Fields;

                foreach(Field oField in oFieldCollection)
                {
                    Console.WriteLine(oField.Title);
                
                }
                Console.ReadLine();
            }
        }
    }
}

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 get Users and Groups in SharePoint 2013 Online using CSOM

In this post, we’ll see how we can retrieve users in a SharePoint group in SharePoint 2013 Online using managed .NET Client Side Object Model (CSOM). We’ll create a Console Application in Visual Studio for the purpose of the demo.

Open Visual Studio 2013.

File –> New Project –> Visual C# –> Console Application and name it as ‘GetUsersInGroup’

Add a reference to assemblies ‘Microsoft.SharePoint.Client’ and ‘Microsoft.SharePoint.Client.Runtime’.

Import the following two namespaces.

using Microsoft.SharePoint.Client;
using System.Security;

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

In the client object model, the list groups in a site-collection needs to be fetched first and then based on the groups another call needs to be made to SharePoint Online to get the list of users. The following code snippet explains it all.

namespace GetUsersInGroupCSOM
{

    class Program
    {
        static void Main(string[] args)
        {
            //Replace it with the url of your tenant or your site-collection
            string SiteUrl = "https://yoursite.sharepoint.com";

            System.Uri oUri = new System.Uri(SiteUrl);

            using (ClientContext oClientContext = new ClientContext(SiteUrl))
            {
                //Replace it with your user id for SharePoint Online
                string UserName = "lavsunswe@yoursite.onmicrosoft.com";


                //Replace it with your password
                string Password = "yourpassword";

                //Create a SecureString object from password string, needed for SharePointOnlineCredentials class
                SecureString SecurePassword = GetSecureString(Password);
                oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);

                //Load the site-collection groups using CSOM
                oClientContext.Load(oClientContext.Web.SiteGroups);
                oClientContext.ExecuteQuery();

                GroupCollection oSiteCollectionGroups= oClientContext.Web.SiteGroups;
                Console.WriteLine("List of groups in the site collection");
                Console.WriteLine("-------------------------------------");

                foreach (Group  oGroup in oSiteCollectionGroups)

                {
                    
                    Console.WriteLine(oGroup.Title);
                    Console.WriteLine("n");


                                
                }

                //Load the users collection in the Group 1

                oClientContext.Load(oSiteCollectionGroups[1].Users);
                oClientContext.ExecuteQuery();

                Console.WriteLine("List of users in the first group of site-collection");
                Console.WriteLine("-------------------------------------");
              foreach(User oUser in oSiteCollectionGroups[1].Users)
                {
                    Console.WriteLine(oUser.Title);
                    Console.WriteLine("n");
                
                }


               
                Console.ReadLine();



            }



        }

        private static SecureString GetSecureString(String Password)
        {
            SecureString oSecurePassword = new SecureString();

            foreach (Char c in Password.ToCharArray())
            {
                oSecurePassword.AppendChar(c);

            }
            return oSecurePassword;
        }

    }
}

image

 Subscribe to my blog

Office 365 development patterns & practices released

The Office 365 Development Patterns & Practices team have shipped the new open source repository today to GitHub.com/OfficeDev. The whole idea of releasing this is that, many sharepoint developers were familiar with how to build custom solutions with full-trust code and VSTO, however they did not know how to implement these solutions using App Model. The set of samples addresses the transformation from Full Trust Code to App Model.

The additional content for Office 365 development is available in Microsoft Download Center SharePoint 2013 and SharePoint Online solution pack for branding and site provisioning.

 Subscribe to my blog

List of Azure services that can be moved from one subscription to another subscription

I have a requirement to transfer the entire SharePoint 2013 Farm on  Azure with Virtual Network, Cloud services, Storage accounts, Virtual Machines, Subnets and Availability sets to a different Subscription on Azure. I did some analysis and in this migration process i have learnt that the following Azure services (as of today 07/29/2014) can be transferred from one Azure subscription to another Azure subscription without data-loss and downtime, by raising a support ticket with Microsoft Azure Support :-

  • Virtual Machines
  • Cloud Services
  • CDN
  • Web sites
  • Media Services
  • Service Bus
  • Storage
  • Multi Factor Authentication
  • Traffic Manager
  • Mobile Services
  • Virtual Network
  • Access Control Service (ACS)
  • Caching – we need to work with Engineering Team for migrating caching service
  • Reserved IP Address and the Reserved IPs under the list

However, there are certain Azure services that cannot be moved from One subscription to another subscription (as of today 07/29/2014):-

a) Active Directory (AAD)
b) BizTalk Services
c) HD Insight
d) Backup 
e) Hyper-V Recovery Manager
f) Azure Store
g) Import / Export
h) Scheduler
i) Management Services 
j) SQL Reporting

The following pre-conditions should be met before initiating a subscription transfer with Microsoft Azure support :

  • Source and destination subscription should be active
  • Selective service transfer is not feasible as of today, it might come in future. It has to be all or nothing.
  • The destination azure subscription should be empty, otherwise it will be overwritten during upgrade
  • Source and destination subscription should have same server administrator assigned until the migration is complete.

 Subscribe to my blog

Consume a SharePoint 2013 Online REST feed using .NET managed code

In this post, we’ll see how we can consume a SharePoint 2013 online REST feed using managed c# code. I’d be using a Provider Hosted App template in Visual Studio 2013 for this demonstration. It is very straight forward to consume a Restful .NET service by issuing HttpWebRequest from c# code and getting HttpWebResponse.

I will be invoking https://yoursite.sharepoint.com/_api/web/lists from c# code to get the list of SharePoint lists in this Office 365 site. The following screenshot shows the response for this Restful service in the browser.

image

Now let’s start creating a Provider hosted app project in Visual Studio 2013.

File –> New Project –> Visual C# –> Office/SharePoint –> App for SharePoint 2013 and name it as ‘ReadRESTCSharp’ & set the site for debugging and app type as ‘Provider-hosted’.

image

Specify the web project type as ‘ASP.NET Web Forms Application’. In the next step, Visual Studio 2013 would prompt for setting App Authentication Type, I did not see this option while using Visual Studio 2012 to create Provider hosted apps.

image

Set the App authentication type as ‘Use Windows Azure Access Control Service’ (mentioned in the above screenshot).

Click ‘Finish’ to create the app.

Go to  ASP.NET Web Forms project and open the default.aspx.cs

Import the following three namespaces at the top.

using Microsoft.SharePoint.Client;
using System.Net;
using System.IO;

In page_load comment out the following lines of code.

//var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

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

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

Since I’m using my own developer tenant in Office 365, I would want to trust all the certificates issued by SharePoint Online to my browser. Otherwise, it will keeping popping up a message to trust the certificates in Visual Studio 2013, when I hit F5 and debug the app.

Open the TokenHelper.cs and the add the following static method ‘TrustAllCertificates’

public static void TrustAllCertificates()
        {
            //Trust all certificates
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                ((sender, certificate, chain, sslPolicyErrors) => true);
        }

If you are using Visual Studio 2012, it adds ‘TrustAllCertificates’ in TokenHelper.cs by default.
.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; }

I will be using my Office 365 developer tenant for this demo, which forces the need to get the Access Token from Office 365 and pass it as a part of the header in the HttpWebRequest. First I need to get the ContextTokenString by invoking GetContextTokenFromRequest method in TokenHelper.cs. Then I need to get the actual SharePointContextToken by invoking ReadAndValidateContextToken method in the TokenHelper.cs. Finally I need to get AccessToken by invoking the GetAccessToken method in the TokenHelper.cs. I won’t go too detailed about this one. All the dynamics of the Token exchange is covered in one of my previous article.

Once the AccessToken is received, a HTTPWebRequest needs to be issued by setting the AccessToken with Bearer, also we need to set the HTTPRequest method as ‘GET’ and HTTPRequest accept headers as “application/json;odata=verbose”.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Microsoft.SharePoint.Client;

namespace ReadRESTCSharpWeb
{
    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())
            //{
              //  clientContext.Load(clientContext.Web, web => web.Title);
               // clientContext.ExecuteQuery();
                //Response.Write(clientContext.Web.Title);


            //}

            TokenHelper.TrustAllCertificates();

            //Get the ContextTokenString
            string ContextTokenString = TokenHelper.GetContextTokenFromRequest(Request);



            if (ContextTokenString != null)
            {

                //Get the SharePointContextToken
                SharePointContextToken ContextToken = TokenHelper.ReadAndValidateContextToken(ContextTokenString, Request.Url.Authority);

                Uri sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);

                //Get the AccessToken
                string AccessToken = TokenHelper.GetAccessToken(ContextToken,sharepointUrl.Authority).AccessToken;

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(@"https://yoursite.sharepoint.com/_api/web/lists");
                request.Method = "GET";
                request.Accept = "application/json;odata=verbose";
                request.Headers.Add("Authorization", "Bearer " + AccessToken);

                HttpWebResponse response =(HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());

                Response.Write("<h2>List of SharePoint lists in SharePoint Online fetched from managed code</h2>");
                Response.Write("<p>" + reader.ReadToEnd() + "</p>");
                Response.Flush();
            
            
            }




        }
    }
}

After executing the above we get the successful HTTPResponse which can be seen in debug mode in Visual Studio 2013.

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