Thursday 27 August 2015

How to build dynamic caml query and complex caml queries in sharepoint

Add a .cs class with name CamlQueryElements.cs.
add the below contents to the class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Karma_Daily_Status
{
    public class CamlQueryElements
    {
        public string LogicalJoin { get; set; } // like <Or>, <And>
        public string ComparisonOperators { get; set; } // like <Eq>, <Contains>
        public string FieldName { get; set; } // Like Title
        public string FieldType { get; set; } // Like Text
        public string FieldValue { get; set; } // <span id="IL_AD6" class="IL_AD">some value</span>
    }
}

Below some examples to build caml query elements dynamically.



public IList<CamlQueryElements> AddElement()
        {
            IList<CamlQueryElements> lstOfElement = new List<CamlQueryElements>();
            try
            {


                    if (ddlTest.SelectedValue != "All")
                    {

                        lstOfElement.Add(new CamlQueryElements
                        {
                            ComparisonOperators = "Eq",
                            FieldName = "AssignedTo",
                            FieldType = "Text",
                            FieldValue = ddlTest.SelectedValue,
                            LogicalJoin = "And"
                        });

                        lstOfElement.Add(new CamlQueryElements
                       {
                           ComparisonOperators = "Eq",
                           FieldName = "Status",
                           FieldType = "Choice",
                           FieldValue = ddlTest.SelectedValue,
                           LogicalJoin = "And"
                       });

                       lstOfElement.Add(new CamlQueryElements
                        {
                           ComparisonOperators = "Eq",
                           FieldName = "AssignedTo",
                           FieldType = "Text",
                           FieldValue = item.Value,
                           LogicalJoin = "Or"
                         });
 

 
                 }

if (!dtFromDate.IsDateEmpty)
                {
                    lstOfElement.Add(new CamlQueryElements
                    {
                        ComparisonOperators = "Geq",
                        FieldName = "Created",
                        FieldType = "DateTime",
                        FieldValue = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtFromDate.SelectedDate),
                        LogicalJoin = "And"
                    });
                }


if (txtTitle.Text != string.Empty)
                {
                    lstOfElement.Add(new CamlQueryElements
                    {
                        ComparisonOperators = "Contains",
                        FieldName = "Title",
                        FieldType = "Text",
                        FieldValue = txtTitle.Text,
                        LogicalJoin = "And"
                    });
                }
 
/*
                  similarly we can add n number of elements
                  You can change this code to fill your criteria as per your <span id="IL_AD10" class="IL_AD">web app</span>.
                  But at the end you will return back "IList of CamlQueryElements" object.
            */
            }
            catch { }
            return lstOfElement;

        }


public string GenerateQuery(IList<CamlQueryElements> lstOfElement)
{
    StringBuilder queryJoin = new StringBuilder();
    try
    {
        string query = @"<{0}><FieldRef Name='{1}' /><Value {2} Type='{3}'>{4}</Value></{0}>";
        if (lstOfElement.Count > 0)
        {
            int itemCount = 0;
            foreach (CamlQueryElements element in lstOfElement)
            {
                itemCount++;
                string date = string.Empty;
                // Display only Date
                if (String.Compare(element.FieldType, "DateTime", true) == 0)
                    date = "IncludeTimeValue='false'";
                queryJoin.AppendFormat
               (string.Format(query, element.ComparisonOperators, element.FieldName, date, element.FieldType, element.FieldValue));

                if (itemCount >= 2)
                {
                    queryJoin.Insert(0, string.Format("<{0}>", element.LogicalJoin));
                    queryJoin.Append(string.Format("</{0}>", element.LogicalJoin));
                }
            }
            queryJoin.Insert(0, "<Where>");
            queryJoin.Append("</Where>");
        }
    }
    catch { }
    return queryJoin.ToString();
}


//on button click
    
IList<CamlQueryElements> lstOfElement = new List<CamlQueryElements>();
                lstOfElement = AddElement();
                strQuery = GenerateQuery(lstOfElement);