With the introduction of Apps, and solutions going away. What is the best way to create a site collection programmatically? I am on-premise. Can it be done with JavaScript? I can create sub-sites with js, but what about Site Collections?
I have found some c# code to create a site collection, but where do I run it from? In an App?
I have successfully created a site collection programmatically using an event receiver (c#). Microsoft has confirmed that it is not possible to create a site collection with JavaScript. I thought I would share my total solution since I don't see complete documentation from start to finish.
Add Event Receiver
Here is the code for the eventreceiver.cs file:
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace SharePointProject5.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
//create admin service reference
SPAdminService.Admin admService = new SPAdminService.Admin();
//grant proper admin credentials to admin service
admService.Credentials = new System.Net.NetworkCredential("Farmaccount", "Password", "Domain");
try
{
//specify new site collection path
String SitePath = "http://twv101sp13/pm/new2013";
//setup properties to create the site, see reference below for more info
admService.CreateSite(SitePath, "new site", "description", 1033, "STS#1", "bluebunny\\sp13admin", "System Account", "[email protected]", "", "");
}
catch (System.Web.Services.Protocols.SoapException ex)
{
//I added this section so any errors would be logged in the server application log
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
System.Diagnostics.EventLog.WriteEntry("Application", "Message:\n" + ex.MRessage + "\nDetail:\n" +
ex.Detail.InnerText +
"\nStackTrace:\n" + ex.StackTrace);
});
}
}
}
}
So you only want this to run when a certain list adds an item so you have to modify the Elements.xml file.
Open the Elements.xml, replace this line <Receivers ListTemplateId="101">
with <Receivers ListUrl="http://{SharepointSite}/{targetListName}">
- this is so we can target only that list and not all lists on the the site
Right-click your project and deploy
You should be able to create a new item and then check for your new site collection.
One issue that I experienced is sites cannot start with a numerical character.
At the bottom of this article it tells how to debug a feature event receiver. Without that I would have been dead in the water: http://msdn.microsoft.com/en-us/library/ee231550.aspx
These three articles helped a lot: