Search This Blog

Saturday, July 29, 2017

Working with CAML Query using Server OM, CSOM .NET, CSOM REST (JSON/ATOM), WEB Services, Powershell

CAML:-

---------
   <Where>
      <IsNotNull>
         <FieldRef Name='ID' />
      </IsNotNull>
   </Where>
   <ViewFields>
      <FieldRef Name='Title' />
   </ViewFields>

Server OM:-
---------------
try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                using (SPWeb spWeb = site.OpenWeb())
                {
                    SPList spList = spWeb.Lists.TryGetList("Site Pages");
                    if (spList != null)
                    {
                        SPQuery qry = new SPQuery();
                        qry.Query = "<Where><IsNotNull><FieldRef Name=\"ID\" /></IsNotNull>
                       </Where>";
                        qry.ViewFields = "<FieldRef Name=\"Name\" />";
                        SPListItemCollection listItems = spList.GetItems(qry);
                        foreach (SPListItem listItem in listItems)
                        {
                            if (listItem != null & listItem["Name"] != null)
                            {
                                lblTitle.Text += listItem["Name"].ToString() + ", ";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
            finally
            { }

Client Side Object Model .NET (CSOM .NET):-
------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using spClient = Microsoft.SharePoint.Client;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                
spClient.ClientContext clientContext = new spClient.ClientContext("http://<server_name>:6677/");
Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Pages");
                
                clientContext.Load(spList);
                clientContext.ExecuteQuery();

                if (spList != null && spList.ItemCount > 0)
                {
spClient.CamlQuery camlQuery = new spClient.CamlQuery();
camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where>
</Query><ViewFields><FieldRef Name='ID' /></ViewFields></View>";

                    spClient.ListItemCollection listItems = spList.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();
                    foreach (spClient.ListItem listItem in listItems)
                    {
                        if (listItem != null && listItem["ID"] != null)
                        {
                            lblTitle.Text += listItem["ID"].ToString() + ", ";
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
            finally
            { }
        }
    }
}


Client Side Object Model ECMA Script:-

----------------------------------------------------------
1. Create a test ASPX page in the Pages library.
2. Add the Content Editor web part and add the following script in it.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
       <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js">
</script>
    <script type="text/javascript" src="/_layouts/15/init.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            createList();
        });
    </script>
    <script type="text/ecmascript">
        function createList() {
            var clientContext = new SP.ClientContext.get_current();
            var oWebsite = clientContext.get_web();
            var listCreationInfo = new SP.ListCreationInformation();
            listCreationInfo.set_title('CustomList2'); // list name
            listCreationInfo.set_description('description'); // list description
            listCreationInfo.set_templateType(SP.ListTemplateType.genericList); //list type
            oWebsite.get_lists().add(listCreationInfo);
            clientContext.executeQueryAsync(
                Function.createDelegate(thisthis.onQuerySucceeded),// when success
                Function.createDelegate(thisthis.onQueryFailed) // when failed
                );
        }
        function onQuerySucceeded() {
            alert("List Created");
        }
        function onQueryFailed(sender, args) {
            alert("List Failed");
        }
    </script>
</asp:Content>

 -----------------------------------------------------------------------------------------------------
Client Side Object Model ECMA Script:-
--------------------------------------------------
1. Create a test ASPX page in the Pages library.
2. Add the Content Editor web part and add the following script in it.
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>    
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/init.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript">
if(typeof jQuery=="undefined"){
var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/";
document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
}
</script>
    <script type="text/javascript">
        $(document).ready(function () {              
retrieveListItems();
        });
    </script>
    <script type="text/ecmascript">
function retrieveListItems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<ViewFields><FieldRef Name=\'ID\' /><FieldRef Name=\'Title\' /></ViewFields>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
 Function.createDelegate(this, this.onQueryFailed));        
}
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() + 
'\nTitle: ' + oListItem.get_item('Title');
    }
    alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Client Side Object Model Rest (CSOM REST) using JSON:-
