Monday 15 December 2008

Adding Site Collection Administrators programatically

One of my team mates had a question whether we can add site collection Administrators to the site through object model.
Its fairly simple and easy.
code chunks:
****************************************************************************
SPSite _site = null;
SPUser user = null;
SPWeb _web = null;
try
{

SPSecurity.RunWithElevatedPrivileges(delegate()
{

_site = new SPSite("siteURL");

_web = _site.OpenWeb();
_web.AllowUnsafeUpdates = true;
_web.SiteUsers.Add(@"mossbox\user1", "user1@email.com", "user1", "Added via object model");
_web.Update();
user = _web.SiteUsers[@"mossbox\user1"];
_site.SecondaryContact = user;
user.Update();
_web.AllowUnsafeUpdates = false;
});
}
catch (Exception ex)
{

MessageBox.Show("Error in Adding Site Collection Administrators " + ex.Message.ToString());


}
finally
{
if (_site != null)
{
_site.Dispose();
}
if (_web != null)
{
_web.Dispose();
}

}


}

****************************************************************************

2 comments:

Anonymous said...

Hi,

i tried to add user for my site.its throwing error -
"The user does not exist or is not unique."

Anonymous said...

Hi,

The mistake was i tried to add a new user which doesn't exist in AD.
i realised and added the user which is alredy there in AD.
it works.

Great post.

Thank You.