Pages

Tuesday, 3 June 2014

Using SPSiteDataQuery with Content Types


I was working on a solution to find items by its content type throughout site collection using SPSiteDataQuery. I would suggest using Content Type ID  instead querying using content type name as I found it breaks when move to other UAT or Production environments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;
using System.Data;
namespace EventCamlConsole
{
class Program
{
static void Main(string[] args)
{
using (SPSite osite = new SPSite("http://your_site_url_here/"))
{
using (SPWeb oweb = osite.RootWeb)
{
Console.WriteLine("--------------------------------------");
Console.WriteLine("Tests execution...");
SPSiteDataQuery query = new SPSiteDataQuery();
query.Webs = "<Webs Scope=\"Recursive\">";
query.Lists = "<Lists BaseType='1' MaxListsLimit='0'/>";
query.ViewFields = "<FieldRef Name='Title' />";
SPContentType cTypeCollection = oweb.ContentTypes["Content_Type_Name"];
string where = string.Format(
@"<Where>
<BeginsWith>
<FieldRef Name='ContentTypeId'/>
<Value Type='Text'>{0}</Value>
</BeginsWith>
</Where>", cTypeCollection.Id);
// Set the query string.
query.Query = where;
DataTable results = oweb.GetSiteData(query);
foreach (DataRow row in results.Rows)
{
Console.WriteLine("{0}", row["Title"]);
}
}
}
}
}
}
view raw QueryCT hosted with ❤ by GitHub