Hi,
You can use below code to check if user exist based on Domain Name.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<entity name="systemuser">
<attribute name="fullname" />
<attribute name="businessunitid" />
<attribute name="title" />
<attribute name="address1_telephone1" />
<attribute name="positionid" />
<attribute name="systemuserid" />
<order attribute="fullname" descending="false" />
<filter type="and">
<condition attribute="domainname" operator="eq" value="USER DOMAIN NAME" />
</filter>
</entity>
</fetch>
Use below code to associate role
// Find the role.
QueryExpression query = new QueryExpression
{
EntityName = Role.EntityLogicalName,
ColumnSet = new ColumnSet("roleid"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "name",
Operator = ConditionOperator.Equal,
Values = {_givenRole}
}
}
}
};
// Get the role.
EntityCollection roles = _serviceProxy.RetrieveMultiple(query);
if (roles.Entities.Count > 0)
{
Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity<Role>();
Console.WriteLine("Role {0} is retrieved for the role assignment.", _givenRole);
_roleId = salesRole.Id;
// Associate the user with the role.
if (_roleId != Guid.Empty && _userId != Guid.Empty)
{
_serviceProxy.Associate(
"systemuser",
_userId,
new Relationship("systemuserroles_association"),
new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) });
Console.WriteLine("Role is associated with the user.");
}
Use below code to create user in CRM Onpremise
Entity user=new Entity(""systemuser);
user["domainname"]=DOMAIN NAME;
//map mandatory fields as per your data
service.Create(user);
If found helpful, Please mark my answer verified.