接触moss已经1年多了,但是一直都没有研究过本身的用户部分,前段时间做了几个实验,下面是代码:
/// <summary>
/// 把域用户添加到MOSS
/// </summary>
/// <param name="UserName">域用户名domain\user</param>
/// <returns></returns>
public bool AddToMoss(DomainUser domainusers)
{
string _Domain = new OperateDomain().Domain;
string siteurl = "";
DomainUser duser = domainusers;
string loginName = _Domain + "\\" + duser.UserId;
try
{
SPSecurity.CodeToRunElevated elevatedGetSitesAndGroups = new SPSecurity.CodeToRunElevated(delegate()
{
siteurl = ConfigurationManager.AppSettings["SiteAddress"].ToString();
SPSite site = new SPSite(@siteurl);
SPWeb web = site.OpenWeb();
SPUserCollection susers = web.SiteUsers;
web.AllowUnsafeUpdates = true;
if (!ExistMossUser(site, loginName))
{
susers.Add(loginName, duser.Email, duser.UserName, "");
if (!web.HasUniqueRoleAssignments)
{
web.BreakRoleInheritance(true);
}
//给用户赋予权限
SPRoleDefinitionCollection roles = web.RoleDefinitions;
SPRoleDefinition role = roles["读取"];
SPUser user = susers[loginName];
SPRoleAssignment raUser = new SPRoleAssignment(user);
raUser.RoleDefinitionBindings.Add(role);
web.RoleAssignments.Add(raUser);
//LogManage.SaveInfo("OK");
}
});
SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups);
return true;
}
catch (Exception ex)
{
LogManage.SaveInfo(ex.ToString());
return false;
}
}
/// <summary>
/// 从MOSS中删除用户
/// </summary>
/// <param name="domainusers"></param>
/// <returns></returns>
public bool DelUserFromMoss(DomainUser domainusers)
{
string _Domain = new OperateDomain().Domain;
string siteurl = "";
DomainUser duser = domainusers;
string loginName = _Domain + "\\" + duser.UserId;
try
{
SPSecurity.CodeToRunElevated elevatedGetSitesAndGroups = new SPSecurity.CodeToRunElevated(delegate()
{
siteurl = ConfigurationManager.AppSettings["SiteAddress"].ToString();
SPSite site = new SPSite(@siteurl);
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPUserCollection susers = web.SiteUsers;
if (ExistMossUser(site, loginName))
{
susers.Remove(loginName);
}
});
SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups);
return true;
}
catch (Exception ex)
{
LogManage.SaveInfo(ex.ToString());
return false;
}
}
/// <summary>
/// 判断网站中是否存在该用户
/// </summary>
/// <param name="site"></param>
/// <param name="userName"></param>
/// <returns></returns>
public bool ExistMossUser(SPSite site, string userName)
{
try
{
SPWeb web = site.OpenWeb();
SPUserCollection susers = web.SiteUsers;
bool f = false;
foreach (SPUser us in susers)
{
if (userName == us.LoginName)
{
f = true;
break;
}
}
//LogManage.SaveInfo(f.ToString());
return f;
}
catch (Exception ex)
{
LogManage.SaveInfo(ex.ToString());
return true;
}
//return false;
}