CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: CAML

Using CAML with SharePoint REST API

Do you prefer REST over CSOM as I do? I’ll skip the whys. Andrew Connell put it already in wrtiting so nicely. Well, if you do prefer REST, then you must have discovered some shortcomings of REST, or its incompleteness compared to CSOM. I think of:

  1. Inability to filter items based on multivalued taxonomy fields
  2. Inability to filter items based on user fields where user is added through a group, rather than directly, e.g. AssignedTo=[Me] combined with a SharePoint group.

In such situations I was forced to use CSOM. Until yesterday. Yesterday I learned that we can actually use CAML queries in REST requests.

 

This enables using REST in all situations. The REST API is still developed and many features are added. Maybe a particular operation that needs a CAML query today, can be supported in the core REST API and can be easily refactored then.

But until then, we can use CAML queries in REST requests. 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.
Needed HTTP Headers in REST requests

HTTP headers you have to provide in REST requests with CAML queries

You can use jQuery or SP.RequestExecutor to make an ajax call. The REST endpoint is:

_api/web/Lists/GetByTitle('<your list title>')/GetItems

The request body (if you use json, and I bet, you do) is in this format:

{ "query" :
   {"__metadata": 
      { "type": "SP.CamlQuery" }
      , "ViewXml": "<YOUR CAML QUERY>" 
   }
}

Here is the boilerplate for a REST request with a CAML Query:

function getDataWithCaml(listName, caml) {
    var endpoint = "/_api/web/lists/GetByTitle('" 
        + listName + "')/GetItems";
    var requestData = { "query" :
           {"__metadata": 
              { "type": "SP.CamlQuery" }
              , "ViewXml": caml
           }
        };
    return jQuery.ajax({
        url: endpoint,
        method: "POST",
        data: requestData,
        headers: {
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "Accept": "application/json; odata=verbose",
            "Content-Type": "application/json; odata=verbose"
        }
    });
}

This function is just an example. It has no error handling, and it takes for granted that your list is in the root site for on your (sub-)domain (“/”). So take it as an example only.

Here is how the function can be invoked

var caml = "<View><Query><Where><Or><Eq><FieldRef Name='AssignedTo' /><Value Type='Integer'><UserID/></Value></Eq><Membership Type='CurrentUserGroups'><FieldRef Name='AssignedTo' /> </Membership></Or></Where></Query></View>";
getDataWithCaml("Tasks", caml);

Paging with JSOM

If there are many list items you try retrieve with javascript object model,paging could be very useful. Today I came across a wonderful blog post series about javascript object model in SharePoint: The SharePoint javascript object model – Resources and Real World Examples posted by David Mann and published on Aptilon Blog.

There is an example how to achieve paging with JSOM. The key is items.get_listItemCollectionPosition() and query.set_listItemCollectionPosition()

I have refactored David’s example to avoid global variables and to put into a module. Here is it. If you have a Tasks list in your site with many items, just hit F12 to open the console and paste this and see the result:

(function(SP) {
   var 
      ctx = SP.ClientContext.get_current(),
      list = ctx.get_web().get_lists().getByTitle('Tasks'),
      position,
      enumerator,
      view = '<View><ViewFields><FieldRef Name="Title"/></ViewFields><RowLimit>10</RowLimit></View>',
      query = new SP.CamlQuery(),
      items,
      init = function() {
         query.set_viewXml(view);			
      },
      loadChunks = function() {
         query.set_listItemCollectionPosition(position);
         items = list.getItems(query);
         ctx.load(items);
         ctx.executeQueryAsync(success, error);
      },
      success = function() {
         console.log("\nFound Matching Items! ");
         enumerator = items.getEnumerator();
         while(enumerator.moveNext()) {
            console.log("Title: " + enumerator.get_current().get_item("Title") );
         }
         position = items.get_listItemCollectionPosition();
         //when there are no items position is null
         position && loadChunks();
      },
      error = function(sender, args) {
         console.log('Request failed. Error: ' + args.get_message() + '. StackTrace: ' + args.get_stackTrace());
      };

   init();
   loadChunks();
})(SP);

Today i Caml

Använd <Today /> i Caml…

Ändra query på en SPView i koden

När man vill ändra hur data ska visas i en SPView i SPList, då måste man ändra CAML-Query. Det enklaste sättet att skapa en CAML Query är att använda ett program som heter CAML Query Builder. Ta bara bort <Query> och </Query> för att de behövs inte.

Sedan är det bara att loopa igenom alla vyer man behöver.

private void UpdateQueryInGroupViews(SPList list)
{
    for (int i = 1; i < 11; i++)
    {
        string viewname = String.Format("Group {0:D2}", i);
        SPView view = list.Views[viewname];
        string query = 
                String.Format(
                        "<Where><Or><Contains><FieldRef Name='Group' />"
                        + "<Value Type='Text'>{0:D2}</Value></Contains>"
                        + "<IsNull><FieldRef Name='Group' /></IsNull></Or></Where>"
                        + "<OrderBy><FieldRef Name='EventDate' Ascending='True' />"
                        + "</OrderBy>", i);
        view.Query = query;
        view.Update();
    }
}

I denna query sorterar vi efter Start Date och visar bara händelser för sin grupp.

Discovering SharePoint

And going crazy doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

RealActivity - Real-time and trustworthy

Blog site of founder, RealActivty - Paul J. Swider

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

paul.tavares

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint

blksthl

Mostly what I know about SharePoint - CommunicoCuspis