En caso de querer añadir un usuario(SPUser) a MOSS desde código fuente, en vez desde SharePoint de la manera habitual, el sistema nos ofrece la siguiente función:
SPWeb.Users.Add(Login, Mail, Name, Notes)
Esta función que aparentemente nos tendría que facilitar el trabajo y permitirnos pasar este escollo sin la menor dilación, producirá el siguiente error en el sistema:
Operation is not valid due to the current state of the object
Esto se debe a que susodicha función no nos sirve para la creación de usuarios, así pues el sistema de creación será un poco más complejo de lo deseado.
La forma de crear un usuario es la que sigue:
1.- Es necesario utilizar la libreria:
using Microsoft.SharePoint;
2.- Antes de crear el usuario es interesante asegurarse de que no exista ya en el entorno, esto lo podemos realizar mediante la siguiente función:
private SPUser GetSPUser(string strLoginName, string strSiteURL)
{
SPUser spReturn = null;
SPSite spSite = null;
SPWeb spWeb = null;
try
{
// Open the SharePoint site
spSite = new SPSite(strSiteURL);
spWeb = spSite.OpenWeb;
// Another way without paramether: strSiteURL
//spSite = new SPSite(SPContext.Current.Site.ID);
//spWeb = spSite.OpenWeb(SPContext.Current.Web.ID);
// Check to see if user exists
spReturn = spWeb.AllUsers[txbUser.Text];
}
catch
{
}
finally
{
spWeb.Close();
spSite.Close();
}
return spReturn;
}
3.- En caso de que no exista el usuario (comprobado con la función anterior) podemos crear el usuario con la siguiente función:
private SPUser CreateUser(string strLoginName, string strEMail, string strName, string strNotes, string strSiteURL)
{
SPUser spReturn = null;
SPSite spSite = null;
SPWeb spWeb = null;
try
{
//Open the SharePoint site
spSite = new SPSite(strSiteURL);
spWeb = spSite.OpenWeb();
//Assign role and add user to site
SPRoleAssignment spRoleAssignment = new SPRoleAssignment(strLoginName, strEMail, strName, strNotes);
//Using Contribute, might need high access - The Contribute option depends on installation language from MOSS
SPRoleDefinition spSPRoleDefinition = spWeb.RoleDefinitions["Contribute"];
spRoleAssignment.RoleDefinitionBindings.Add(spSPRoleDefinition);
spWeb.RoleAssignments.Add(spRoleAssignment);
//Update site
spWeb.Update();
spReturn = spWeb.AllUsers[strLoginName];
}
catch(Exception)
{
}
finally
{
spWeb.Close();
spSite.Close();
}
return spReturn;
}
Así pues de esta manera se podrá crear/localizar un usuario dentro de SharePoint desde código.