Thursday, April 22, 2010

Sharepoint MOSS 2007 distribute announcement over several site collections

The following lines of code iterate over all site collections within a Sharepoint / MOSS 2007 Farm and it's adding an announcement to each site collection.

To use this code i had to impersonate the user to the application pool user. This is the only user which allows me to access all content databases.

// connect to sharepoint and read all site collections under "default web site"
foreach (var application in SPWebService.ContentService.WebApplications)
{
siteCollectionMax = application.Sites.Count;

this.UpdateProcess(string.Format("Connecting to: {0}", application.Name));
this.UpdateProcess(string.Format("Total Amount of #{0} site collections", siteCollectionMax));

this.UpdateProcess("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");

string currentUrl = string.Empty;
this.UpdateProcess(
"Connecting to Sharepoint this can take some seconds!"
);
System.Threading.Thread.Sleep(500);

foreach (SPSite site in application.Sites)
{
try
{
currentUrl = site.Url;
siteCollectionCounter++;

using (SPSite s = new SPSite(site.Url))
{

using (SPWeb web = s.OpenWeb())
{
SPList list = web.GetList(s.Url + "/Lists/Announcements");
if (list != null)
{
SPListItemCollection items = list.Items;
SPListItem item = items.Add();
item["Title"] = title.Trim();
item["Body"] = body.Trim();
item["Expires"] = expiries;
item.Update();
this.UpdateProcess(
string.Format("#{0} of {1} - Announcement added to 'Site Collection': {2}", siteCollectionCounter.ToString(), siteCollectionMax.ToString(), currentUrl)
);
}
else
{
string txt = string.Format("Following 'Site Collection' does not contain an Announcement List: {0}", currentUrl);
this.UpdateProcess(
txt
);
errors.Add(txt);
}
}
}
System.Threading.Thread.Sleep(250);
}
catch (Exception ex)
{
this.UpdateProcess(
string.Format("An error occured: {0}", ex.Message)
);
}
}
}


The this.UpdateProcess(...) method is a helper method which writes into a log file. You can simply replace it and write to the Console.

No comments:

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge