Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Name

Description

Last Modified Date

Download

CamlBuilder.cs

Wrapper over CAML queries.

2220/1011/2014

None

Code Block
languagec#
titleCamlBuilder.cs
 /// <summary>
    ///     CAML Operations
    /// </summary>
    public enum CamlOperator
    {
        Contains,
        BeginsWith,
        Eq,
        Geq,
        Leq,
        Lt,
        Gt,
        Neq,
        DateRangesOverlap,
        IsNotNull,
        IsNull
    }
    /// <summary>
    ///     CamlBuilder constructs CAML queries.  Useful when needing dynamic generated CAML.
    ///     Written by Tim Wheeler https://codemonkeysoftware.atlassian.net/wiki
    ///     Version 2 4 24/10/2015
    /// </summary>
    /// <remarks>
    ///     bool allWords = true;
    ///     CamlBuilder builder = new CamlBuilder();
    ///     builder.Begin(allWords); //Uses an AND query
    ///     builder.AddViewFields(new string[] {"Company", "Business Phone"});//Or leave empty to return all fields;
    ///     builder.AddClause(CamlOperator.Contains, "Title", "My Text To Search For");
    ///     builder.AddOrderBy("Company",true);
    ///     ...
    ///     SPQuery query = new SPQuery();
    ///     query.Query = builder.Query;
    ///     query.ViewFields = builder.ViewFields;
    ///     ...
    ///     Updates:
    ///     Now contains ViewXml property when using with Client Object Model
    ///     example:
    ///     var builder = new CamlBuilder();
    ///     builder.Begin(true);
    ///     builder.AddViewField("Title");
    ///     builder.AddClause(CamlOperator.Eq, Fields.Title, "My Page Title");
    ///     var query = new CamlQuery();
    ///     query.ViewXml = builder.ViewXml;
    /// </remarks>
    public class CamlBuilder
    {
        #region PrivateQuery VariablesBuilding
        private ICollection<string> _camlClauses = new List<string>(); string BuildQuery()
        {
          private Dictionary<string, bool>var _orderByFieldsquery = new Dictionary<string, bool>StringBuilder();
        private bool _requireAll;  var openOperators = 0;
   private StringBuilder _viewFields = new StringBuilder();    if (TotalClauses > 0)
 #endregion         #region Public Query{
Properties (for retrieveing the query when ready)         public string Query query.Append("<Where>");
         {       //When we have just one clause getwe {can't return BuildQuery(); }
use AND or OR.
       }         /// <summary>
   if (_camlClauses.Count > 1)
    ///     Used when dealing with Client Object Model {
       /// </summary>         public string ViewXml var totalCamlPairs = _camlClauses.Count - 1;
  {             get     //Math.DivRem(_CamlClauses.Count, 2, out remainder) + remainder;
   {                 returnwhile string.Format("<View><Query>{0}</Query><ViewFields>{1}</ViewFields>{2}</View>",
 (totalCamlPairs > 0)
                  TotalClauses == 0{
? string.Empty : Query, ViewFields,                     RowLimit.HasValuequery.Append(_requireAll ? "<RowLimit><And>" + RowLimit.Value +: "</RowLimit>" : string.Empty<Or>");
             }         }  totalCamlPairs--;
      public string ViewFields         {       openOperators++;
     get { return _viewFields.ToString(); }         }  }
      public int TotalClauses        }
{             get { return _camlClauses.Count var clausesAdded = 0;
}         }       foreach (var publicclause int? RowLimit { get; set; }in _camlClauses)
            #endregion    {
    #region public methods         /// <summary>    query.Append(clause);
    /// </summary>         /// <param name="requireAll">Uses an AND operation clausesAdded++;
between CAML pairs.  Uses Or when false. All Words/Any Word</param>         public voidif Begin(boolclausesAdded > requireAll1)
        {            {
_camlClauses = new List<string>();             _requireAll = requireAll;      query.Append(_requireAll ? "</And>"     _viewFields = new StringBuilder();
  : "</Or>");
         _orderByFields = new Dictionary<string, bool>();         }  openOperators--;
      public void AddClause(CamlOperator operation, string fieldRef, int value)       }
 {             AddClause(operation, fieldRef, value.ToString()); }
        }         public void AddClause(CamlOperator operation, string fieldRef)query.Append("</Where>");
            }
{            if (_camlClauses.Add(string.Format("<{0}><FieldRef Name='{1}' /></{0}>",orderByFields.Count > 0)
            {
     new[] { operation.ToString(), fieldRef }));       query.Append("<OrderBy>");
 }         public void AddClause(CamlOperator operation, string fieldRef, stringforeach value)(var item in _orderByFields)
     {             if (!string.IsNullOrEmpty(value)){
             {                 _camlClauses.Add(string.Format("<query.AppendFormat("<FieldRef Name='{0}><FieldRef' NameAscending='{1}' /><Value Type='Text'>{2}</Value></{0}>", item.Key, item.Value);
                }
 new[] { operation.ToString(), fieldRef, value  }));         query.Append("</OrderBy>");
   }         }
        public void AddClause(CamlOperator operation, string fieldRef, string value, string valueType)return query.ToString();
        }
   {     #endregion
       if (!string.IsNullOrEmpty(value))
  #region Private Variables
        private ICollection<string> {_camlClauses = new List<string>();
        private Dictionary<string,   bool> _camlClauses.Add(string.Format("<{0}><FieldRef Name='{1}' /><Value Type='{2}'>{3}</Value></{0}>",
orderByFields = new Dictionary<string, bool>();
        private bool _requireAll;
        new[]private { operation.ToString(), fieldRef, valueType, value })StringBuilder _viewFields = new StringBuilder();
        #endregion
   }     #region Public Query Properties }(for retrieveing the query when ready)
   public void AddClauseWithLookupId(CamlOperator operation, string fieldRef,public string value,Query
string valueType)       {
 {           get { if (!string.IsNullOrEmpty(value))return BuildQuery(); }
        }
   {     /// <summary>
        ///  _camlClauses.Add(   Used when dealing with Client Object Model
        /// </summary>
 string.Format("<{0}><FieldRef Name='{1}' LookupId='True' /><Value Type='{2}'>{3}</Value></{0}>",    public string ViewXml
        {
            get
           new[] { operation.ToString(), fieldRef, valueType, value }) {
                string viewFields = string.Empty;
                if (_viewFields != null && _viewFields.Length > 0)
                {
                    viewFields = $"<ViewFields>{_viewFields}</ViewFields>";
                }
                return string.Format("<View{3}><Query>{0}</Query>{1}{2}</View>",
                    TotalClauses == 0 ? string.Empty : Query, viewFields,
                    RowLimit.HasValue ? "<RowLimit>" + RowLimit.Value + "</RowLimit>" : string.Empty,
                    string.IsNullOrEmpty(ViewScope) ? string.Empty : " " + ViewScope);
            }
        }
        public voidstring AddViewField(string fieldRef)
  ViewScope { get; set; }
     {   public string ViewFields
       _viewFields.AppendFormat("<FieldRef Name='{0}'/>", fieldRef);
   
    }        get public{ void AddViewFields(string[] fieldRefs)
return _viewFields.ToString(); }
       { }
        public int  foreachTotalClauses
(string fieldRef in fieldRefs)     {
       {     get { return _camlClauses.Count; }
       _viewFields.AppendFormat("<FieldRef Name='{0}'/>", fieldRef.Replace("
", "_x0020_"));       public int? RowLimit { get; set; }
        #endregion
}        #region public methods
    void AddOrderBy(string fieldName, bool ascending)/// <summary>
       { /// </summary>
        ///  _orderByFields.Add(fieldName, ascending);
        }
   <param name="requireAll">Uses an AND operation between CAML pairs.  Uses Or when false. All Words/Any Word</param>
    #endregion    public void Begin(bool requireAll)
 #region Query Building     {
   private string BuildQuery()       _camlClauses = {new List<string>();
           var query_requireAll = new StringBuilder()requireAll;

           int openOperators_viewFields = new 0StringBuilder();
            _orderByFields if= (TotalClausesnew >Dictionary<string, 0bool>();
        }
    { 
        public void AddClause(CamlOperator operation, string fieldRef,  query.Append("<Where>");int value)
        {
       //When we have just one clause we can't use AND or OR. AddClause(operation, fieldRef, value.ToString());
        }
        public ifvoid (_camlClauses.Count > 1)AddClause(CamlOperator operation, string fieldRef)
        {
        {    _camlClauses.Add(string.Format("<{0}><FieldRef Name='{1}' /></{0}>",
              int totalCamlPairs = _camlClauses.Count - 1new[] {operation.ToString(), fieldRef}));
        }
        public   //Math.DivRem(_CamlClauses.Count, 2, out remainder) + remainder;
               void AddClause(CamlOperator operation, string fieldRef, string value)
    while (totalCamlPairs > 0) {
            if (!string.IsNullOrEmpty(value))
     {       {
                 query.Append(_requireAll ? "<And>" : "<Or>");_camlClauses.Add(string.Format("<{0}><FieldRef Name='{1}' /><Value Type='Text'>{2}</Value></{0}>",
                    new[] {operation.ToString(), fieldRef, value}));
  totalCamlPairs--;          }
        }
     openOperators++;   public void AddClause(CamlOperator operation, string fieldRef, string value, string   valueType)
      }  {
            if  }(!string.IsNullOrEmpty(value))
            {
    int clausesAdded = 0;         _camlClauses.Add(string.Format("<{0}><FieldRef Name='{1}' /><Value Type='{2}'>{3}</Value></{0}>",
    foreach (string clause in _camlClauses)            operation, fieldRef, valueType, value));
 {           }
        }
query.Append(clause);        public void AddClauseWithLookupId(CamlOperator operation, string fieldRef, string value, string valueType)
   clausesAdded++;     {
            if (!string.IsNullOrEmpty(value))
 if (clausesAdded > 1)        {
            {    _camlClauses.Add(
                    querystring.Append(_requireAll ? "</And>" : "</Or>");
 Format("<{0}><FieldRef Name='{1}' LookupId='True' /><Value Type='{2}'>{3}</Value></{0}>",
                      openOperators--;  operation, fieldRef,     valueType, value));
            }
       
        }
        public void       query.Append("</Where>");AddViewField(string fieldRef)
        {
   }             if (_orderByFields.Count > 0)_viewFields.AppendFormat("<FieldRef Name='{0}'/>", fieldRef);
        }
   {     public void AddViewFields(string[] fieldRefs)
        query.Append("<OrderBy>");
   {
            foreach (var itemfieldRef in _orderByFields)
   fieldRefs)
            {
                    query_viewFields.AppendFormat("<FieldRef Name='{0}' Ascending<FieldRef Name='{10}' />", item.Key, item.ValuefieldRef.Replace(" ", "_x0020_"));
            }
   }     }
        public void  query.Append("</OrderBy>");
  AddOrderBy(string fieldName, bool ascending)
        {
}             return query.ToString(_orderByFields.Add(fieldName, ascending);
        }
        #endregion
    }