MSDN > 論壇首頁 > SharePoint - Development and Programming > add users to sharepoint programmatically
發問發問
 

已答覆add users to sharepoint programmatically

  • 2007年6月19日 下午 12:47Thomas Moellnitz 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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 Snippet

          MembershipCreateStatus 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

     





               


解答

  • 2007年7月2日 下午 02:47Alexander Demura 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     已答覆

    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.

所有回覆

  • 2007年6月19日 下午 07:52James Peckham 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    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.

  • 2007年6月24日 下午 04:33Curtis Ruppe _MicroStaff IT_ 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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.
  • 2007年6月25日 上午 04:14DavidCrabbe 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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.



  • 2007年6月27日 下午 05:30Alexander Demura 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    MembershipUser you create is not yet a sharepoint user, so you can't assign roles to it. Try the following:

     

    Code Snippet

    SPWeb 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 constructor

      

    I 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!

  • 2007年6月29日 下午 05:10rae barton 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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
  • 2007年7月2日 下午 02:47Alexander Demura 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     已答覆

    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.

  • 2007年7月4日 下午 02:51zhljy711 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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.

  • 2007年7月4日 下午 03:12Curtis Ruppe _MicroStaff IT_ 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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.
  • 2007年7月5日 下午 02:18Alexander Demura 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    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!

  • 2008年2月25日 下午 07:48myfriedmind 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    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!
    papabear
  • 2008年3月13日 下午 03:27Erinc Arikan 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    Nice 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

  • 2008年3月26日 上午 11:26neeraja_godrej.com 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    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

     

     

     

  • 2008年4月15日 上午 11:07khaled abrass 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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...

     

     

  • 2008年5月2日 下午 12:16awadh 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    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

     

     

     

     

  • 2008年5月2日 下午 12:19awadh 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

     

    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 ?

  • 2008年12月20日 下午 03:46xor_freecity 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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.
  • 2009年2月3日 下午 01:14任国强 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    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:


    任国强
  • 2009年2月3日 下午 01:16任国强 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
  • 2009年2月27日 上午 07:29Amreesh Sharma 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

    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

  • 2009年5月25日 上午 05:43Sridebi Korada 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     提議的解答
    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