Thursday, January 22, 2015

SPSiteDataQuery - The property Query contains an invalid value


I had an assignment to create some functionality to fetch information from various SharePoint Lists to perform some operations. Everything was working fine, until I have been asked to make it parameterized based on Content Types, which can be supplied by Admin/Content Author via Web Part Properties. Below is the Sample Code Snippet:

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
    using (SPWeb web = site.OpenWeb())
    {
         SPSiteDataQuery query = new SPSiteDataQuery();
         query.ViewFields = @"";
         query.Webs = @"";

         DataTable dataTable = web.GetSiteData(query);

         GridView1.DataSource = dataTable;
         GridView1.DataBind();
     }
}

So, I modified my code as follows:

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
    using (SPWeb web = site.OpenWeb())
    {
         SPSiteDataQuery query = new SPSiteDataQuery();
         query.ViewFields = @"";
         query.Query = @"query.Query%20%3D%20%40%22%20%20%20%3CWhere%3E%0A%20%3CEq%3E%0A%20%20%20%3CFieldRef%20Name%3D%27ContentType%27%20%2F%3E%0A%20%20%20%3CValue%20Type%3D%27Text%27%3EContact%3C%2FValue%3E%0A%20%3C%2FEq%3E%0A%3C%2FWhere%3E%22%3B";

         query.Webs = @"";

         DataTable dataTable = web.GetSiteData(query);

         GridView1.DataSource = dataTable;
         GridView1.DataBind();
     }
}

This change was based on the new requirement but after that I started getting the following error:

------------------------------------------------------------

Microsoft.SharePoint.SPException was unhandled by user code
  HResult=-2146232832
  Message=The property Query contains an invalid value.
  Source=Microsoft.SharePoint
  ErrorCode=-2146232832
  StackTrace:
       at Microsoft.SharePoint.SPSiteDataQuery.ReportInvalidProperty(Exception ex, String strProperty)
       at Microsoft.SharePoint.SPSiteDataQuery.ValidateXmlProperty(String strXml, String strPropertyName, String strTag, String strTag2, String strTag3)
       at Microsoft.SharePoint.SPSiteDataQuery.get_ViewXml()
       at Microsoft.SharePoint.SPWeb.GetSiteData(SPSiteDataQuery query)...........
       
  InnerException: 

------------------------------------------------------------

This freaked me out since with CAML Query Builder, my query was working fine. I searched a lot and applied some fixes mentioned in some of the posts online, but none of them worked. 

So, after spending several hours and trying various stuff with the Code, I managed to resolve it by deleting all extra non-readable characters as follows:

query.Query = @"Contact";

I am not sure why SPSiteDataQuery causes this issue whereas I have been writing queries with above mentioned readability and clarity with SPQuery Class.

Enjoy!!! :-)

No comments: