Cross Web Application Query - SharePoint



Whenever we think of querying something in SharePoint site and showing results to users, then some initial thoughts pop ups in our mind like using Content Query web part.

No doubt that Out-of-the-box CQWP works pretty fine and does great content wrap up, but there are certain scenarios when we need to think differently.

OOB CQWP has great support for querying entire site collection or single web or a list but what will be the solution when you need to show results to users from another SharePoint web application?

Well there are some options remaining for us such as using APIs like SPSiteDataQuery and SPQuery. But there are two more options made available by the SharePoint publishing APIs; the CrossListQueryInfo and CrossListQueryCache classes. Note that to use these you need to add a reference to the SharePoint Publishing assembly (Microsoft.SharePoint.Publishing).
I am using these two classes and getting results from another web application's root site, how? Here is sample code.

I am simply Initializing CrossListQueryInfo object and querying to pages library (server template Id=850) and used scope of query as entire site collection; after getting results I am simply adding a Content Query web part and binding the results with the data property of CQWP.

I know there can be multiple ways to do this in SharePoint but this one works fine for me.

Reference: MSDN, Weblog Ton Stegeman [MVP]

protected override void CreateChildControls()
{
  base.CreateChildControls();
  try
  {
    ContentByQueryWebPart _cqwp = new ContentByQueryWebPart();

    using (SPSite site = new SPSite(http://anothersitefromwebapplication))
    {
      using (SPWeb web = site.RootWeb)
      {
        string _url = web.ServerRelativeUrl;

        //Initialize

        CrossListQueryInfo _crossListQueryInfo = new CrossListQueryInfo();
        _crossListQueryInfo.Lists = "<Lists ServerTemplate=\"850\"/>";
        _crossListQueryInfo.Webs = "<Webs Scope=\"SiteCollection\"/>";
        _crossListQueryInfo.ViewFields = "<FieldRef Name=\"Title\"/><FieldRef Name=\"FileRef\"/>";
        _crossListQueryInfo.Query = "<Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where>";
        _crossListQueryInfo.RowLimit = 10;
        _crossListQueryInfo.WebUrl = _url;

        CrossListQueryCache _crossListQueryCache = new CrossListQueryCache(_crossListQueryInfo);

        DataTable _table = _crossListQueryCache.GetSiteData(web);

        if (!this.Page.IsPostBack)
        {
         if (_table != null && _table.Rows.Count > 0)
         {
           _cqwp.Data = _table;
         }
        }

      }
     }
      this.Controls.Add(_cqwp);
   }
   catch (Exception ex)
   {
     this._error = true;
     this.Controls.Clear();
     this.Controls.Add(new LiteralControl(ex.Message));
  
}
  }