Alvaro Dias

Creating SharePoint WebApplication the geeky way

There I was coding away for my project, when I thought what if I created a sharepoint site entirely from code? and i mean right from creating a web application to a site collection and beyond. So, opened VS 2005 and started on my new mission. Turned out it isn't that complex. In fact 20 lines of code and my new sharepoint site was up Hot

Here's the code, have fun...

SPWebApplicationBuilder webApplicationBuilder = new SPWebApplicationBuilder(SPFarm.Local);
webApplicationBuilder.Port = 22222;
webApplicationBuilder.ApplicationPoolId = "Test from Code";
webApplicationBuilder.ApplicationPoolUsername = Environment.UserDomainName + "\\" + Environment.UserName;

SecureString password = new SecureString();
foreach (char c in "[email protected]$$w0rD".ToCharArray())
{
    password.AppendChar(c);
}

webApplicationBuilder.ApplicationPoolPassword = password;
webApplicationBuilder.CreateNewDatabase = true;
webApplicationBuilder.DatabaseName = "Test from Code";
webApplicationBuilder.DatabaseServer = webApplicationBuilder.DefaultZoneUri.Host;
webApplicationBuilder.UseNTLMExclusively = true;

SPWebApplication webApplication;
webApplication = webApplicationBuilder.Create();
webApplication.Name = "Test from Code";
webApplication.Provision();

SPSite siteCollection = webApplication.Sites.Add("/", "Test from Code", "Test from Code", 1033, "STS#1", "AlDUser", "Domain\\AlDUser", [email protected]);
siteCollection.Features.Add(SPFarm.Local.FeatureDefinitions["PublishingSite"].Id);
SPFarm.Local.FeatureDefinitions["PublishingSite"].Provision();
siteCollection.Close();