It is quite easy to add groups, add contacts, and enumerate both contacts and groups using UCMA’s ContactGroupServices extension. 

To enumerate groups, you can use the following.

ICollection<Group> groups = endpoint.ContactGroupServices.EndGetAllGroups(endpoint.ContactGroupServices.BeginGetAllGroups(null, null));

To add a group, the following will work.

endpoint.ContactGroupServices.EndAddGroup(endpoint.ContactGroupServices.BeginAddGroup(“mygroupname”, null, null, null));

And to add a contact in this new group you may use the following.

ContactAddOptions contactOptions = new ContactAddOptions();
contactOptions.GroupIds.Add(groupId);

// Add the contact
endpoint.ContactGroupServices.EndAddContact(endpoint.ContactGroupServices.BeginAddContact(contactUri, contactOptions, null, null));

Where it becomes slightly confusing is, how do you obtain the groupId?  At first glance, you may think the answer is to add the group, call GetAllGroups to retrieve the groups, find your new group, and use its groupId.  Unfortunately, that is not the way to do it.

The problem is you really do not know when the group will actually be added, and until it is actually added the group will not have a groupId – so GetAllGroups will not return it.

The answer is therefore to subscribe for notifications and wait for the group to be created.  Here is some sample code demonstrating this.

int groupId = 0;

AutoResetEvent foundGroupIdEvent = new AutoResetEvent(false);
EventHandler<ContactGroupNotificationEventArgs> contactNotificationHandler =
    delegate(object sender, ContactGroupNotificationEventArgs e)
    {
        foreach (NotificationItem<Group> groupNotification in e.Groups)
        {
            if (String.Equals(“mygroup”, groupNotification.Item.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                groupId = groupNotification.Item.GroupId;
                foundGroupIdEvent.Set();
            }
        }
    };

endpoint.ContactGroupServices.NotificationReceived += contactNotificationHandler;
endpoint.ContactGroupServices.EndAddGroup(endpoint.ContactGroupServices.BeginAddGroup("mygroup", null, null, null));
foundGroupIdEvent.WaitOne(WaitTimeForGroupIdInSeconds * 1000, true);
endpoint.ContactGroupServices.NotificationReceived -= contactNotificationHandler;