Sample code to add an existing Security role to all System Users:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Configuration;
using System.Linq;
using Xrm;
public static bool assignSecurityRoleToAllUsers(string roleName)
{
_logger.Info("Starting assignment of '{0}' SecurityRole to all users ...", roleName);
// Initiate CRM-connection
var conn = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString);
var service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
var context = new OrganizationServiceContext(service);
var users = (from u in context.CreateQuery<SystemUser>()
where u.IsDisabled.Equals(false)
select u).ToList();
// Find the role.
QueryExpression query = new QueryExpression
{
EntityName = Role.EntityLogicalName,
ColumnSet = new ColumnSet("roleid", "businessunitid"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "name",
Operator = ConditionOperator.Equal,
Values = { roleName }
}
}
}
};
// Get the role.
EntityCollection roles = service.RetrieveMultiple(query);
if (roles.Entities.Count > 0)
{
foreach (var user in users)
{
Role salesRole = null;
foreach (Entity role in roles.Entities)
{
Role r = (Role)role;
if (r != null && r.BusinessUnitId != null)
{
if (r.BusinessUnitId.Equals(user.BusinessUnitId))
{
salesRole = r;
}
}
}
if (salesRole == null)
continue;
Guid roleId = salesRole.Id;
try
{
Guid userId = user.SystemUserId ?? Guid.Empty;
if (roleId != Guid.Empty && userId != Guid.Empty)
{
// Associate the user with the role.
service.Associate(
"systemuser",
userId,
new Relationship("systemuserroles_association"),
new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, roleId) });
_logger.Info("OK - {0} ({1})", user.FullName, user.Id);
}
}
catch (Exception e)
{
if (!e.Message.Contains("Microsoft managed component"))
{
_logger.Info("Skipped - {0} ({1}) - Microsoft managed", user.FullName, user.Id);
}
else if (e.Message.Contains("Cannot insert duplicate key"))
{
_logger.Info("Skipped - {0} ({1}) - Is already assigned", user.FullName, user.Id);
}
else
{
_logger.Error("Error - {0} ({1}): {2}", user.FullName, user.Id, e.Message);
}
}
}
}
_logger.Info("Ending assignment of '{0}' SecurityRole to all users ...", roleName);
return true;
}
Observe: The above code requires a generated XRM early bound entity file for the Role and SystemUser entities.