public static readonly string entityName = "systemuser";
public Guid userId = Guid.Empty;
/// <summary>
/// 创建用户
/// </summary>
public void Create(IOrganizationService service)
{
Entity en = new Entity() { LogicalName = entityName };
en["domainname"] = "test";
en["fullname"] = "測试";
userId = service.Create(en);
}
/// <summary>
/// 启用和停用用户
/// </summary>
/// <param name="service"></param>
public void UpdateUserState(IOrganizationService service)
{
//启用用户
UpdateState(entityName, userId, 0, -1, service);
//停用用户
UpdateState(entityName, userId, -1, -1, service);
}
/// <summary>
/// 加入和移除安全角色
/// </summary>
/// <param name="service">服务</param>
/// <param name="roleId">安全角色</param>
public void AddAndRemoveRole(IOrganizationService service,Guid roleId)
{
//加入安全角色
AddConnection(service, "systemuserroles_association", new EntityReference() { LogicalName = "role", Id = roleId });
//删除安全角色
RemoveConnection(service, "systemuserroles_association", new EntityReference() { LogicalName = "role", Id = roleId });
}
private void UpdateState(string enName, Guid id, int state, int status, IOrganizationService service)
{
SetStateRequest setState = new SetStateRequest()
{
EntityMoniker = new EntityReference()
{
Id = id,
LogicalName = enName
},
State = new OptionSetValue(state),
Status = new OptionSetValue(status)
};
service.Execute(setState);
}
public void AddConnection(IOrganizationService service, string name, params EntityReference[] array)
{
Relationship ship = new Relationship(name);
AssociateRequest request = new AssociateRequest();
request.Relationship = ship;
request.Target = new EntityReference() { LogicalName = entityName, Id = userId };
request.RelatedEntities = new EntityReferenceCollection();
request.RelatedEntities.AddRange(array);
service.Execute(request);
}
public void RemoveConnection(IOrganizationService service, string name, params EntityReference[] array)
{
Relationship ship = new Relationship(name);
DisassociateRequest request = new DisassociateRequest();
request.Relationship = ship;
request.Target = new EntityReference() { LogicalName = entityName, Id = userId };
request.RelatedEntities = new EntityReferenceCollection();
request.RelatedEntities.AddRange(array);
service.Execute(request);
}