I had a requirement to create a web service which would be used to add user to a SharePoint group. The code for it
[WebMethod]
public string AddSharePointUser(string username,string password, string email){
string statusInfo = “”;
try{
string SharePointUrl = ConfigurationManager.AppSettings[“SharePointUrl”].ToString();
string SharePointGroup = ConfigurationManager.AppSettings[“SharePointGroup”].ToString();
SPSecurity.RunWithElevatedPrivileges(delegate(){
using (SPSite oSiteCollection = new
SPSite(SharePointUrl)){
oSiteCollection.AllowUnsafeUpdates = true;
using (SPWeb oWebsite = oSiteCollection.OpenWeb()){
oWebsite.AllowUnsafeUpdates = true;
SPUser spUser = oWebsite.EnsureUser(username);
SPGroup spGroup = oWebsite.SiteGroups[SharePointGroup];
spGroup.AddUser(spUser);
oWebsite.AllowUnsafeUpdates = false;
}
oSiteCollection.AllowUnsafeUpdates = false;
}});
statusInfo = “User Created Successfully”;
}
else{
statusInfo = “User Already Exists”;
}}
catch (Exception ex){
statusInfo = ex.Message;
}
return statusInfo;
}
To run the web service successfully, we need to set the identity of application pool of the web service to SharePoint Administrator account.
Hope it helps.
Discover more from Nishant Rana's Weblog
Subscribe to get the latest posts sent to your email.
