Search This Blog

Friday, September 2, 2016

Using CAML Query with REST API

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.

Sending an Email in SharePoint 2013 via Javascript (REST API)

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

});


                                                                                          OR

<input type="text" name="fname" id="fname" placeholder="Your Full Name"/><br/> 
Your Email: <br/>
<input type="text" name="femail" id="femail" placeholder="Your Email Address"/><br/>
Your Message: <br/>
<textarea rows="4" cols="50" id="fmessage"></textarea><br/><br/>
<button type="button" id="fbutton">Send Message</button> 
<script type="text/javascript" src="jquery.js"></script>​​​​​​​​​​​​ 
<script type="text/javascript" src="emailform.js"></script> ​​​​​​​​​​​​​​
emailform.js code:
$(document).ready(function() {
    $("#fbutton").click(function(){
       var siteurl = _spPageContextInfo.webServerRelativeUrl;
       var name = $("#fname").val();
       var from = $("#femail").val();
       var msg = 'From: ' + name + '<br/><br/>' + 'Email: ' + from + '<br/><br/><br/>' + $("#fmessage").val();

       var urlTemplate = siteurl + "_api/SP.Utilities.Utility.SendEmail";

       $.ajax({
         contentType: 'application/json',
         url: urlTemplate,
         type: "POST",
         data: JSON.stringify({
            'properties': {
              '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
              'From': from,
              'To': { 'results': ['jdoe@company.com'] },
              'Body': msg,
              'Subject':'New Message From SharePointWebsite'
             }
           }),
         headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()                 
         },
         success: function (data) {
           alert('Your message has been sent');
           $("#fname").val('');
           $("#femail").val('');
           $("#fmessage").val('');
         },
         error: function (err) {
            alert(JSON.stringify(err));
         }
      });
   });          
});
                                 OR
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
Full Name: ​<br/>
<input type="text" name="fname" id="fname" placeholder="Your Full Name"/><br/>
Your Email: <br/>
<input type="text" name="femail" id="femail" placeholder="Your Email Address"/><br/>
Your Message: <br/>
<textarea rows="4" cols="50" id="fmessage"></textarea><br/><br/>
<button type="button" id="fbutton">Send Message</button>
<script type="text/javascript" src="jquery.js"></script>​​​​​​​​​​​​
<script type="text/javascript" src="emailform.js"></script> ​​​​​​​​​​​​​​
                <script type="text/javascript">
                $(document).ready(function() {
    $("#fbutton").click(function(){
       var siteurl = _spPageContextInfo.webServerRelativeUrl;
       var name = $("#fname").val();
       var from = $("#femail").val();
       var msg = 'From: ' + name + '<br/><br/>' + 'Email: ' + from + '<br/><br/><br/>' + $("#fmessage").val();
 
       var urlTemplate = siteurl + "_api/SP.Utilities.Utility.SendEmail";
 
       $.ajax({
         contentType: 'application/json',
         url: urlTemplate,
         type: "POST",
         data: JSON.stringify({
            'properties': {
              '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
              'From': from,
              'To': { 'results': ['XYZ@gmail.com'] },
              'Body': msg,
              'Subject':'New Message From SharePointWebsite'
             }
           }),
         headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()                
         },
         success: function (data) {
           alert('Your message has been sent');
           $("#fname").val('');
           $("#femail").val('');
           $("#fmessage").val('');
         },
         error: function (err) {
            alert(JSON.stringify(err));
         }
      });
   });         
});
                </script>

Upload multiple files with ASP.Net 4.5 FileUpload control in Visual Studio 2012 and 2013

HTML Markup
The HTML markup consists of an ASP.Net FileUpload control with AllowMultiple property set to true, a Button control for triggering the upload of files and a Label for displaying the success message after the files are uploaded.
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick ="UploadMultipleFiles" accept ="image/gif, image/jpeg" />
<hr />
<asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />

Namespaces
You will need to import the following namespace.
C#
using System.IO;

VB.Net
Imports System.IO


Upload multiple files with ASP.Net 4.5 FileUpload control in Visual Studio 2012 and 2013
Inside the Button click event handler, a loop is executed over the FileUpload PostedFiles property which holds the uploaded files.
Inside the loop, the names of the files are extracted and then the files are stored in folder.
Finally the success message is displayed using the Label control.
C#
protected void UploadMultipleFiles(object sender, EventArgs e)
{
     foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
     {
          string fileName = Path.GetFileName(postedFile.FileName);
          postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
     }
     lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}



Reset List Item ID in SharePoint 2013 List

Here we will discuss how we can reset list item id in a SharePoint 2013 list. Every item will have one id associated with it. If you have 5 items and you delete all 5 items from the SharePoint list then next time if you will try to add one item to the list then the id will starts from 6 not with 1.

Also there is no out of box way you can reset the id apart from resetting the value in the content database.

First Approach to solve the issue:
One approach you can do is, you can Save the List as a template and can use the same template to create a new list. You can follow this article to check.

Second Approach:
The other way is you can modify in the database.

Before opening your database for modification, make sure you have the list GUID.

AllListsAux table in content database maintains information about Item count and Id details for all lists.

Then open the database and run the below command:

SELECT * FROM [ContentDBName].[dbo].[AllListsAux] where ListID='GUID of the List'
Example:
SELECT * FROM [WSS_Content].[dbo].[AllListsAux] where ListID='B13CC473-6187-4478-A0DD-853E83AA6F9D'

It will display like below:

Now if you will add item to the list, the next id will be generated like below:


Then Run the below command to reset the value:

UPDATE [Content DB].dbo.AllListsAux set NextAvailableId=1 where ListID='GUID of the List'

Example:
UPDATE [WSS_Content].dbo.AllListsAux set NextAvailableId=1 where ListID='B13CC473-6187-4478-A0DD-853E83AA6F9D'

Now if you will add an item to the list, then the item will be reset (Item ID will start from 1) like below:


But Microsoft strictly do not recommend to change anything in the content database. Take special care while doing this kind of modifications.