Friday, February 22, 2013

Get System Users From Specific Team

Today I had a very simple request, which is to get System Users in a specific team. Since it was a very simple task I just Google and try to find a sample. I was amazed as there was no such exaample in the Net. So I had to write my own. Once it is done, I just thought to share it as it might be useful.
Here is the code.

1. First example is to get the System Users in a Team
2. Second example is to get System Users as ActivityParty that you might need to link with an Activity.

public List<SystemUser> GetTeamUsers(string teamName)
{
    return (from user in Context.CreateQuery<SystemUser>()
            join teamMembership in Context.CreateQuery<TeamMembership>() 
                 on user.SystemUserId.Value equals teamMembership.SystemUserId
            join team in Context.CreateQuery<Team>() on teamMembership.TeamId.Value equals team.TeamId.Value
            where team.Name == teamName
            select user
            ).ToList();
}

public List<ActivityParty> GetTeamUsersAsActivityParty(string teamName)
{
    return (from user in Context.CreateQuery<SystemUser>()
            join teamMembership in Context.CreateQuery<TeamMembership>() 
                 on user.SystemUserId.Value equals teamMembership.SystemUserId
            join team in Context.CreateQuery<Team>() on teamMembership.TeamId.Value equals team.TeamId.Value
            where team.Name == teamName
            select new ActivityParty
            {
                PartyId = new EntityReference { LogicalName = user.LogicalName, Id = user.SystemUserId.Value }
            }).ToList();
}