Assign a Custom Role to a User
This sample assigns a custom security role to a user.
Class Reference
Schema Reference
- role.xsd
Example
[C#]
public void AssignCustomRole()
{
// strServer should be set with the name of the platform Web server
string strServer = "MyServerName";
// strVirtualDirectory should be set with the name of the Microsoft CRM
// virtual directory on the platform Web server
string strVirtualDirectory = "mscrmservices";
// Create the URL to the SRF files for platform objects
string strDir = "https://" + strServer + "/" + strVirtualDirectory + "/";
// BizUser proxy object
Microsoft.CRM.Proxy.BizUser oUser = new Microsoft.CRM.Proxy.BizUser ();
oUser.Credentials = System.Net.CredentialCache.DefaultCredentials;
oUser.Url = strDir + "BizUser.srf";
// SecRole proxy object
Microsoft.CRM.Proxy.SecRole oSecRole = new Microsoft.CRM.Proxy.SecRole ();
oSecRole.Credentials = System.Net.CredentialCache.DefaultCredentials;
oSecRole.Url = strDir + "SecRole.srf";
// Declare the caller
Microsoft.CRM.Proxy.CUserAuth oUserAuth = null;
string strSecRoleXML = "";
string strErrorMsg = "";
// Array for role IDs and for privilege IDs
string [] strRoleIds = new string[1];
Microsoft.CRM.Proxy.CRolePrivilege [] strPrivilegeIds = new Microsoft.CRM.Proxy.CRolePrivilege[2];
try
{
// Get the UserAuth of the currently logged on user
oUserAuth = oUser.WhoAmI();
// Build a role XML string in the business unit of the caller
// Name of the role should be unique in an organization
strSecRoleXML = "<role>" +
"<name>Sales Assistant</name>" +
"<businessunitid>" + oUserAuth.MerchantId + "</businessunitid>" +
"</role>";
// Create a custom role
strRoleIds[0] = oSecRole.Create(oUserAuth, strSecRoleXML);
// Get a couple of privileges to be added to this role
strPrivilegeIds[0] = new Microsoft.CRM.Proxy.CRolePrivilege();
strPrivilegeIds[1] = new Microsoft.CRM.Proxy.CRolePrivilege();
// Users can create accounts (BASIC)
strPrivilegeIds[0].PrivilegeId = "{D26FE964-230B-42DD-AD93-5CC879DE411E}";
strPrivilegeIds[0].Depth = Microsoft.CRM.Proxy.PRIVILEGE_DEPTH.BASIC;
// Users can read accounts (BASIC)
strPrivilegeIds[1].PrivilegeId = "{886B280C-6396-4D56-A0A3-2C1B0A50CEB0}";
strPrivilegeIds[1].Depth = Microsoft.CRM.Proxy.PRIVILEGE_DEPTH.BASIC;
// Add a couple of privileges to the role
oSecRole.AddPrivileges(oUserAuth, strRoleIds[0], strPrivilegeIds);
// Assign the custom role to the caller user
oSecRole.AssignUserRoles(oUserAuth, oUserAuth.UserId, strRoleIds);
}
catch(System.Web.Services.Protocols.SoapException err)
{
// Process the platform error here
strErrorMsg = ("ErrorMessage: " + err.Message + " " + err.Detail.OuterXml + " Source: " + err.Source );
}
catch(Exception err)
{
// Process other errors here
strErrorMsg = ("ErrorMessage: " + err.Message + "Source: " + err.Source );
}
}