Search This Blog

Monday, March 7, 2011

Searching documents from document libraries across subsites on the basis of version


 One of the common requirements in sharepoint portals is to develop search or roll up webparts that query documents from multiple document libraries across all subsites and show the results to the user. In order to achieve this,sharepoint provides us with a class named 'SPSiteDataQuery'. Using this class we can write a CAML query to fetch all documents having the value for the fields specified in the query.

Recently, in one of our projects, we came across a requirement wherein we needed to fetch all the documents from all document libraries having a specific version like 0.1,0.2,1.0,1.1 . This kind of search is very useful when we want to find all documents that are published/not published etc.

The way we can achieve this is by using SPSiteDataQuery and to compose the query using the field '_UIVersionString':

 SPSiteDataQuery objSPSiteDataQuery = null;
 SPWeb objSPWeb = null;
 DataTable objDataTable = null;
           
 objSPWeb = SPContext.Current.Web;
 objSPSiteDataQuery = new SPSiteDataQuery();


//Specify the fields to be fetched in the results.Similar to select clause of an SQL query

 objSPSiteDataQuery.ViewFields = "<FieldRef Name=\"LinkFilename\"/>" +
                                 "<FieldRef Name=\"Created\" />" +
                                 "<FieldRef Name=\"Modified\"/>" +
                                 "<FieldRef Name=\"Editor\"/>";

                                                          
//specifying list server template=101 so that it will query only document libraries


 objSPSiteDataQuery.Lists = "<Lists ServerTemplate=\"101\" Hidden=\"FALSE\" MaxListsLimit=\"0\"/>";
               
 objSPSiteDataQuery.RowLimit = 500;

 objSPSiteDataQuery.Webs = "<Webs Scope=\"Recursive\"/>";

//querying all documents of the content type 'CT23December1' having version=1.0

 objSPSiteDataQuery.Query="<Where><And><Eq><FieldRef Name=\"ContentType\" /><Value Type=\"Computed\">CT23December1</Value></Eq><Eq><FieldRef Name=\"_UIVersionString\" /><Value Type=\"Text\">1.0</Value></Eq></And></Where>";

//SPSiteDataQuery returns the results in the datatable.Use it for showing the results to the user.

 objDataTable = objSPWeb.GetSiteData(objSPSiteDataQuery);

No comments:

Post a Comment