Friday, September 13, 2013

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):-
------------------------------------------------------------------
Source: http://msdn.microsoft.com/en-us/library/ee536158(v=office.14).aspx
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(this, this.onQuerySucceeded),// when success
                Function.createDelegate(this, this.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:-
--------------------------------------------------------------------------------------
Source: http://blogs.breeze.net/mickb/CommentView,guid,d4bde347-853b-41b0-9e1c-11ce2ecbf500.aspx
<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)
---------------------------------------------------------------------------------------------------------------------------------
Source: http://blogs.breeze.net/mickb/CommentView,guid,d4bde347-853b-41b0-9e1c-11ce2ecbf500.aspx
<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:-
----------------------
Reference:- http://msdn.microsoft.com/en-us/library/aa979690(v=office.14).aspx
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.
Thank You.

25 comments:

  1. Post is really impressive... Thanks for the data update and waiting for your new updates.
    Need of Android
    Importance of Android

    ReplyDelete
  2. https://www.buyyoutubesubscribers.in/2021/11/20/how-to-earn-money-from-youtube-views/ The second biggest search engine in the world is now YouTube - it's a fact! Yet modern businesses are still unfamiliar with using YouTube to drive more business to their respective websites or sales numbers. That may be because they do not have the knowledge or time to create an effective video marketing campaign. Setting up a YouTube channel that looks professional and reflects the business brand, using that across other social media, researching keywords, producing video with annotation, collecting effective backlinks - all takes time and knowledge.

    ReplyDelete
  3. https://dynamichealthstaff.com/jobs-in-dubai-for-nurses Search Engine Optimization (SEO) is all about getting your site to the top of the list when people search for your topic in the major search engines: Google and Bing/Yahoo. It's a popularity contest. The more links you have coming to your site from other sites, the more popular the search engines think you are and the closer to the top of the list they will place you.

    ReplyDelete
  4. https://hostinglelo.in Blog commenting is a great way to get backlinks to your site. It can increase your ranking in Google and, even more importantly, get your site more exposure in your niche. You can increase your own blog readership by commenting on the blogs of others. However, anybody who has a blog knows that spammers routinely hit them with spam comments. There are a few huge mistakes you can make when commenting that will get your comments deleted as spam. If this happens it could actually hurt your ranking in Google and it definitely won't get you any new readers. Here is how you do it successfully without looking spammy.

    ReplyDelete
  5. https://www.visualaidscentre.com/lasik-eye-surgery-in-delhi/ There is a new trend in the world of gaming called game swap, also known as game sharing. It is a concept that has been used over and over again among friends and family, but is starting to branch out over the Internet. The idea behind game sharing is you essentially take the games that you have but don't really play anymore and see if you can trade for games that others have that you want.

    ReplyDelete
  6. https://onohosting.com There are many opportunities available in the video gaming industries. If you are very enthusiastic about career in the video gaming industry, this article will surely give you a couple of things for some serious consideration.

    ReplyDelete

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   &qu...

Popular posts