Enumerating All SPWebs In SPFarm.Local Into Strongly Typed Collection

So when enumerating the SPWebs within a SPFarm to build a strongly typed SPWeb collection for whatever purpose your enumeration might look like this:

[csharp]

public static List WebsPreppedForIteration()
{
var collection = new List();
foreach (SPSite x in SPFarm.Local.Services.OfType().SelectMany
(svc => ((svc).WebApplications.Where
(webApp => !webApp.Properties.ContainsKey(“Microsoft.Office.Server.SharedResourceProvider”)).SelectMany
(webApp => webApp.Sites.Cast()))).Where
(x => !Equals(x.RootWeb.Title, “Central Administration”)))
{
collection.AddRange(x.RootWeb.Webs.Cast());
}
return collection;
}

[/csharp]

I saw this in a code review today. The part I am wondering about is the SPWebApplication property bag to query the key for WCAM as opposed to do a clunky string SPWeb.Title comparison. Putting the keys out to standard output hasn’t yielded anything particularly evident, and I’m getting frustrated with the under-the-hood, unnecessary foreach loop with a fancy shirt on (the second LINQ query against the Title property(,

Does anyone know the key for WCAM?

Share

Use the SystemAccount Property When Building SPUserToken Objects

I saw a developer doing this with some funky impersonation today, so I thought I would throw out some sample code. Consider the below shell code, demonstrating the SPSite.SystemAccount property use, subsequently using it to expose the SystemAccount.Token property to pass into the SPSite constructor.

[csharp]
SPWeb primaryWeb = SPContext.Current.Web;
using (var primarySite = new SPSite(primaryWeb.Site.ID))
{
SPUserToken userToken = primarySite.SystemAccount.UserToken;
using (var secondarySite = new SPSite(primarySite.ID,userToken))
{
using (SPWeb secondaryWeb =secondarySite.OpenWeb(primaryWeb.ID))
{

try
{

}
catch (Exception)
{
}

}
}
}
[/csharp]

Share

Casting To SPDocumentLibrary

A friend just asked me the way to cast a SPList To a SPDocumentLibrary so that he could access the document library specific attributes for document library objects. This is one way of doing it:

[csharp]

public static SPWeb GetWeb(string url)
{
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
return web;
}
}
}

public static SPDocumentLibrary CastDocumentLibrary(string url, string libraryName)
{
return GetWeb(url).Lists[libraryName] as SPDocumentLibrary;
}

[/csharp]

Obviously, the casting can take on many forms, but the end result is still an SPDocumentLibrary object.

Share