Saturday, July 27, 2013

Build CAML Query Dynamically based on Passing Parameters to the Query in SharePoint.

string camlQuery = CreateCAMLQuery(parameters); 
private static string CreateCAMLQuery(string[] parameters)
        {
            StringBuilder sb = new StringBuilder(); 
            if (parameters.Length == 0)
            {
                AppendEQ(sb, "all", "all");
            }
            for (int i = 0; i < parameters.Length; i += 2)
            {
                AppendEQ(sb, parameters[i], parameters[i + 1]);
                if (i > 0)
                {
                    sb.Insert(0, "<And>");
                    sb.Append("</And>");
                }
            }
            sb.Insert(0, "<Where>");
            sb.Append("</Where>"); 
            return sb.ToString();
        }

        private static void AppendEQ(StringBuilder sb, string column, string value)
        {
            sb.Append("<Eq>");
            if (column == "state")
            {
                sb.Append("<FieldRef Name='state'/>");
                sb.AppendFormat("<Value Type='Lookup'>{0}</Value>", value);
            }
            if (column == "City")
            {
                sb.Append("<FieldRef Name='City'/>");
                sb.AppendFormat("<Value Type='Lookup'>{0}</Value>", value);
            }
            if (column == "VehicleMake")
            {
                sb.Append("<FieldRef Name='VehicleMake'/>");
                sb.AppendFormat("<Value Type='Choice'>{0}</Value>", value);
            }
            if (column == "GarageType")
            {
                sb.Append("<FieldRef Name='GarageType'/>");
                sb.AppendFormat("<Value Type='Choice'>{0}</Value>", value);
            }
            sb.Append("</Eq>");
        }

No comments:

Post a Comment

Featured Post

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management https://docs.microsoft.com/en-us/azure/api-management/api-...

Popular posts