CRM 2011 – Add Users to a Team via the SDK

Roshan Mehta, 26 May 2013

In this post, we will see how we can use C# and the Microsoft Dynamics CRM 2011 SDK to programmatically add Users to a Team. This is useful in situations where there are special conditions in your organisation that define which Team (or Teams) a particular User can belong to. The SDK makes it easy via the AddMembersTeamRequest in the Microsoft.Crm.Sdk.Messages namespace.

 CRM 2011 Add Users to a Team via the SDK

 CRM 2011 Add Users to a Team via the SDK

The AddMembersTeamRequest defines two important properties – MemberIds and TeamId. The MemberIds parameter is a GUID array of all of the GUIDS related to the Users we want to add to the Team. The TeamId refers to the GUID of the Team we want to add the members to.

Code snippet:

Guid aucklandTeamId = GetAucklandTeamId();
Guid[] aucklandUserIds = GetAucklandUserIds();

if (aucklandTeamId != default(Guid) && aucklandUserIds != null)
{
    _sdk.Execute(new AddMembersTeamRequest 
    {
        TeamId = aucklandTeamId,
        MemberIds = aucklandUserIds
    });
}

Supporting Methods:

private static Guid GetAucklandTeamId()
{
    Guid teamId = default(Guid);

    QueryExpression query = new QueryExpression { EntityName = "team" };
    query.Criteria.AddCondition("name", ConditionOperator.Equal, "Auckland");

    EntityCollection results = _sdk.RetrieveMultiple(query);
    if (results.Entities.Count > 0)
    {
        teamId = results[0].Id;
    }
    return teamId;
}

private static Guid[] GetAucklandUserIds()
{
    Guid[] userIds = null;

    QueryExpression query = new QueryExpression { EntityName = "systemuser" };
    query.Criteria.AddCondition("address1_city", ConditionOperator.Equal, "Auckland");

    EntityCollection results = _sdk.RetrieveMultiple(query);
    userIds = results.Entities.Select(e => e.Id).ToArray();

    return userIds;
}

In my next post, we will see how we can programmatically add items to a queue.