Fing system user by name in MSCRM4

This is a code sample to find and return a system user by running a query over the name:
// find system user by name
private systemuser GetUser(string name)
{
QueryByAttribute query = new QueryByAttribute();
ColumnSet column = new ColumnSet();
column.EntityName = EntityName.systemuser.ToString();
//column.Attributes = new String[] { "name", "systemuserid" };
query.EntityName = EntityName.systemuser.ToString();

systemuser sysUser = new systemuser();
return sysUser; //returns system user
}


Get all roles assigned to a user in MSCRM 4.0

Hi this is a small function to get all the roles assigned to a particular user in Dynamics CRM 4.0 using the CRM SDK.
// Get all roles  assigned to a user 
private BusinessEntityCollection CurrentUserRoles(ICrmService service, Guid userId)
{
var queryForUserRole = new QueryExpression { 
EntityName = "role", 
ColumnSet = new AllColumns()
};

// Create the link entity from role to systemuserroles.
var linkEntityRole = new LinkEntity{
LinkFromEntityName = "role",
LinkFromAttributeName = "roleid",
LinkToEntityName = "systemuserroles",
LinkToAttributeName = "roleid"
};

var linkEntityUserRoles = new LinkEntity{
LinkFromEntityName = "systemuserroles",
LinkFromAttributeName = "systemuserid",
LinkToEntityName = "systemuser",
LinkToAttributeName = "systemuserid"
};

// Create the condition to test the user ID.
var conditionForUserRole = new ConditionExpression{
AttributeName = "systemuserid",
Operator = ConditionOperator.Equal,
Values = new object[] { userId }
};

// Add the condition to the link entity.
linkEntityUserRoles.LinkCriteria = new FilterExpression();
linkEntityUserRoles.LinkCriteria.Conditions.Add(conditionForUserRole);

// Add the from and to links to the query.
linkEntityRole.LinkEntities.Add(linkEntityUserRoles);
queryForUserRole.LinkEntities.Add(linkEntityRole);

// Retrieve the roles and write each one to the console.
BusinessEntityCollection currentUserRoles = service.RetrieveMultiple(queryForUserRole);
return currentUserRoles;
}


Grant/Revoke Security principles in CRM 4

Here are some list of function that works together to share/unshare and assign security priviledges over an entity.

/* Grant/Revoke Security principles in CRM 4 */

// Get Target owner dynamic
private TargetOwnedDynamic GetTargetOwned(string entityName, Guid entityGuid)
{
return new TargetOwnedDynamic()
{
EntityId = entityGuid,
EntityName = entityName
};
}

//Retrieve shared principle access
private PrincipalAccess[] GetPrincipals(TargetOwnedDynamic target)
{
//Describe the target for entity instances that are owned by a security principal.
RetrieveSharedPrincipalsAndAccessRequest retrieve = new RetrieveSharedPrincipalsAndAccessRequest();
retrieve.Target = target;
RetrieveSharedPrincipalsAndAccessResponse retrieved = (RetrieveSharedPrincipalsAndAccessResponse)_crmService.Execute(retrieve);
return retrieved.PrincipalAccesses;
}

//Retrieve team shared principle access
private PrincipalAccess[] GetTeamPrincipals(TargetOwnedDynamic target)
{
//Describe the target for entity instances that are owned by a security principal.
RetrieveSharedPrincipalsAndAccessRequest retrieve = new RetrieveSharedPrincipalsAndAccessRequest();
retrieve.Target = target;
RetrieveSharedPrincipalsAndAccessResponse retrieved = (RetrieveSharedPrincipalsAndAccessResponse)_crmService.Execute(retrieve);
return retrieved.PrincipalAccesses.TakeWhile(tm=>tm.Principal.Type==SecurityPrincipalType.Team).ToArray();
}

// Remove principle access over target
private void RemovePrincipals(TargetOwnedDynamic target, PrincipalAccess[] principals)
{
RevokeAccessRequest request = new RevokeAccessRequest();
request.Target = target;
foreach (PrincipalAccess principal in principals)
{ 
request.Revokee = principal.Principal;
RevokeAccessResponse response = (RevokeAccessResponse)_crmService.Execute(request);
}
}

