Wednesday, August 17, 2011

Looping the people picker values

Recently I encountered the strange error while retrieving the all user from the
People picker control using SPQuery.
My datatable comes with Site user id and Name.As I wanted to assign these user to a
specific task in workflow.
while using these first user comes without site user id and the remaining were perfect as i expected.
I should admit,I tried many times but could not figure it out for my first user comes along with site id.Finally I made it to work.

Firstly queried the all user from the people picker control with certain condition using CAML.
 private string GetApproverList()
        {
            using (SPWeb web = workflowProperties.Web)
            {
                string appList = "";
                SPList docApproverList = web.Lists["DocApprovers"];
                
                string DocType = workflowProperties.Item["DocumentType"].ToString();               
                SPQuery q = new SPQuery();
                
                //q.Query = q.Query = "" + DocType + "";
                q.Query = "" + DocType + "";
                DataTable dt = docApproverList.GetItems(q).GetDataTable();
                foreach (DataRow row in dt.Rows)
                {
                    appList = appList + row["Approvers"].ToString()+",";
                }
                return appList.TrimEnd(',');
            }
        }


Secondly split this string into array by passing the comma sperator and '#' separator.
 string DocListUser = GetApproverList();
            string[] uids = DocListUser.Split(';', '#');
            for (int a = 0; a < uids.Length; a++)
            {
                if (uids[a].ToString() != "" && !CheckNumber(uids[a].ToString()))
                {
                    uidsList.Add(uids[a]);
                }

            }
Now I have final string array which comes with "",user id and display name.
public bool CheckNumber(string value)
        {

            int number1;
            return int.TryParse(value, out number1);
        }
I used array list to add each items in above string.Then I omit the "" string and numbers in the array.
 foreach (var userList in uidsList)
            {
                SPUser user = SPContext.Current.Web.EnsureUser(userList.ToString());
                assignees.Add(user.LoginName);
            }