--------------------------------------------------------------------------------------
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead"
 runat="server">
    <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            CSOMRestJson();
        });
        function CSOMRestJson() {
            $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('CustomField')/Items?$select=Title",
                type: "GET",
                headers: { "accept""application/json;odata=verbose" },
                success: function (data) {
                    if (data.d.results) {
                        var results = data.d.results;
                        var html = "<table>";
                        for (var i = 0; i < results.length; i++) {
                            html += "<tr><td>";
                            html += results[i].Title;
                            html += "</td><td>";
                            html += "</td><tr>";
                        }
                        html += "</table>";
                        alert(html);
                        $("lblText").text(html);
                        $('#<%= lblText.ClientID %>').text(html);
                    }
                },
                error: function (xhr) {
                    alert(xhr.status + ': ' + xhr.statusText);
                }
            });
            function onDataReturned(data) {
                // TODO: handle the data
            }
            function onError(err) {
                // TODO: handle the error
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label ID="lblText" runat="server"></asp:Label>
</asp:Content>

Client Side Object Model Rest (CSOM REST) using ATOM:- (but it is not working)
---------------------------------------------------------------------------------------------------------------------------------
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            CSOMRestJson();
        });
        function CSOMRestJson() {
            $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('CustomField')/Items?$select=Title",
                type: "GET",
                contentType: "application/atom+xml;type=entry",
                headers: { "accept""application/atom+xml" },

                success: function (data) {
                    if (data.d.results) {
                        var results = data.d.results;
                        var html = "<table>";
                        for (var i = 0; i < results.length; i++) {
                            html += "<tr><td>";
                            html += results[i].Title;
                            html += "</td><td>";
                            html += "</td><tr>";
                        }
                        html += "</table>";
                        alert(html);
                        $("lblText").text(html);
                        $('#<%= lblText.ClientID %>').text(html);
                    }
                },
                error: function (xhr) {
                    alert(xhr.status + ': ' + xhr.statusText);
                }
            });
            function onDataReturned(data) {
                // TODO: handle the data
            }
            function onError(err) {
                // TODO: handle the error
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label ID="lblText" runat="server"></asp:Label>
</asp:Content>

WEB Services:-
----------------------
Web_Reference.Lists listsWS = new Web_Reference.Lists();
            listsWS.Credentials = System.Net.CredentialCache.DefaultCredentials;
            listsWS.Url = "http://<server_name>:6677/_vti_bin/Lists.asmx";

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            XmlNode queryNode = doc.CreateElement("Query");
            queryNode.InnerXml = "<Where><IsNotNull><FieldRef Name=\"ID\" /></IsNotNull></Where>";

            XmlNode viewfieldsNode = doc.CreateElement("ViewFields");
            viewfieldsNode.InnerXml = "<FieldRef Name=\"Title\" /><FieldRef Name=\"ID\" />";

            XmlNode queryOptionsNode = doc.CreateElement("QueryOptions");
            queryOptionsNode.InnerXml = "";

            string rowLimit = "150";

System.Xml.XmlNode items = listsWS.GetListItems("CustomField"null, queryNode, viewfieldsNode, rowLimit, queryOptionsNode, null);
            foreach (System.Xml.XmlNode listItem in items)
            {
                lblTitle.Text += listItem.OuterXml + ", ";
            }
Powershell:-
---------------
$spweb = Get-SPWeb http://<server_name>:6677/
$splist = $spweb.Lists.TryGetList("Site Pages")
if($splist -ne $null)
{
   $query = New-Object Microsoft.SharePoint.SPQuery;$query.Query =
"<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>";$query.ViewFields = "<FieldRef Name='Title' />";
$query.ViewFieldsOnly = $true;$items = $splist.GetItems($query);
}















Source: CAML Designer 2013.

No comments:

Post a Comment