Monday, February 14, 2011

Cross Web Application Query – SharePoint

Whenever we think of querying something in SharePoint site and showing results to users, then some intial 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 then some options left for us like using APIs like SPSiteDataQuery and SPQuery. but there are two more options which are available to us which are made available by SharePoint publishing APIs
CrossListQueryInfo and CrossListQueryCache classes. Note that to use these you need to add reference to 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 results with data property of CQWP
I know there can be multiple ways to do this in SharePoint but I got this one and works fine for me




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

    using (SPSite site = new SPSite("http://wv001945:4567"))
    {
      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));
   }
  }

No comments:

Post a Comment