Archive

Archive for the ‘CAML’ Category

How To: Create CAML Query Dynamically in SharePoint

December 26, 2013 12 comments

In one of my project, I was having requirement where we must need to create CAML query dynamically.

So I’ve tried to googling..and i found some good options but it does not fulfill my requirement.

So  I’ve created my own by taking some reference.

Might be useful to someone like me:


public static string CreateCAMLQuery(List<string> parameters, string orAndCondition, bool isIncludeWhereClause)
{
 StringBuilder sb = new StringBuilder();

 if (parameters.Count == 0)
 {
AppendEQ(sb, "all");
 }

int j = 0;
for (int i = 0; i < parameters.Count; i++)
  {
   if (!string.IsNullOrEmpty(parameters[i].Split(';')[3]))
   {
    AppendEQ(sb, parameters[i]);

    if (i > 0 && j > 0)
    {
     sb.Insert(0, "<" + orAndCondition + ">");
     sb.Append("</" + orAndCondition + ">");
    }
    j++;
   }
  }
 if (isIncludeWhereClause)
 {
  sb.Insert(0, "<Where>");
  sb.Append("</Where>");
 }
 return sb.ToString();
}

public static void AppendEQ(StringBuilder sb, string value)
{
 string[] field = value.Split(';');

 sb.AppendFormat("<{0}>", field[2].ToString());
 sb.AppendFormat("<FieldRef Name='{0}'/>", field[0].ToString());
 sb.AppendFormat("<Value Type='{0}'>{1}</Value>", field[1].ToString(), field[3].ToString());
 sb.AppendFormat("</{0}>", field[2].ToString());
}

Now, you can prepare your query and call the function as per below to create dynamic query:


List<string> objColumns = new List<string>();

// here, format is like: "Column name(internal name of column);Column type; Conditional operator; Search string (input by user)

objColumns.Add("Title;Text;Contains;" + textbox1.Text.Trim());

objColumns.Add("FileLeafRef;Text;Contains;" + textbox1.Text.Trim());

SPQuery query = CreateCAMLQuery(objColumns, "Or", true);

Let me know your views or feedback.

Happy coding and SharePointing !

How To: Filter out Files with subfolder from document library using SPQuery

April 1, 2011 4 comments

I want to filter files (which is .doc,.xls,.ppt) from document library.

And I got very nice result through SPQuery which gives me all the files with subfolder recursion

Its also called CAML Query…..


SPQuery q = new SPQuery();
SPList list = web.GetListFromUrl("Your List URL");
SPListItemCollection spc = web.Lists[list.Title].GetItems(q);

q.ViewFields = "<FieldRef Name=\"Name\"/>";
q.ViewAttributes = <strong>"Scope='RecursiveAll'";
</strong>q.Query = “

<Where>

<And>

<Or>

<Or>

<Eq>

<FieldRef Name="DocIcon" />

<Value Type="Computed">doc</Value>

</Eq>

<Eq>

<FieldRef Name="DocIcon" />

<Value Type="Computed">ppt</Value>

</Eq>

</Or>

<Eq>

<FieldRef Name="DocIcon" />

<Value Type="Computed">xls</Value>

</Eq>

</Or>

<Eq>

<FieldRef Name="FSObjType" />

<Value Type="Lookup">0</Value>

</Eq>

</And>

</Where>”;

Happy .net / SharePoint Coding…