bittusarkar
bittusarkar

Reputation: 6357

Adding user to SharePoint group using web services in C# is not working for me

I have a SharePoint 2010 site hosted on a remote server and I want to add users to one of the SharePoint groups automatically from another machine using C#. I've tried using web services as mentioned all over the internet as under:

class Program
{
    static void Main(string[] args)
    {
        SPUserGroupRef.UserGroup usrGrpService = new SPUserGroupRef.UserGroup();
        System.Net.NetworkCredential netCred = new System.Net.NetworkCredential(<my username>, <my password>, <my domain name>);
        usrGrpService.Credentials = netCred;
        usrGrpService.AddUserToGroup(<group name>, <new user full name>, <domain\new user name>, <new user email address>, <notes>);
    }
}

Note: 1. SPUserGroupRef is the web service reference to http:///_vti_bin/usergroup.asmx 2. All the angle-bracketed entities mentioned above in the code are strings.

1st 3 lines of code inside Main execute fine but the 4th line fails with "Exception of type Microsoft.SharePoint.SoapServer.SoapServerException was thrown". I am pretty new to SharePoint so may be I am missing something here. Can someone help me figure out how to get over this issue or may be suggest another approach that might work (but remember my SharePoint site is hosted on a remote server, not on my local machine.

Upvotes: 2

Views: 3635

Answers (1)

Manish
Manish

Reputation: 90

why dont you use Sharepoint 2010 client object model,I have not tested below code, but it should work.

namespace ClientObjectModel 
{ 
class Program 
{ 
static void Main(string[] args) 
{ 
// Add a new user to a particular group 

string siteURL = "http://serverName:1111/sites/SPSiteDataQuery/"; 
ClientContext context = new ClientContext(siteURL); 
GroupCollection groupColl = context.Web.SiteGroups; 
Group group = groupColl.GetById(7); 
UserCreationInformation userCreationInfo = new UserCreationInformation(); 
userCreationInfo.Email = ""; 
userCreationInfo.LoginName = @"DomainName\UserName"; 
userCreationInfo.Title = "SharePoint Developer"; 
User user = group.Users.Add(userCreationInfo); 
context.ExecuteQuery(); 
} 
} 
}

Microsoft.SharePoint and Microsoft.SharePoint.Client let me know if it works?

Upvotes: 1

Related Questions