add users to sharepoint programmatically
- I am trying to add users to sharepoint 2007 programmatically. I have set up my site to use forms authentication using the default aspsqlmembershipprovider. However, I want to be able to add a user to my database and to a sharepoint with a defined role. User are added to the database, no problem, but not to sharepoint. Hope someone can help me. My code is as follows:
Code SnippetMembershipCreateStatus status;
MembershipUser user = Membership.CreateUser(username, password, email, "Not used", "Not used", true, out status);
if(status.ToString().ToLower().Equals("success"))
{
SPWeb portalweb = SPContext.Current.Web;
if(portalweb != null) {
SPWeb site = SPContext.Current.Site.RootWeb;
SPRoleDefinitionCollection roleDefinitions = site.RoleDefinitions;
SPRoleAssignmentCollection roleAssignments = site.RoleAssignments;
SPRoleAssignment roleAssignment =
new SPRoleAssignment(username, email, username, "myNotes");
SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
roleDefBindings.Add(roleDefinitions["Contribute"]);
roleAssignments.Add(roleAssignment);
}
With this code I get the following error message:
The user does not exist or is not unique.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: The user does not exist or is not unique.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[COMException (0x81020054): The user does not exist or is not unique.]
Microsoft.SharePoint.Library.SPRequestInternalClass.EnsureUserExists(String bstrUrl, String bstrLogin, String bstrEmail, String bstrName, String bstrNotes, Boolean bIsRole, Boolean bSendEmail, Boolean bForceAdd, Byte[]& ppsaSystemId, Boolean bImportDeleted, Int32& plUserId) +0
Microsoft.SharePoint.Library.SPRequest.EnsureUserExists(String bstrUrl, String bstrLogin, String bstrEmail, String bstrName, String bstrNotes, Boolean bIsRole, Boolean bSendEmail, Boolean bForceAdd, Byte[]& ppsaSystemId, Boolean bImportDeleted, Int32& plUserId) +145
[SPException: The user does not exist or is not unique.]
Microsoft.SharePoint.Library.SPRequest.EnsureUserExists(String bstrUrl, String bstrLogin, String bstrEmail, String bstrName, String bstrNotes, Boolean bIsRole, Boolean bSendEmail, Boolean bForceAdd, Byte[]& ppsaSystemId, Boolean bImportDeleted, Int32& plUserId) +186
Microsoft.SharePoint.SPRoleAssignmentCollection.Add(SPRoleAssignment roleAssignment) +410
Netcompany.Forsikringsguiden.Backend.Agents.UserManager.CreateUser(String username, String password, String email) +373
Netcompany.Forsikringsguiden.UI.Administration.Users.CreateUser.Submit_Click(Object sender, EventArgs e) +92
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102
Odpovědi
Rae,
As far it seems that you have already configured a membership provider for your sharepoint site, and you have forms authentication working.
If not, please read here - http://weblog.vb-tech.com/nick/archive/2006/06/14/1617.aspx
So, then you all need is to create a user and add it to a default group, that's say "VISITORS".
Code Snippet//1) Create membership user
MembershipUser membershipUser = Membership.CreateUser(login, password, email);
//now you have it
//2) Create sharepoint user
SPWeb spWeb = SPControl.GetContextWeb(HttpContext.Current);
//get your site instance
SPUser spUser = spWeb.EnsureUser(login);
//now you have sharepoint user
//3) Add sharepoint user to a desired group
SPGroup spGroup = spWeb.SiteGroups["VISITORS"];
//get your group
spGroup.AddUser(spUser);
//that should do the work
That's all! Of course some error-checking is nessesary.
If you have some questions, please write with some concrete questions.
Všechny reakce
if using forms authentication and asp role/member provider, can you not use the asp role/member methods to add new users?
That method you're using, i think the way it works is it takes an existing asp.net or AD account and adds it into the sharepoint users. in your case no such user exists so it can't be added to sharepoint.
I think first you'd need to call the asp.net methods to add the user to sql/asp provider then call the sharepoint methods to import from sql/asp provider....
these are just my assumptions based on the error you're receiving.
- Whenever you create an aspnetdb based user account the username really isn't the typical username. It becomes aspnet:username (or something similar). Play around with adding a database-based user account to a SharePoint group manually, and then logging in as them to see their SharePoint UserInfo page (My Settings). Hope this helps.
- I could be way off the mark with what you're trying to do, but I've added user accounts to SharePoint site groups using the following (where groupMembers is an ArrayList of SPUserInfo objects with details populates from the user's AD entry):
site.SiteUsers.AddCollection((SPUserInfo[])groupMembers.ToArray(typeof(SPUserInfo)));
// add each user to the specified site group
foreach (SPUserInfo member in groupMembers)
{
site.SiteGroups[edSiteGroup.Text].AddUser(site.SiteUsers[member.LoginName]);
}
This depends upon the SharePoint groups exsiting at the site level (in the above code, the group name is taken from a form control: "edSiteGroup").
Hope this helps,
David. MembershipUser you create is not yet a sharepoint user, so you can't assign roles to it. Try the following:
Code SnippetSPWeb site = SPContext.Current.Site.RootWeb;
SPUser spUser = site.EnsureUser(username); //this creates an actual sharepoint user
//if (spUser == null) throw something to be sure;
SPRoleAssignment roleAssignment =
new SPRoleAssignment(spUser); //use another constructorI faced this problem when I needed to add new user to a default visitors group, and that helped. I can provide you with some additional code if you need.
Good luck!
- Alexander,
I have exactly same issue. I've configure my site as form-based authentication site. Now, I want to add users in a default visitor group upon their registration. Could you please shed some lights as to how to do so step-by-step? I've been looking for some guides for many days without such luck. If you're kind enough to send me some codes/instruction, my email address raekbarton@hotmail.com. Any help would be greatly appreciated.
Rae Rae,
As far it seems that you have already configured a membership provider for your sharepoint site, and you have forms authentication working.
If not, please read here - http://weblog.vb-tech.com/nick/archive/2006/06/14/1617.aspx
So, then you all need is to create a user and add it to a default group, that's say "VISITORS".
Code Snippet//1) Create membership user
MembershipUser membershipUser = Membership.CreateUser(login, password, email);
//now you have it
//2) Create sharepoint user
SPWeb spWeb = SPControl.GetContextWeb(HttpContext.Current);
//get your site instance
SPUser spUser = spWeb.EnsureUser(login);
//now you have sharepoint user
//3) Add sharepoint user to a desired group
SPGroup spGroup = spWeb.SiteGroups["VISITORS"];
//get your group
spGroup.AddUser(spUser);
//that should do the work
That's all! Of course some error-checking is nessesary.
If you have some questions, please write with some concrete questions.
- Hi Alexander,
I'm facing the same issue. My website has been configured as forms-based authentication website. By default, I'm not allowing anonymous access to my website. But I'll allow a visitor from internet can register his own accounts and put it into a specific group automatically.
Now there is no problems to create an asp.net user. But when I try to put this new user into a sp group, the web is redirected to the login page. This happens when it reaches the code spWeb.EnsureUser(login). I think there might be an authorization issue. I've been working on this for a whole week but no luck either. Can you give me some suggestions on that? Thanks. - Unless you want to mess with Impersonation context, you will not be able to do what you are looking to do. The web object is under the context of the current user (anonymous), so in effect, if the user does not have the appropriate set of rights, they will be prompted to log in as a user who does. Your web part / page might be able to call a web service with alternate credentials to perform the tasks you wish to do.
Try running this code with higher privileges:
Microsoft.SharePoint.
SPSecurity.RunWithElevatedPrivileges(delegate{
spWeb.EnsureUser(login);
});
You may need to add the following string to your web.config file.
<identity impersonate="true" />
Hope that will help you,
good luck!
Remember, if you are using FBA, to prefix the Membership Provider Name before the "username" - ex
string _usernameWithProvider = String.Format("{0}:{1}", System.Web.Security.Membership.Provider.Name, username);
SPRoleAssignment roleAssignment =
new SPRoleAssignment(_usernameWithProvider, email, username, "myNotes");
Also note that the LoginName and DisplayName are different due to the necc prefixing of the Provider.Name
Also, also note that you may need to have the AllowSafeUpdates=true on either Web, Site, or both (haven't tested this)
Also, also, also note <g> that the NTLM with throw an error on Provider.Name, so use for FBA
Also, also, also, also note (last one, I promise) that you should specify System.Web.Security.Membership.Provider, since MOSS has its own Membership.Provider which can cause confusion
good luck!
papabearNice post
Also for anyone who is having problems with EnsureUser, has to add one user to site by using sharepoint add user functionality and should check account name. Generally it is in the form of groupname:username, so instead of trying:
spWeb.EnsureUser(username);
Try:
spWeb.EnsureUser("whatevergroupnameitis:"+username);
That worked in my case.
Good luck.
Erinc Arikan
Hey zhijy
I m facing similar kind of issue.I am using Form authentication to access the site.
You have mentioned that an anonymous user can register himself and then put it into a specific group.Can you please explain the way this can be done??Can we do this in a single step(Registration and group allocation)??
Thanks,
Neeraj
- to solve this problem : The user does not exist or is not unique.
and u r using forms authentications , u can use this code to add the user ( after adding it in membership):
input : userName, fullName, groupName,email,website name
using
(SPSite site = new SPSite(webSite)){
using (SPWeb web = site.OpenWeb()){
userName =
"scemembershipsqlprovider:" + userName;web.SiteUsers.Add(userName, mail, fullName,
"Automatically Added User");web.Groups["GroupName"].AddUser(userName, mail, fullName,
"Automatically Added User");}
}
so u should add ur membership provider before the login name...
Hi to All,
I m too facing exactly the same problem and I tried all the posts on this subject in this thread with EXACTLY the same steps , but still its not doing the things with following observations..
1. FBA user is created by anonymous user.
2. But anonymous user is not able to add this newly created account to any SP groups and this i think is due to fact that anonymous user doesn't hv ant rights to add any user directly to any SharePoint Group.
So, CAN ANYONE PLZ TELL IF THIS REALLY POSSIBLE OR NOT , AND IF POSSIBLE PLZ POST WITH EXACT STEPS.
Thanks in Advance,
awadh
Hi Alexander ,
i tried exactly the same steps with proper FBA settings, still its not doing the things.
Can u plz help me to get out of this problem ?
- I suggest you add a asp.net role to the sharepoint group when the site is setup. At runtime, you can simply add membership users to this role when the user is registered. This is much easier to program and don't need elevated privileges.
the best solution is
step1. RunWithElevatedPrivileges when ensureuser and adduser
step2. you should
a. You can update data for a single site or site collection by adding a page directive and FormDigest control to the page that makes the request.
b. Include a FormDigest control within the form as follows:
任国强Hi All,
I have a publishing site in sharepoint. i configured forms authentication for this site using asp.net web application. it wass successfull. i added these roles in the SharePoint Groups and gave appropriate Approve permission to the group. i created different users and assigned them the roles in asp.net web application. Now if i edit a page and start a workflow(serial workflow) as an administrative user and then i login as a normal user under the role which i have added in the sharepoint group, i am not able to see the "Approve" "Reject" and "View Page Tasks" on the home page. I tried by configuring the Forms Authentication for SSP and MySite also which i think not needed in this scenario.
If i add a user uder this role in the sharePoint Group then he is able to see all the Approve , Reject and 'View page taks" buttons but not when i add a role in the SharePoint Group. Please give the solution immediately. its very urgent. Any help regarding this will be highly appreciated.
i checked the WorkFlow task list permissions and permissions of the workflow. but i am not able to find the solution after so many attempts. please suggest appropriate ideas and solutions...
Thanks and Regards
Amreesh Sharma- Hi All,
I have a sharepoint site which is form authenticated. In my 'Create User' form I would like to add user to membership database, if it is successful I add that user to user information list.
When I was trying with the code above it did not work for me. at last I could able to get the solution.
The username in the membership database is not a AliasName in sharepoint.
The login name in sharepoint is 'name of membershipProvider':'Username.
For example if
User Name is : Sridebi.Korada
MembershipProviderName is : MembershipProvider
then the login Name for sharepoint will be : MembershipProvider:Sridebi.Korada
The code snippet for adding new user will be as follows
SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
SPGroup addUserGroup = web.Groups["ReadiNow Members"];
addUserGroup.AddUser(
string.Format("MembershipProvider:Sridebi.Korada","SKorada.abc.com", "Sridebi.Korada", "");
Try this code if you fail to add user to UI list in sharepoint site if it is form authenticated.
Thanks and Regards
Sridebi Korada- Navržen jako odpověďSridebi Korada 25. května 2009 5:47

