Monday, March 30, 2009

Creating Site Collection in FBA

Using WSS object model to create site collection is not that new but I have come across a scenario of creating site collection in form based authenticated web apps. I hope the following would help you to achieve the same as you need to make certain changes in your client to make it work.

For example, you have a windows service which is running with certain service account which has previelege to create site collection and other objects.

Step 1: Open you web.config of the SharePoint web app. Copy the following section and place it the app.config of your windows service. This is required for windows service to refer the user identity, otherwise it will throw "User not found" exception.






Step 2: In your code use SPSecurity.RunWithElevatedPrivileges carefully. See the following code

SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWebApplication spWebApp = new SPSite("url").WebApplication;
SPSiteCollection spscol = spWebApp.Sites;

SPSite newSiteCollection = spscol.Add("path",
"FBAUser",
"",
1033,
"sts#1",
"FBA_AspNetSqlMembershipProvider:FBAUser",
"FBA User",
"FBA User");
});

SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite newSiteCollection = new SPSite("url");

SPWeb newSCweb = newSiteCollection.OpenWeb();

newSCweb.AllowUnsafeUpdates = true;

//Code to create the custom List
#region Creating Custom List
SPListCollection FLListColl = newSCweb.Lists;
:
:
:
});

First block of RunWithElevatedPrivileges ends with site creation. Once you try to open the web with same security context, you might face access denied exception. Hence you close the context and create new elevated security context.

I hope with this you are set to go.