Programmatically add users to SharePoint

Points you need to remember when you add user :
  • Always run the code with Eleveted Privillages. Also use Delegate.
  • Get SPWeb by abosolute URI, not relative
  • Set AllowUnsafeUpdates to true before adding user, and turn it off once user is added.
  • Remember, if you are using FBA, prefix the Membership Provider Name before the “username” i.e
    • defaultProvider + “:” + sUserName
    • fbademo:testuser
  • Always Dispose the SpWeb object after finishing everything.

Sample Code:

SPSecurity.RunWithElevatedPrivileges(delegate {

// get provider name

MembershipSection section = (MembershipSection)WebConfigurationManager.OpenWebConfiguration(“/”).GetSection(“system.web/membership”);

string defaultProvider = section.DefaultProvider;

// get site ref

SPWeb web = new SPSite(this.Request.Url.AbsoluteUri.Replace(this.Request.Url.LocalPath, “”)).OpenWeb();

// get memeber group

SPGroup associatedMemberGroup = web.AssociatedVisitorGroup;

web.AllowUnsafeUpdates = true;

// add user to group and update it

associatedMemberGroup.AddUser(defaultProvider + “:” + sUserName, sEmail, sUserName, “”);

associatedMemberGroup.Update();

web.AllowUnsafeUpdates = false;

web.Dispose();

});

Advertisements

2 Comments

  1. Me said,

    September 26, 2009 at 12:48 AM

    Always run the code with Eleveted Privillages. ?? why

    Set AllowUnsafeUpdates to true before adding user ?? why

  2. Johnette said,

    August 6, 2013 at 8:18 AM

    So having enough chicken recipes in the kitchen would
    be rewarding. When a coating such as bread crumbs are applied
    to the meat the flavors and coating will cover a greater amount
    of the meat’s surface offering more of these flavors per bite. Essentially the most important portion of frying fish is making it possible for the oil to reach the best temperature prior to including the fish.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: