|
Bye Bye GuidGen!
Exploring .NET, SharePoint and Beyond
|
Bye Bye GuidGen!
Today I found that Microsoft release a SharePoint Introduction website for .NET develpers.The site is created with SilverLight and contains lots of information on what developer can use when they start with SharePoint.
Check it out on: Do Less. Get More. Develop on SharePoint.
using (SPSite site = new SPSite("http://demosite"))
{
SPWeb rootWeb = site.RootWeb;
// Query to get all publishing pages in the sitecollection that are detached from pagelayout.
// ServerTemplate=850, is template for the Pages lists.
SPSiteDataQuery dataQuery = new SPSiteDataQuery();
dataQuery.Webs = "< Webs Scope="SiteCollection">";
dataQuery.Lists = "< Lists ServerTemplate="850">";
dataQuery.ViewFields = "< FieldRef Name="FileRef" Nullable="TRUE">";
dataQuery.Query = "< Where>" +
"< Contains>" +
"< FieldRef Name="PublishingPageLayout">" +
"< Value Type="Text">?DisconnectedPublishingPage=true< /Value>" +
"< /Contains>" +
"< /Where>";
// Store result in datatable
DataTable dt = rootWeb.GetSiteData(dataQuery);
foreach (DataRow row in dt.Rows)
{
if (row.IsNull("FileRef"))
{
Console.WriteLine("FileRef should not be null!");
continue;
}
// Strip listitem id from fieldref value
string fieldRef = row["FileRef"].ToString().Trim();
if (!string.IsNullOrEmpty(fieldRef))
{
int pos = fieldRef.IndexOf(";#");
if (pos > -1)
{
fieldRef = fieldRef.Substring(pos + 2);
}
}
Console.WriteLine(fieldRef);
}
}
Also you can use the 'Content and Structure Reports' functionality from MOSS to get an overview of all publishing pages that are disconnected from the pagelayout.
using (SPSite site = new SPSite("http://demosite"))
{
using (SPWeb web = site.OpenWeb())
{
SPField field = web.Fields.GetFieldByInternalName("Title);
Console.WriteLine("Field: {0}", fieldName);
Console.WriteLine("==============================");
var usage = SPSiteColumnUsage.GetUsages(field);
foreach (var u in usage)
{
Console.WriteLine("Id: {0}", u.Id);
Console.WriteLine("Scope: {0}", u.Scope);
Console.WriteLine("ContentTypeId: {0}", u.ContentTypeId);
Console.WriteLine("IsUrlToList: {0}", u.IsUrlToList);
Console.WriteLine("Url: {0}", u.Url);
Console.WriteLine();
}
}
}
See a working example on http://SPSiteColumnUsage.codeplex.com////// Class with site column usage information. /// public class SPSiteColumnUsage { public static IList< SPSiteColumnUsage> GetUsages(SPField field) { List< SPSiteColumnUsage> list = new List< SPSiteColumnUsage>(); if(field != null && field.UsedInWebContentTypes) { // Use reflection to get the fields collection for the specified field SPFieldCollection fieldCollection = field.GetType().GetProperty("Fields", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(field, null) as SPFieldCollection; if(fieldCollection != null) { // Get the web context from the collection SPWeb web = fieldCollection.Web; // First collect all contenttypes to an array, so we can use Linq var contentTypes = web.ContentTypes.CopyToArray< SPContentType>(); // Filter contenttypes where field is used var contentTypesWithField = (from contentType in contentTypes where contentType.Fields.ContainsField(field.InternalName) select contentType).ToArray(); // Create usages for fields in contenttypes foreach(SPContentType contentType in contentTypesWithField) { SPSiteColumnUsage siteColumnUsage = new SPSiteColumnUsage(field.Id, field.Scope, contentType.Id); list.Add(siteColumnUsage); } // Get unique lists-urls where contentypes are beeing used var listUrlsContentTypeUsage = (from contentType in contentTypesWithField let contentTypeUsages = SPContentTypeUsage.GetUsages(contentType) from contentTypeUsage in contentTypeUsages where contentTypeUsage.IsUrlToList select contentTypeUsage.Url).Distinct().ToArray(); // Create usages for fields in list foreach (string listUrl in listUrlsContentTypeUsage) { SPSiteColumnUsage siteColumnUsage = new SPSiteColumnUsage(field.Id, field.Scope, listUrl); list.Add(siteColumnUsage); } } } return list; } private readonly Guid _Id; private readonly string _Scope; private readonly SPContentTypeId _ContentTypeId; private readonly string _Url; private SPSiteColumnUsage(Guid id, string scope, SPContentTypeId contentTypeId) { _Id = id; _Scope = scope; _ContentTypeId = contentTypeId; _Url = null; } private SPSiteColumnUsage(Guid id, string scope, string url) { _Id = id; _Scope = scope; _ContentTypeId = SPContentTypeId.Empty; _Url = url; } public Guid Id { [DebuggerStepThrough] get { return _Id; } } public string Scope { [DebuggerStepThrough] get { return _Scope; } } public SPContentTypeId ContentTypeId { [DebuggerStepThrough] get { return _ContentTypeId; } } public string Url { [DebuggerStepThrough] get { return _Url; } } public bool IsUrlToList { [DebuggerStepThrough] get { return _ContentTypeId.Equals(SPContentTypeId.Empty) && !string.IsNullOrEmpty(_Url); } } }
public static class SharePointPublishingHelper
{
public static bool IsPublishingWeb(SPWeb web)
{
return GetBooleanValueFromPropertyBag(web, "__PublishingFeatureActivated", false);
}
public static bool IncludeInGlobalNavigation(SPWeb web)
{
return GetIncludeInNavigation(web, "__GlobalNavigationExcludes");
}
public static bool IncludeInCurrentNavigation(SPWeb web)
{
return GetIncludeInNavigation(web, "__CurrentNavigationExcludes");
}
private static bool GetIncludeInNavigation(SPWeb web, string propertyKey)
{
if(web == null)
{
throw new ArgumentNullException("web");
}
if (string.IsNullOrEmpty(propertyKey))
{
throw new ArgumentException("The argument can't be null or a empty string.", "propertyKey");
}
SPWeb parentWeb = web.ParentWeb;
if (!web.IsRootWeb && parentWeb != null)
{
string globalNavigationExcludes = GetValueFromPropertyBag(parentWeb, propertyKey) as string;
if (!string.IsNullOrEmpty(globalNavigationExcludes))
{
string[] list = globalNavigationExcludes.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
bool found = list.Contains(web.ID.ToString("D"));
return !found;
}
}
return true;
}
public static bool InheritGlobalNavigation(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
if (web.IsRootWeb)
{
return false;
}
return web.Navigation.UseShared;
}
public static bool InheritCurrentNavigation(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
if (web.IsRootWeb)
{
return false;
}
return GetBooleanValueFromPropertyBag(web, "__InheritCurrentNavigation", true);
}
public static bool IncludeSubSitesInNavigation(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
return GetBooleanValueFromPropertyBag(web, "__IncludeSubSitesInNavigation", true);
}
public static bool IncludePagesInNavigation(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
return GetBooleanValueFromPropertyBag(web, "__IncludePagesInNavigation", true);
}
public static string OrderingMethod(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
string value = GetValueFromPropertyBag(web, "__NavigationOrderingMethod").ToString();
switch (value)
{
case "0":
return "Automatic";
case "1":
return "ManualWithAutomaticPageSorting";
case "2":
return "Manual";
default:
break;
}
return "Manual";
}
public static bool NavigationShowSiblings(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
if (web.IsRootWeb)
{
return false;
}
return GetBooleanValueFromPropertyBag(web, "__NavigationShowSiblings", true);
}
public static string NavigationAutomaticSortingMethod(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
string value = GetValueFromPropertyBag(web, "__NavigationAutomaticSortingMethod").ToString();
switch (value)
{
case "0":
return "Title";
case "1":
return "CreatedDate";
case "2":
return "LastModifiedDate";
default:
break;
}
return "Title";
}
public static bool NavigationSortAscending(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
return GetBooleanValueFromPropertyBag(web, "__NavigationSortAscending", true);
}
public static Guid PagesListId(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
string value = GetValueFromPropertyBag(web, "__PagesListId").ToString();
if (string.IsNullOrEmpty(value))
{
return Guid.Empty;
}
return new Guid(value);
}
public static bool InheritCustomMasterUrl(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
return GetBooleanValueFromPropertyBag(web, "__InheritsCustomMasterUrl", false);
}
public static bool InheritAlternateCssUrl(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
return GetBooleanValueFromPropertyBag(web, "__InheritsAlternateCssUrl", false);
}
public static bool IsInheritingAvailableWebTemplates(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
return GetBooleanValueFromPropertyBag(web, "__InheritWebTemplates", false);
}
public static bool IsInheritingAvailablePageLayouts(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
string value = GetValueFromPropertyBag(web, "__PageLayouts").ToString();
if (!string.IsNullOrEmpty(value))
{
return value.Equals("__inherit", StringComparison.InvariantCultureIgnoreCase);
}
return false;
}
public static string[] GetAvailablePageLayouts(SPWeb web)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
List list = new List();
string value = GetValueFromPropertyBag(web, "__PageLayouts").ToString();
if (!string.IsNullOrEmpty(value))
{
SPWeb rootWeb = web.Site.RootWeb;
var pageLayouts = XElement.Parse(value).Elements("layout");
foreach (var pageLayout in pageLayouts)
{
string itemUrl = null;
string id = null;
XAttribute guidAttribute = pageLayout.Attribute("guid");
if (guidAttribute != null)
{
id = guidAttribute.Value;
}
// first try to find pagelayout by id
if (!string.IsNullOrEmpty(id))
{
SPFile file = rootWeb.GetFile(new Guid(id));
if (file != null && file.Exists)
{
itemUrl = file.ServerRelativeUrl;
}
}
// if no pagelayout is found by id, try the url
if (string.IsNullOrEmpty(itemUrl))
{
string url = null;
XAttribute urlAttribute = pageLayout.Attribute("url");
if (urlAttribute != null)
{
url = urlAttribute.Value;
}
SPFile file = rootWeb.GetFile(url);
if (file != null && file.Exists)
{
itemUrl = file.ServerRelativeUrl;
}
}
if (!string.IsNullOrEmpty(itemUrl))
{
list.Add(itemUrl);
}
}
}
return list.ToArray();
}
private static object GetValueFromPropertyBag(SPWeb web, string key)
{
if (web == null)
{
throw new ArgumentNullException("web");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("The argument can't be null or a empty string.", "key");
}
object value = null;
// First check the AllProperties collection
if (web.AllProperties.ContainsKey(key))
{
value = web.AllProperties[key];
}
// Still empty, check also the Properties collection
if (value == null)
{
if (web.Properties.ContainsKey(key))
{
value = web.Properties[key];
}
}
return value;
}
private static bool GetBooleanValueFromPropertyBag(SPWeb web, string key, bool defaultValue)
{
string value = GetValueFromPropertyBag(web, key) as string;
bool ret;
if (!bool.TryParse(value, out ret))
{
ret = defaultValue;
}
return ret;
}
}
public static class Helpers
{
public static T[] CopyToArray(this ICollection collection)
{
if (collection == null) { return new T[0]; }
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return array;
}
}
Now it is possible to make Linq queries like this:
using (SPSite site = new SPSite("http://demosite"))
{
using (SPWeb web = site.OpenWeb())
{
// Get all webs ordered by Title
var items1 = web.Webs.CopyToArray< SPWeb>().OrderBy(p => p.Title);
foreach (var item in items1)
{
Console.WriteLine(item.Title);
}
// Get all content types grouped by group and ordered by group and name
var items2 = web.ContentTypes.CopyToArray< SPContentType>().GroupBy(p => p.Group).OrderBy(g => g.Key);
foreach (IGrouping<> group in items2)
{
Console.WriteLine(group.Key);
foreach (var item in group.OrderBy(p => p.Name))
{
Console.WriteLine(item.Name);
}
}
// Get a list by name and not by title
var list = web.Lists.CopyToArray< SPList>().SingleOrDefault(p => p.RootFolder.Name.Equals("pages", StringComparison.InvariantCultureIgnoreCase));
if (list != null)
{
Console.WriteLine("List: {0} found!", list.Title);
}
}
}
public class FakeSharePointWorkerRequest : SimpleWorkerRequest
{
private readonly string _ServerName;
public FakeSharePointWorkerRequest(SPWeb web) : base(web.ServerRelativeUrl, web.Site.WebApplication.IisSettings[SPUrlZone.Default].Path.FullName, string.Empty, string.Empty, null)
{
_ServerName = web.Site.HostName;
}
public override string GetServerName()
{
return _ServerName;
}
}
public static HttpContext GetFakeHttpContextForSharePoint(SPWeb web)
{
FakeSharePointWorkerRequest workerRequest = new FakeSharePointWorkerRequest(web);
HttpContext httpContext = new HttpContext(workerRequest);
httpContext.Items["HttpHandlerSPWeb"] = web;
httpContext.Items["HttpHandlerSPSite"] = web.Site;
return httpContext;
}
Usage example
using(SPSite site = new SPSite("http://demosite"))
{
using(SPWeb web = site.OpenWeb())
{
bool httpContextIsFake = false;
if (HttpContext.Current == null)
{
// Must be set before using the SPLimitedWebPartManager in a console app
HttpContext.Current = GetFakeHttpContextForSharePoint(web);
httpContextIsFake = true;
}
// Do your own thingies!
// .....
// Don't forget to reset the current http context
if (httpContextIsFake)
{
HttpContext.Current = null;
}
}
}