SharePoint People Search

Searching of all user profiles in SharePoint 2013 by WCF CSOM service.

In SharePoint for searching users by CSOM can be performed by writing the below code by creating a WCF service.

Note: 

1. 'MethodResponse' is a custom object to store list of string
2. 'token' is a unique string to verify stored UserCredentials

public MethodResponse<List<string>> GetPeoples(string text, string token)
        {
            MethodResponse<List<string>> response = new MethodResponse<List<string>>();
            List<string> lstMetadata = new List<string>();
            UserCredential userCredential = new UserCredential();
           
            try
            {
                userCredential = VerifyToken(token);
                if (userCredential != null)
                {
                    _ctx = GetClientContext(userCredential);
                    if (_ctx != null)
                    {

                        KeywordQuery keywordQuery = new KeywordQuery(_ctx);
                        keywordQuery.QueryText = text;
//                        keywordQuery.HiddenConstraints = "scope:\"People\"";                        
                        keywordQuery.TrimDuplicates = true;                        
                        keywordQuery.SourceId = Guid.Parse("B09A7990-05EA-4AF9-81EF-EDFAB16C4E31");
                        SearchExecutor searchExecutor = new SearchExecutor(_ctx);
                        ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
                        _ctx.ExecuteQuery();

                        if (results.Value[0].RowCount > 0)
                        {
                            foreach (var resultRow in results.Value[0].ResultRows)
                            {
                                lstMetadata.Add(resultRow["PreferredName"].ToString());
                            }
                            response.ErrorCode = "200";
                            response.ErrorDescription = "No error.";
                            response.Response = lstMetadata;

                        }
                        else
                        {
                            response.ErrorCode = "400";
                            response.ErrorDescription = "No users found.";
                            response.Response = lstMetadata;
                        }
                    }
                }
            }
            catch (Exception ex)
            {        
                response.ErrorCode = "400";
                response.ErrorDescription = ex.Message;
                response.Response = null;
            }
            finally
            {
                _ctx.Dispose();
            }
            return response;
        }

Comments

Popular posts from this blog

Office365