Thursday, September 24, 2009

Create Site Collection in specified database

Scenario:
Small function to create a new site collection in specified database.

Code:

function bool CreateSiteCollectionInDB(string mainSiteUrl , string databaseName )
{
bool siteCollectionCreated = false;

SPSecurity.RunWithElevatedPrivileges(delegate()
{

SPSite siteCol = new SPSite(mainSiteUrl);

foreach (SPContentDatabase contentDB in siteCol .WebApplication.ContentDatabases)
{
if (string.Equals(contentDB .Name, databaseName , StringComparison.InvariantCultureIgnoreCase)
{
if (contentDB.MaximumSiteCount <= contentDB.CurrentSiteCount)
{
throw new Exception("The maximum site count for the specified database has been exceeded. Increase the maximum site count or specify another database.");
}
else
{
using (SPSite newSiteCollection = contentDB.Sites.Add("Test", "Test Site", "", 1033, "STS#0", "1", "Administrator", "admin@sandeeptraining.com"))
{
System.Threading.Thread.Sleep(20000);
}
}

siteCollectionCreated = true;
break ;
}
}
}

if ( ! siteCollectionCreated )
{
throw new Exception("Content database not found.");
}
return true ;
}
}

Usage:
1. You can call it from a console application
2. You can call it from an application page
3. You can call it from with in a Timer ob also

3 comments:

Anonymous,  July 19, 2011 at 12:24 PM  

How do you execute such functions? do I need VS2008 or STSADM?

Anonymous,  July 19, 2011 at 12:32 PM  

Hello Sandeep,

I wanted to change document library settings --> advance settings --> Opening Documents in the Browser need to set to "Open in the client application"

How this can be done with in one shot for all document libraries for all sites? Please help me on that you can send email to hemant dot risbud at yec dot yk dot ca (replace dots and at with symbols)

Regards,
Hemant