// Removes all team access over target
private bool RevokeAllTeamAccess(TargetOwnedDynamic target)
{
PrincipalAccess[] allPrinciples = GetPrincipals(target);
PrincipalAccess[] teamPrincipals =
allPrinciples.Where(tp => tp.Principal.Type.Equals(SecurityPrincipalType.Team)).Select(tp => tp).ToArray();
RemovePrincipals(target, teamPrincipals);
return true;
}

// Revoke unknown team access 
private bool RevokeUnknownTeamAccess(TargetOwnedDynamic target)
{
Guid unknownTeamGuid = GetTeamGuid(_configUnknownSalesTeam);

PrincipalAccess unknownTeamPrincipal = GetPrincipals(target).Where(
up => up.Principal.PrincipalId.Equals(unknownTeamGuid) && 
up.Principal.Type.Equals(SecurityPrincipalType.Team))
.Select(up => up).SingleOrDefault();

if (unknownTeamPrincipal != null)
{
RevokeAccessRequest request = new RevokeAccessRequest();
request.Target = target;
request.Revokee = unknownTeamPrincipal.Principal;
RevokeAccessResponse response = (RevokeAccessResponse)_crmService.Execute(request);
return true;
}
else
return false;
}

// Get Team GUID
private Guid GetTeamGuid(string teamName)
{
QueryExpression query = new QueryExpression("team")
{
ColumnSet = new AllColumns(),
Criteria = new FilterExpression {FilterOperator = LogicalOperator.And}
};

ConditionExpression condition1 = new ConditionExpression
{
AttributeName = "name",
Operator = ConditionOperator.Equal,
Values = new object[] {teamName}
};
query.Criteria.Conditions.Add(condition1);

var teamRequest = new RetrieveMultipleRequest { Query = query, ReturnDynamicEntities = true };
var teamResponse = (RetrieveMultipleResponse)_crmService.Execute(teamRequest);
if (teamResponse.BusinessEntityCollection.BusinessEntities.Count == 1)
{
DynamicEntity teamRetrived = (DynamicEntity)teamResponse.BusinessEntityCollection.BusinessEntities[0];
//Key teamKey = ((Key)teamRetrived.Properties["teamid"]).Value;
return ((Key)teamRetrived.Properties["teamid"]).Value;
}
else
{
return Guid.Empty;
}
} 

// Share with unknown team
private bool UnknownTeamShare(TargetOwnedDynamic target)
{
bool alreadySharedToUnknown = false;
Guid unknownTeamGuid = GetTeamGuid(_configUnknownSalesTeam);

//PrincipalAccess[] allPrinciples = GetPrincipals(target);
PrincipalAccess[] teamPrincipals =
GetPrincipals(target).Where(tp => tp.Principal.Type.Equals(SecurityPrincipalType.Team)).Select(tp => tp).ToArray();
alreadySharedToUnknown = teamPrincipals.Any(p => p.Principal.PrincipalId.Equals(unknownTeamGuid));

if (target != null && alreadySharedToUnknown == false)
{
SecurityPrincipal principal = new SecurityPrincipal();
principal.Type = SecurityPrincipalType.Team;
principal.PrincipalId = GetTeamGuid(_configUnknownSalesTeam);

UInt32 mask = 0;
if (_configUnknownSalesTeamPermission.Count >= 1)
mask = _configUnknownSalesTeamPermission.Aggregate(mask, (current, item) => current | UInt32.Parse(item.Value));

//Grant Access
GrantAccessRequest request = new GrantAccessRequest();
request.Target = target;

request.PrincipalAccess = new PrincipalAccess();
request.PrincipalAccess.AccessMask = (AccessRights)mask;
request.PrincipalAccess.Principal = principal;
GrantAccessResponse response = (GrantAccessResponse)_crmService.Execute(request);
Log("The "+target.EntityName + " {" + target.EntityId +"} is shared with the sales team " + _configUnknownSalesTeam,false);
return true;
}
else
{
return false;
}
}