n
nWhenever 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.
n
nno 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.
n
nOOB 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?
n
nWell 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
n
nCrossListQueryInfo and CrossListQueryCache classes. Note that to use these you need to add reference to SharePoint Publishing assembly, Microsoft.SharePoint.Publishing
n
nI am using these two classes and getting results from another web application’s root site, how? here is sample code
n
nI 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
n
nI know there can be multiple ways to do this in SharePoint but I got this one and works fine for me
n
n
n
n
n
n
n
n
n
n
nprotected override void CreateChildControls()
n
n{
n
n base.CreateChildControls();
n
n try
n
n {
n
n ContentByQueryWebPart _cqwp = new ContentByQueryWebPart();
n
n
n
n using (SPSite site = new SPSite(“http://wv001945:4567”))
n
n {
n
n using (SPWeb web = site.RootWeb)
n
n {
n
n string _url = web.ServerRelativeUrl;
n
n
n
n //Initialize
n
n
n
n CrossListQueryInfo _crossListQueryInfo = new CrossListQueryInfo();
n
n _crossListQueryInfo.Lists = “<Lists ServerTemplate=\”850\”/>”;
n
n _crossListQueryInfo.Webs = “<Webs Scope=\”SiteCollection\”/>”;
n
n _crossListQueryInfo.ViewFields = “<FieldRef Name=\”Title\”/><FieldRef Name=\”FileRef\”/>”;
n
n _crossListQueryInfo.Query = “<Where><IsNotNull><FieldRef Name=’Title’ /></IsNotNull></Where>”;
n
n _crossListQueryInfo.RowLimit = 10;
n
n _crossListQueryInfo.WebUrl = _url;
n
n
n
n CrossListQueryCache _crossListQueryCache = new CrossListQueryCache(_crossListQueryInfo);
n
n
n
n DataTable _table = _crossListQueryCache.GetSiteData(web);
n
n
n
n if (!this.Page.IsPostBack)
n
n {
n
n if (_table != null && _table.Rows.Count > 0)
n
n {
n
n _cqwp.Data = _table;
n
n }
n
n }
n
n
n
n }
n
n }
n
n this.Controls.Add(_cqwp);
n
n }
n
n catch (Exception ex)
n
n {
n
n this._error = true;
n
n this.Controls.Clear();
n
n this.Controls.Add(new LiteralControl(ex.Message));
n
n }
n
n }
n
n
n