MOSS: Add user to site through code (programmatically)

We can add users to a SharePoint site using object model.  

 

One possible way: 

 

SPRoleAssignment MyRoleAssign = new SPRoleAssignment(”domain/alias”, “email address”, “User Name”, “Description”);

 

SPRoleDefinition MyRoleDef = newSubWeb.RoleDefinitions[“Contribute”];

MyRoleAssign.RoleDefinitionBindings.Add(MyRoleDef);

site.RoleAssignments.Add(MyRoleAssign);

 

Second is:

 

SPGroup AddUserGroup = site.Groups[“Group name”];

AddUserGroup.AddUser(”domain/alias”, “email address”, “User Name”, “Description”);

 

To add bulk of users in one go, following code is preferred:

 

SPUserInfo[] AddUsers = new SPUserInfo[1];

 

AddUsers[0].Email = “email address”;

AddUsers[0].LoginName = “domain\login”;

AddUsers[0].Name = “name”;

AddUsers[0].Notes = “notes”;

 

site.Roles[“Contributor”].Users.AddCollection(AddUsers);

Advertisements

57 Comments »

  1. hyze said

    Hai FarhanFaiz,

    Can I know how to use that object model and code for the test. Actually i always found the sample code like this but dont know where to start and how. Can you help me how to do that in visual studio..

    Appreciate your help

    fyi: i’m not .net programmer but want to know the result of some code above.

  2. farhanfaiz said

    hyze,

    I will try to explain the whole process step-by-step:

    1- Open VS and select “Console Application” as new project.

    2- Add reference of “SharePoint”. For details check this link (https://farhanfaiz.wordpress.com/2007/12/31/creating-adding-an-event-handler/ )

    3- Completed Code is as under:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using Microsoft.SharePoint;

    namespace AddUsers
    {
    class AddUserClass
    {
    static void Main(string[] args)
    {

    SPSite siteCollection = new SPSite(“Site URL”);
    SPWeb site = siteCollection.OpenWeb();

    SPGroup AddUserGroup = site.Groups[“Group Name”];
    AddUserGroup.AddUser(“domain/alias”, “email address”, “Name”, “Description”);

    OR

    SPRoleAssignment MyRoleAssign = new SPRoleAssignment(“domain/alias”, “email address”, “Name”, “Description”);

    SPRoleDefinition MyRoleDef = newSubWeb.RoleDefinitions[“Contribute”];
    MyRoleAssign.RoleDefinitionBindings.Add(MyRoleDef);
    site.RoleAssignments.Add(MyRoleAssign);

    site.Dispose();
    siteCollection.Dispose();
    }
    }
    }

    4- Run the code and check it in the site.

    In case you require more assistance of any of the above steps, do let me know.

  3. hyze said

    thanks bro for the explanation. it’s work and easy. things is, i need to start coding. really appreciate your help

  4. Rudy said

    Hai FarhanFaiz,
    Thanks for the code, what if we have to create a Group through code other than adding users to an already existing Group?
    Pls explain

  5. farhanfaiz said

    Rudy,

    Try the following line, hopefully it will work:

    site.SiteGroups.Add(….)

  6. john said

    Thank you for your site. I have found here much useful information…

  7. Melissa said

    I thank the Lord for giving us the gift of brilliant preachers!o

  8. Dan said

    s prazdnikov vas

  9. Melissa said

    Looking for information and found it at this great site…e

  10. chanaka said

    i wnt to get data from the SPSITE, but when i trying to access in progarmaticaly it gives “the system administrator may need to add a new request URL mapping to the intended application”, can you help me please!!!

  11. farhanfaiz said

    Chanka,

    Any details of the specific data that you want to extract?

    Regards

  12. Trent said

    Looked everywhere for this code great post! Have a question though…

    When i add the user i then need to update other attributes associated with that user.

    this is my code
    Dim AddUserGroup As SPGroup = newSubWeb.Groups(“Users”)

    AddUserGroup.AddUser(Account, Email, loginName, Description)

    dim newUser as spuser = newSubWeb.AllUsers(loginName)

    ‘update details of spuser
    updateUserDetailsSP(newUser)
    ——-
    I get an error back to say ‘User cannot be found.’ but the user is being added. I think it may be trying to find the user before the whole process has been completed.

    Unfortunately the add method doesn’t return the user eg.
    dim newUser as spuser = AddUserGroup.AddUser(Account, Email, loginName, Description)

    Do you know if there is another way?

    Thanks again

  13. farhanfaiz said

    Trent,

    I am a bit lost. What are the attributes that you want to update? Can you specify anyone.

    Regards,

    Farhan

  14. Trent said

    All data is stored for each user in a list called ‘User Information List’ on the root site. You can setup extra metadata on that list like any other list.

    Say i had this

    dim newUser as spuser = newSubWeb.AllUsers(loginName)
    dim userID as string=newUser.Id

    UserID is now the row in which i can update that User Information List with any data i want eg. Job Title, Phone, Branch etc.

  15. farhanfaiz said

    Trent,

    What I can say is that try to generate list of all the users in the site and see if code can fetch the recently added user or not.

    do let me know the result.

  16. Trent said

    It will find the user within the full list but there is about a 30 second delay after first inserting the user. Just thought you might have known a way to return the user at point of inserting the new user. Thanks anyways.

  17. farhanfaiz said

    Trent,

    It may be that you have tried the following work around already but that worked for me in case of list update.

    1 – Try different vesion of update if exist.

    2- Use AllowUnsafeUpdate

    Regards,

  18. Kalpesh said

    Hi Farhan,

    Thanks for sharing your fruitful knowledge. I got much from this article.

    Actually i am a .net devloper and recently started sharepoint. I have some confusions and I find you as right person to get solution.

    [1] Please let me know that, how can i give the link from the sharepoint site to add the user which are not still added in the windows authenication too. Or it is compulsory to add windows authenticated users.

    [2] In some example on other site (http://www.fpweb.net/sharepoint-tutorials/AddNewUser.asp) I found that in the site stting> permission> add user link they have one extra button ADD USER along with check user and add windows user image. When in my site I have only two images to add user from windows authenticated users and check them. Please let me know how can we do that.

    [3] You have explained to create the console application and added users to the site. Do we need to run this app manualy to add new user or we can reference this app in the sharepoint site and run it from there.

    I would appreciate any assistance/comments/suggestion.

    Thanks in Adv.

    Regards,
    Kalpesh.

  19. Farhan Faiz said

    Kalpesh,

    Let me answer your queries one by one:

    [1] Please let me know that, how can i give the link from the sharepoint site to add the user which are not still added in the windows authenication too. Or it is compulsory to add windows authenticated users.

    First thing is that, no it is not compulsory to add windows authenticated users. Second thing is that as per my understanding, you are trying to add user which are not on company domain. Like, abc@companyname.com is a user on company doamin and can access through windows authentication.Now, the problem is to add a user which is not on comapny domain like xyz@other-company.com. You will find many options but what we have implemented is that created a user group on sevrer machine running SharePoint and add user in that group creating specific login and password. Also, we add the user to the SharePoint site for which access is required by specifying login. We give that login and password to the user and user can access SharePoint site.

    [2] In some example on other site (http://www.fpweb.net/sharepoint-tutorials/AddNewUser.asp) I found that in the site stting> permission> add user link they have one extra button ADD USER along with check user and add windows user image. When in my site I have only two images to add user from windows authenticated users and check them. Please let me know how can we do that.

    I have no idea about the create button and user with gmail addess. Hope to find out more 🙂

    [3] You have explained to create the console application and added users to the site. Do we need to run this app manualy to add new user or we can reference this app in the sharepoint site and run it from there.

    I have created this apllication keeping in mind to run manualy to add new user.

    Do let me know in case you require further assistance in this regard.

    Regards,

    Farhan

  20. Kalpesh said

    Hi Farhan,

    Thanks for your kind support.

    Right now I am adding users from the admin side using SSP. to do this the user must have a windows user (As per my knowledge). My aim is to add users directly from the site and it may or may not be a windows domain user.

    Right now i dont have Active directory service set up on my machine. So let me investigate further for this.

    By the way thanks again for your reply. and I will contact u in future for any assistant if needed.

    Best Regards,
    Kalpesh

  21. Farhan Faiz said

    Kalpesh,

    Sure. you are welcome.

    Regards,

    Farhan

  22. husain said

    Hi Farhan,
    Can we fetch the currently logged in user GROUP at runtime. Actually i want to make a dynamic menu which will be loaded dynamically depending on the logged in user permissions.
    Do you have any ideas on how we can implement it.

    Regards
    Husain

  23. Farhan Faiz said

    MOSS 2007 shows status of the online users but I am not sure how this is done. Also, I am not sure about the accuracy of the status.

  24. kalpesh said

    Hi Farhan.

    I want your assistance for the following problem.

    –> I had developed one sharepoint application on one server. Now our system admin had mooved the sharepoint server to another machine.

    I had taken a back up for the folder of my application from the inetpub\wwroot\wss\virtualdirectories.

    Now can you eplain me how to onfigure this application on the new server and do i need to copy any other files or any thing to successfuly configure it on other machine.

    so can you have any idea about this issue.

    Any assistance would be appreciable.

    Thanks.

  25. Farhan Faiz said

    Kalpesh,

    I will like to deploy the solution from point zero. Do let me know in case you require further assistance in this regrd.

    Regards,
    Farhan

  26. Murtuza Husain said

    Hi kalpesh,
    Here are the steps-
    1. create a new site.
    2. restore the site from your backup file. (using stsadm)
    3. copy any configuration settings that you made in old webconfig to existing one.
    4. install any 3rd party tool if you are using in old version and configure it here also.
    5. if you made any changes in layout folder of previous server (added custom images, JS, CSS) you need to make it here also.
    6. check and configure the services in central admin (like smtp, search etc).

    Hope this list helps
    Murtuza Husain

  27. Subita said

    Hello,

    I created a web part that would give users read permissions using your code above. But I am running into an issue. The code is runnign without errors, but it is not adding the user to the site. Can you please take a look at my procedure and see if I am missing anything:

    Public Sub makeUserSiteAdmin()
    Dim siteCollection As New SPSite(“http://devsite.com/”)
    Dim devSite As SPWeb = siteCollection.OpenWeb()
    ‘Dim allowUnsafeUpdate As Boolean = devSite.AllowUnsafeUpdates
    Dim MyRoleAssign As New SPRoleAssignment(“NA\user”, “user_last@devsite.com”, “User Last”, “Desc”)
    Dim MyRoleDef As SPRoleDefinition = devSite.RoleDefinitions(“Read”)

    ‘devSite.AllowUnsafeUpdates = True
    MyRoleAssign.RoleDefinitionBindings.Add(MyRoleDef)
    devSite.RoleAssignments.Add(MyRoleAssign)

    ‘devSite.AllowUnsafeUpdates = allowUnsafeUpdate

    devSite.Dispose()
    siteCollection.Dispose()

    End Sub

  28. kalpesh said

    Hi,

    I had installed sharepoint server on two machines. But on one machine I get the option for KPI and Reports creation and on other machine I am not getting the report center and KPI section to create the reports and KPIs. I think the steps followed to install the sharepoint server was same for both machines.

    So do I need to activate any service, other setting or to check that the specific steps are followed when installing.

    I would appreciate any assistance in this issue. Please let me know if you have check list(which steps to check and follow) for installing sharepoint perfectly.

    Best Regards,
    Kalpesh.

  29. kalpesh said

    Hi,

    Regarding the previous report center issue.

    I had also checked that the create report templates are installed in the template folder in c:\[sharepoint template features path].

    I hav also tried to upload that template and try to create the enterprice template site but still there is no option for report center in enterprice teplate section.

    Thanks.

  30. Farhan Faiz said

    Kalpesh,

    What was the template you selected for top-level site of “other nmachine”.

    Also, try to create site collection from Central Admin.

    Do let me know.

    Regards,

  31. kalpesh said

    Hi Farhan,

    Thanks for your suggestion.

    I had talked with my system admin and they inform me that the version which we have installed in the new server is trial version which does not have enterprise section so it does not give this option.

    I regret for my lack of information.

    The site template I was selecting ‘publishing – Collaboration portal’ and also I was creating it from central admin.

    Thanks,

    Regards,
    kalpesh.

  32. janardhan Chippa said

    i am new to sharepoint and i am working on programatically create and Posts the blog. can you direct in right path how can i access posts and comments of sharepoint blog using object model in my web application.
    appriciate for explaining with code.
    Thanks
    janardhan

  33. confikarthik said

    Hi,

    Here i want to restrict ‘contribute user’ to use options like “save as” & “Export” from ‘File menu’ when ‘contribute users’ open a document from document library.

    Eg: when user opens document [eg: ABC.doc] from document library,
    ms-word should not allow them to make “save as” and “export” it.

    Is it possible to block that two option from file menu,
    Can any one helps on this.

    Thanks,
    Karthik.

  34. Farhan Faiz said

    I don’t think that this is possible as .doc files uses MS Word to open. One way is to use Rights Management Services.

  35. karthik said

    Hi,

    Thanks for the reply,

    Here also i am using RMS ,Using RMS, i am not able to disable “Save As”.
    But i could disable other options like save, forward etc..
    So only i come back to MOSS.

  36. Ginni said

    How to deploy the above program on a remote SharePoint Server??? Actually i am using this code on my local machine and need to deploy that on remote SharePoint Server.

  37. Farhan Faiz said

    As per my understanding, RMS blocks “Save As” option as well. Set file as read only.

  38. Farhan Faiz said

    Ginni,

    Try following resource:

    http://go.microsoft.com/fwlink/?LinkId=110087

    Look for “solution”.

  39. Ginni said

    Is there any other way?? I mean normally i deploy things by copying the dll into GAC on SharePoint Server through VPN. But in this case, this method is not working. Do i need to change my web.config?

  40. Farhan Faiz said

    Ginni,

    To be on safeside, i recomend adding solution approach.

    Regards,

  41. Manoj Tripathi said

    Hi Farhan Faiz ,
    i want to populate a dropdown list with sub-sites as per the permission of the user i.e. if a user open his home site then he can view all the allowed sub-sites into his drop down.
    Can you please give me the code in which i will send a user name & it returns the sub-sites url in which the users has been added.

    Thanks in Advance

  42. Farhan Faiz said

    Manoj,

    What type of authentication you are using? NTLM or other?

  43. Manoj said

    Hi Farhan,

    I have default site with NTLM authentication & extended it for internet. The extended site has FBA. FBA is working fine & implemented similar functionality like Web Site Administration Tool in MOSS site. Now i can create and manage users & roles from the extended site.
    created membership as AspNetSqlProvider_membership & rolemanager as AspNetSqlProvider_role.

    i am able the populate the dropdown list with sub-sites as per the permission of the user but has another problem.

    i am created users & roles. Added the users into the respected roles and added the roles into Sharepoint groups.
    Like sharepoint site: zccp, user: kate.jog ,role: zccp-admin and share point group: zccp-owners (has full control).
    kate.jog has zccp-admin role. Added zccp-admin role into zccp-owners group of zccp site.

    in this way i don’t want to add users directely into sharepoint site group, instead added the users first into roles & then added the roles into the share point group. everything is working but problem is that if i want to set target audience , i m not getting the role name.
    if i set target audience as the sharepoint group then it is working for the users directly added into the group. But not working for the users belonging to the roles.
    If you can solve the problem , it will be great help to me.

    Thanks

  44. sandrar said

    Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

  45. SPdev said

    Also, I do I change SharePoint login programmatically? Thanks!

  46. Naresh said

    Hi Subitha,

    Have you crated the webpart to assign the permissions successfully, if so can you please share the code.
    thanks.

  47. Tusar said

    Hi Farhan,
    Thanks for the code.
    I have check boxes for diff groups in a customised webpart. The user need to select the checkboxes for the respective groups he want to be added.
    I want to write code in (OK) button click event, which can add the user to respective selected groups.

    Regards,
    Tusar

  48. Tusar said

    On above post. Groups are sharepoint user groups.

    Regards,
    Tusar

  49. Uma said

    The following line results in an exception

    “you cannot grant a user a permission level that is not attached to a web”

    MyRoleAssign.RoleDefinitionBindings.Add(MyRoleDef);

    Note that my user belongs to an AD group that is a member of a sharepoint group

  50. srinivas said

    hi,
    i used the above code but when i open people and group list the added users are not shown.but when i query using object model it is displaying the users. can u tell me how to rectify the problem?

    • Farhan Faiz said

      Does users has access or not?

  51. srinivas said

    using object model i need to perform the following task
    1. i have to join two lists ?
    2.i have to make the list column/field to accept unique values only
    can u guide me for the above two

    • Farhan Faiz said

      1 – please use SPQuery ato get data from two lists
      2- you use event handler to make sure unique value entered.

      let me know if further assistance is desired

  52. tfslov said

    Hi,
    How do I add users/groups in a site definition VS project?
    I want to create a site from a template with predefined users

  53. aru said

    i want to add user programmetically how can i do this

    • Farhan Faiz said

      Code is available in the above post. Let me know if further assistance is desired.

  54. Vysakh said

    Hai Farhan,

    Thanks for ur support.
    Now I’m suffering from an issue related to Group.
    Can i create a usergroup specific to a site (among many other sites) within a sitecollection..?

    When i tried to create a group within a site, it appears on all the sites within the sitecollection.
    Can u please help on this…

RSS feed for comments on this post · TrackBack URI

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: