Tuesday, 4 August 2015

Execution of a CAML query by means of a POST method type REST call to get list view data in the Host Web from App Web


Few days ago, We faced a requirement from our client. The requirement was to read a SharePoint listview in the host web from app web. As we all know, view is just a query on a list maintaining certain conditions. It has no physical existence. So the challenge was to get those data from list by maintaining certain conditions.

As we want to get data from a list, so the primary thinking was to read data by means of a GET 
method call using REST API. But we didn't get such method to find a solution of this problem.


The following method illustrates the scenario:

 function getListItemsForView(webUrl, listTitle, viewTitle)
{
        
        
        $.when(getJson(webUrl, listTitle, viewTitle)).then(function (data)
            {
                var viewQuery = data.d.ViewQuery;
                return getListViewItems(webUrl, listTitle, viewQuery);
            });
    }


The idea is to get the view query by means of a GET method call as follows:

 function getJson(appweburl, listname, viewTitle) 
{
        
        var d = $.Deferred();
        var datalist = null;
        var executor;

        executor = new SP.RequestExecutor(appweburl);

        executor.executeAsync({
            url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listname + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery?@target='" + _hostWebUrl + "'",
            method: "GET",
            headers: {
                "content-type": "application/json; odata=verbose", 
                "Accept": "application/json;odata=verbose"
            },
            success: function (data) {
                if (data.body != null ) {
                    datalist = JSON.parse(data.body);
                }
                d.resolve(datalist);
            },
            error: function (data, errorCode, errorMessage) {
                d.reject(errorMessage);
            }
        });
        return d.promise();
    }


Then we need to POST the view query  in JSON format to get the view data as list items.

function getListViewItems(appweburl, listTitle, queryText)
 {
        var viewXml = '<View><Query>' + queryText + '</Query></View>';      
        var queryPayload = {
            'query': {
                '__metadata': { 'type': 'SP.CamlQuery' },
                'ViewXml': viewXml
            }
        };
        
        
        var d = $.Deferred();
        var datalist = null;
        var executor;
        executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync({
            url:  appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listTitle + "')/getitems?@target='" + _hostWebUrl + "'",
            method: "POST",
            body: JSON.stringify(queryPayload),
            headers: {
                        
                        "Accept": "application/json; odata=verbose",
                        "content-type": "application/json; odata=verbose"
                    },
            success: function (data) {
                if (data.body != null ) {
                    datalist = JSON.parse(data.body).d.results;
                }
                
            
                d.resolve(datalist);

               

            },
            error: function (data, errorCode, errorMessage) {
                d.reject(errorMessage);
            }
        });
   
        return d.promise();
        
    }

Actually above method call is returning the result of the view query from the list
passed by the listTitle parameter like shown below:

<View><Query><Where><Eq><FieldRef Name="My_x0020_Column" /><Value Type="Text">01</Value></Eq></Where></Query></View>

So the trick is the execution of a CAML query by means of a POST method type REST call to get view data.



Happy SharePointing..................:)

Sunday, 21 June 2015

Programmatically Create a Term Group if not exist in SharePoint 2013 Online Term Store Management


It is possible to programmatically create a term group  if not exist in SharePoint 2013 Online Term Store Management. The following method illustrates the steps:



public static Microsoft.SharePoint.Client.Taxonomy.TermGroup CreateTermGroupIfNotExist(ClientContext context, TermStore parent, Guid termGroupId, string termGroupName, string termGroupDescription = null)
        {
            Microsoft.SharePoint.Client.Taxonomy.TermGroup termGroup = null;
            try
            {
                context.Load(parent, ts => ts.Groups);
                termGroup = parent.GetGroup(termGroupId);
                context.Load(termGroup, ts => ts.Id);
                context.ExecuteQuery();

                if (termGroup.ServerObjectIsNull != null && termGroup.ServerObjectIsNull.Value)
                {
                    parent.CreateTermGroup(termGroupName, termGroupId, termGroupDescription);
                    context.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
               
                throw ex;
            }
            return termGroup;
        }

The above method will create a term group by the name termGroupName with the id termGroupId and description termGroupDescription.


Happy SharePointing.........:)

Tuesday, 2 June 2015

Change look up field to allow multiple values by means of REST Call



It is possible change a look up field of a SharePoint list to allow multiple values by means of REST Call. The following code snippets illustrates the scenario:





    var hostweburl;
    var appweburl;

    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

function changeLookupFieldToAllowMultipleValues(listName, fieldName, callback) {

    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listName + "')/fields/getbytitle('" + fieldName + "')?@target='" + hostweburl + "'",
        method: "POST",
        body: "{ '__metadata': { 'type': 'SP.FieldLookup' }, 'AllowMultipleValues': true }",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose", "X-HTTP-Method": "MERGE"
        },
        success: function (data) { callback({ Status: "Success", Message: data }); },
        error: function (error) { callback({ Status: "Error", Message: error }); }
    });

}


Test it on your own environment.


Happy SharePointing.....................:)

Create a sharepoin list in the host web for SharePoint hosted app by means of REST Call


It is possible to create a list in the host web by means of REST call from the app web for SharePoint hosted app. The following code snippets illustrates the scenario:



function createList(listName, onCreated, onError) {

    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists?@target='" + hostweburl + "'",
        method: "POST",
        body: "{ '__metadata': { 'type': 'SP.List' }, 'Hidden':true,  'AllowContentTypes': true,'BaseTemplate': 100,'Description': '" + listName + "', 'Title':'" + listName + "'}",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose"
        },
        success: onCreated,
        error: onError
    });


}

Test it in your own environment.



Happy SharePointing....:)

Check if whether a field is exist in list by REST Call


We can check whether a field is existed in a sharepoint list by means of REST call. The following code illustrates the scenario:



    var hostweburl;
    var appweburl;

    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

function isFieldExist(listName, fieldName, callback) {

    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listName + "')/fields?$Filter=StaticName eq '" + fieldName + "'&@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose"
        },
        success: function (data) {
            var fields = JSON.parse(data.body).d.results;
            if (fields.length == 0) callback({ Status: false, Field: null });

            else callback({ Status: true, Field: fields[0] });
        },
        error: function (error) {
            callback({ Status: false, Field: null });
        }
    });


}


Sunday, 31 May 2015

Check If a list exist in host web from app web by means of REST call for provider hosted app



We can check whether a list exists in host web for the app web. This can be done by REST call to the Host web from App Web. The below code samples illustrates the scenario:



function isListExist(listName, onExist, onNotExist) {
    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listName + "')?                   @target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose"
        },
        success: onExist,
        error: onNotExist
    });
}

Sunday, 24 May 2015

Check if the Document is a Folder and folder is an OneNote Notebook


 While Searching for documents in a SharePoint site, it is possible to determine whether the  document  is a folder or not. The following code snippets illustrates the scenario:


              // Check if a document library elements  is folder or not
              foreach (DataRow row in table.Rows)
               {
                   var isFolder = row["IsContainer"] == null || row["IsContainer"] == DBNull.Value ?
                                           false : Convert.ToBoolean(row["IsContainer"]);
                }


  Again, we can check whether a folder is OneNoteBook or not.

              if ( isFolder)
                    {

                        if (row["ProgID"].ToString() == "OneNote.Notebook")
                        {
                            row["DocIcon"] = "../Images/OneNoteBook.png";
                        }
                        else
                        {
                            row["DocIcon"] = "../Images/folder.png";
                        }

                   }



 That's it...............:)