Showing posts with label Object Model. Show all posts
Showing posts with label Object Model. Show all posts

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();
}

}


}

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