CRM 2011 – Add Users to a Team with C#

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.

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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s