Tuesday 28 May 2013

How to find groups & get users from SharePoint People Picker programmatically ?



string[] strEmployee = splstCurItem["peoplepicker"].ToString().Split(';','#');                               
List<string> lstUID = new List<string>();
List<string> lstUserID = new List<string>();
for (int i = 2; i < strEmployee.Length; i += 4)
{
lstUID.Clear();
Contact c = Contact.FromName(strEmployee[i-2], myWeb);
if (c != null)
{
string strUserType = c.PrincipalType.ToString();
if (strUserType == "SecurityGroup")
{
lstUID = GetUsersFromADGroup(strEmployee[i-2]);
lstUserID.AddRange(lstUID);
}
else if (strUserType == "SharePointGroup")
{
lstUID = GetUsersFromSharePointGroup(strEmployee[i-2]);
lstUserID.AddRange(lstUID);
}
else if (strUserType == "User")
{
lstUID.Add(strEmployee[i]);
lstUserID.AddRange(lstUID);
}
}
}

//Method1
List<int> GetUsersFromADGroup(string GroupName)
        {
            List<int> lstUsrID = new List<int>();
            SPSite MySite = new SPSite(workflowProperties.WebUrl);
            SPWeb Myweb = MySite.OpenWeb();
            Contact c = Contact.FromName(GroupName, Myweb);
            if (c != null)
            {
                Contact[] contacts = new Contact[] { c };
                bool reachedMaxCount = false;
                contacts = Contact.ExpandGroups(Myweb, contacts, 100, out reachedMaxCount);

                foreach (Contact user in contacts)
                {
                    string strID = user.PrincipalID.ToString();
                    string strName = user.DisplayName;
                    SPUser spUser = Myweb.EnsureUser(strName);
                    lstUsrID.Add(spUser.ID);
                }
            }
            return lstUsrID;
        }
 //Method2
  List<int> GetUsersFromSharePointGroup(string GroupName)
        {
            List<int> lstUsrID = new List<int>();
            SPSite MySite = new SPSite(workflowProperties.WebUrl);
            SPWeb Myweb = MySite.OpenWeb();
            SPGroup spGroup = Myweb.Groups[GroupName];
            foreach (SPUser spUser in spGroup.Users)
            {
                lstUsrID.Add(spUser.ID);
            }
            return lstUsrID;
        }


No comments:

Post a Comment