Showing posts with label CSOM. Show all posts
Showing posts with label CSOM. Show all posts
Hi there,
Working with SharePoint Online, we should be thinking on solving provisioning tasks using JSOM in combination with XML using SharePoint provisioning engine.
This post is intended to describe how to update a WebPart Property using JSOM. Specifically, I am updating JSLink property for a given webpart and page.

var listName = "NewsIdeas"
var jslinkURL = "~sitecollection/Style Library/JSLink/NewsIdeas_NewForm.js";
var pageUrl = "/Lists/" + listName + "/NewForm.aspx";
var clientContext = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
console.log(_spPageContextInfo.webServerRelativeUrl);
var oFile = clientContext.get_web().getFileByServerRelativeUrl(_spPageContextInfo.webServerRelativeUrl + pageUrl); 
var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var collWebPart = limitedWebPartManager.get_webParts();
clientContext.load(collWebPart);
clientContext.executeQueryAsync(function () 
    {
        var webPartDef = null;
        for (var x = 0; x < collWebPart.get_count() && !webPartDef; x++) {
        var temp = collWebPart.get_item(x);
            console.log(temp.get_id().toString());
        }
        webPartDef = collWebPart.get_item(0);
        if (!webPartDef) {
            console.log("Web Part: " + wpId + " not found on page: "
                         _spPageContextInfo.webServerRelativeUrl);
        return;
        }
        var webPartProperties = webPartDef.get_webPart().get_properties();
        clientContext.load(webPartProperties);
        clientContext.executeQueryAsync(
        function () {
        var webpartprops = webPartProperties;
                console.log(webpartprops.get_item('JSLink'));
                webpartprops.set_item("JSLink", jslinkURL);
                webPartDef.saveWebPartChanges();
                clientContext.load(webPartDef);
                clientContext.executeQueryAsync(
        function () {
                    console.log("WebPart properties saved.");
                },
        function() 
                {
                    console.log("Failed save WebPart Properties"); 
                });
            }, 
        function () 
            { 
                console.log("Failed to load web part properties"); 
            });
    }, 
        function () { 
        console.log("Failed to load web part collection"); 
    });

In this post, I will describe how to use CAML query with SharePoint 2013with REST endpoints.

Note: This code works in both on-prem and online.

In SharePoint, we've many ways to do one thing and we chose one which is productive for our solution. As you all have worked on CSOM and REST you will be having your own preference of doing things, like people who have worked on Server side coding would be familiar with the "SharePoint Object Model" and tend to like CSOM more than REST.
As SharePoint newbie will like to work on REST because there is no need to learn about the object model and stuff. Andrew Connell has posted an excellent post on REST vs CSOM. Please have look.

REST was introduced in SharePoint 2013, so there are some areas which Microsoft have not covered.

If you guys prefer REST (like me) you would have faced some issues while filtering multivalued taxonomy fields, and like filtering based on user, where is user is added through a group and so on.

I had to go with CSOM to achieve above tasks. But while exploring on REST, I saw a very powerful way to query lists. Like using this you can pass CAML queries into your REST call

There are couple of reasons why I am interested in this approach of getting stuff done.
1.      There are many solutions, frameworks which can be used to build complex queries easily.
2.      oData operators is somewhat limited in SharePoint when compared to CAML, liked I faced in above mentioned issues.
3.      I prefer CAML query than oData operators.

Coming to the code, there are two ways I know off actually. The first option is to embed the query in the query string of a GET call. The other option, which we will use in this post, is to embed the query in the body of a POST call.



var _RequestExecutor = new SP.RequestExecutor(webUrl);
_RequestExecutor.executeAsync({
    url: "http://webUrl/_api/web/lists/getbytitle('My list')/GetItems",
    method: 'POST',
    headers: {
        "Accept": "application/json; odata=verbose",
        "Content-Type": "application/json; odata=verbose"
    },
    body: {
        "query": {
            "__metadata": {
                "type": "SP.CamlQuery"
            },
            "ViewXml": "<View>" +
              "<Query>" + query + "</Query>" +
            "</View>"
        }
    },
    success: function (data) {
        alert("Success!!");
    },
    error: function (err) {
        alert(JSON.stringify(err));
    }
});

Here are the important things about it:
• A REST request with a CAML query is always a POST request.
• A REST request with a CAML query has always to have X-RequestDigest http header (actually because it is a POST request).
• A REST request with a CAML query should always have the attached CAML query in the request body (and not in a query string). We don’t want to mess with long urls, do we?
• A REST request with a CAML query must have the http header “Content-Type: application/json;odata=verbose” unless you use xml in the request body.

Hope this post help you.

In this post, I will describe how to send an eMail using REST API from within a SharePoint hosted App.
Note: This code works in both on-prem and Office 365, but however there is one restriction that the recipient must be a valid SharePoint user for security reason.

Introduction
The REST API in SharePoint 2013 provides developers with a simple standardised method of accessing information contained within SharePoint. It can be used from any technology that is capable of sending standard http requests and is particularly useful for developers who are not familiar with the Client Side Object Model.
        For a full list of advantages and disadvantages of the REST API, and for a comparison with other API’s click here.
You should be able to send an email from a hosted app, if you have the mail server set up correctly in      SharePoint Foundation. Check out this link on how to Configure outgoing email for a SharePoint 2013 farm.

REST URI Operators
Once you have the correct base URI the next step is to determine the correct method for sending mail.     To send a mail, SharePoint REST API exposes the following method 'SendEmail' as an endpoint which is in the class SP.Utilities.Utility.


The example below is to send a mail using ajax call.

var urlTemplate =_spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                'From': 'Hemanth.Anumolu@somewhere.com',
                'To': { 'results': ['Test@somewhere.com'] },
                    'Body': '<h1>Hello!!</h1><p>This is mail was sent from a client side function</p>',
                    'Subject':'Send eMail'
                }
        }
      ),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            alert("eMail sent successfully.");
        },
        error: function (err) {
            alert(JSON.stringify(err));
        }

});

Hope this post helps you all.