private void QuerySearchEngineRecursive(ClientContext ctx, string kql, Action <IDictionary <string, object> > procesResultRow, int startRow) { Logger.Verbose($"Fetching results in range {startRow} to {startRow + BatchSize + 1}"); var executor = new SearchExecutor(ctx); var results = executor.ExecuteQuery( new KeywordQuery(ctx) { QueryText = kql, StartRow = startRow, RowLimit = BatchSize, // beware that the TrimDuplicates setting is true by default and that its behavior may be somewhat // counter-intuitive as it removes search results which are similar to a some degree. This implies // search will treat some results as similar even though they're not, leaving out distinct results. // http://sharepoint.stackexchange.com/questions/14460/sharepoint-2010-search-when-is-a-document-a-duplicate TrimDuplicates = false }); ctx.ExecuteQuery(); var rows = results.Value[0]; Logger.Verbose($"Result contains {rows.RowCount} rows"); rows.ResultRows.ToList().ForEach(procesResultRow); if (rows.RowCount > 0) { QuerySearchEngineRecursive(ctx, kql, procesResultRow, startRow + BatchSize); } }
private List <string> GetUserLoginNamesFromSearch() { Logger?.Debug($"[O365] Getting user list from search"); try { List <string> loginNames = new List <string>(); var ctx = GetSpoClientContextForSite(SpoSite.RootSite); SearchExecutor searchExecutor = new SearchExecutor(ctx); int currentPage = 0; int totalRows = -1; int startRow = 1; int rowLimit = 10; do { startRow = (rowLimit * currentPage) + 1; // http://www.techmikael.com/2015/01/how-to-query-using-result-source-name.html KeywordQuery qry = new KeywordQuery(ctx); qry.Properties["SourceName"] = "Local People Results"; qry.Properties["SourceLevel"] = "SSA"; qry.QueryText = "*"; qry.RowLimit = rowLimit; qry.StartRow = startRow; ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(qry); ctx.ExecuteQueryWithIncrementalRetry(SpoRetries, SpoBackoff, Logger); var resultTable = results.Value[0]; if (currentPage == 0) { totalRows = resultTable.TotalRows; } foreach (var resultRow in resultTable.ResultRows) { loginNames.Add(resultRow["AccountName"].ToString()); } currentPage++; } while (startRow + rowLimit < totalRows); return(loginNames); } catch (MaximumRetryAttemptedException ex) { // Exception handling for the Maximum Retry Attempted Logger?.Error($"[O365] Max retries / throttle for SPO reached getting site user list. Message {ex.Message}"); throw new O365Exception($"Max retries / throttle for SPO reached. Message {ex.Message}", ex); } catch (Exception ex) { Logger?.Error($"[O365] Problem getting root site user list. Message {ex.Message}"); throw new O365Exception($"Problem getting root site user list. Message {ex.Message}", ex); } }
protected void cmdSearch_Click(object sender, EventArgs e) { string contextToken = SPAppToken.Value; string hostWeb = Page.Request["SPHostUrl"]; ClientContext ctx = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority); KeywordQuery keywordQuery = new KeywordQuery(ctx); keywordQuery.QueryText = txtSearchText.Text; SearchExecutor searchExecutor = new SearchExecutor(ctx); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); ctx.ExecuteQuery(); DataTable dt = new DataTable(); dt.Columns.Add("Title"); dt.Columns.Add("Author"); dt.Columns.Add("Last Update"); dt.Columns.Add("URL"); if (results.Value.Count > 0) { foreach (Dictionary <String, Object> resultRow in results.Value[0].ResultRows) { dt.Rows.Add(resultRow["Title"], resultRow["Author"], resultRow["Write"], resultRow["Path"]); } } grd.DataSource = dt; grd.DataBind(); }
private static ClientResult <ResultTableCollection> SearchContentLog(ContentLogRequest request, int i, string eventDate, ClientContext clientContext, KeywordQuery keywordQuery) { keywordQuery.QueryText = "(Site:" + request.SiteUrl + ") AND ((ContentTypeId:" + request.ContentTypeId + "*))"; StringCollection selectProperties = keywordQuery.SelectProperties; keywordQuery.RowLimit = 500; keywordQuery.RowsPerPage = 500; keywordQuery.Timeout = 10000; keywordQuery.StartRow = i; keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("FileName"); keywordQuery.SelectProperties.Add("ListItemID"); keywordQuery.SelectProperties.Add("Author"); keywordQuery.SelectProperties.Add("DocId"); keywordQuery.SelectProperties.Add("ComplianceTag"); keywordQuery.SelectProperties.Add("ComplianceAssetId"); keywordQuery.SelectProperties.Add("Path"); keywordQuery.SelectProperties.Add("FileType"); keywordQuery.SelectProperties.Add("ModifiedOWSDATE"); keywordQuery.SelectProperties.Add("ListUrl"); keywordQuery.SelectProperties.Add("ListId"); keywordQuery.SelectProperties.Add("SPWebUrl"); keywordQuery.SelectProperties.Add("DefaultEncodingURL"); keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Descending); keywordQuery.TrimDuplicates = false; SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); clientContext.ExecuteQuery(); return(results); }
private void RunSearch(string searchText) { SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); Uri hostWeb = spContext.SPHostUrl; using (var context = spContext.CreateUserClientContextForSPHost()) { //Get current user User currentUser = context.Web.CurrentUser; context.Load(currentUser); context.ExecuteQuery(); //Get current user's tasks KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = searchText; var searchExecutor = new SearchExecutor(context); ClientResult<ResultTableCollection> resultsCollection = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); //Bind them to the grid IEnumerable<IDictionary<string, object>> results = resultsCollection.Value[0].ResultRows; List<SearchResult> tasks = new List<SearchResult>(); foreach (var result in results) { SearchResult searchResult = new SearchResult(); searchResult.Title = result["Title"].ToString(); searchResult.Path = result["Path"].ToString(); tasks.Add(searchResult); } SearchResultsView.DataSource = tasks; SearchResultsView.DataBind(); } }
/// <summary> /// /// </summary> /// <param name="cc">ClientContext object of an arbitrary site collection accessible by the defined enumeration username and password</param> /// <param name="keywordQueryValue">Query to execute</param> /// <param name="sites">List of found site collections</param> /// <param name="keywordQuery">KeywordQuery instance that will perform the actual queries</param> /// <param name="startRow">Row as of which we want to see the results</param> /// <returns>Total result rows of the query</returns> private static int ProcessQuery(ClientRuntimeContext cc, string keywordQueryValue, List <string> sites, KeywordQuery keywordQuery, int startRow) { int totalRows = 0; keywordQuery.QueryText = keywordQueryValue; keywordQuery.RowLimit = 500; keywordQuery.StartRow = startRow; keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(cc); ClientResult <ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); cc.ExecuteQueryRetry(); if (results != null) { if (results.Value[0].RowCount > 0) { totalRows = results.Value[0].TotalRows; foreach (var row in results.Value[0].ResultRows) { if (row["SPSiteUrl"] != null) { sites.Add(row["SPSiteUrl"].ToString()); } } } } return(totalRows); }
private void RunSearch(string searchText) { SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); Uri hostWeb = spContext.SPHostUrl; using (var context = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity)) { //Get current user User currentUser = context.Web.CurrentUser; context.Load(currentUser); context.ExecuteQuery(); //Get current user's tasks KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = searchText; var searchExecutor = new SearchExecutor(context); ClientResult <ResultTableCollection> resultsCollection = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); //Bind them to the grid IEnumerable <IDictionary <string, object> > results = resultsCollection.Value[0].ResultRows; List <Task> tasks = new List <Task>(); foreach (var result in results) { Task task = new Task(); task.Title = result["Title"].ToString(); task.Path = result["Path"].ToString(); tasks.Add(task); } SearchResultsView.DataSource = tasks; SearchResultsView.DataBind(); } }
public List <Event> GetEvents() { List <Event> events; using (new SPMonitoredScope("Boxing Events Search Retrieval")) { KeywordQuery query = new KeywordQuery(SPContext.Current.Site); query.SelectProperties.AddRange(new[] { "Title", "EventDate", "Path" }); query.QueryText = "ContentType:\"CT-Event\""; var searchExecutor = new SearchExecutor(); ResultTableCollection results = searchExecutor.ExecuteQuery(query); ResultTable resultTable = results.Filter("TableType", KnownTableTypes.RelevantResults).Single(); events = (from DataRow row in resultTable.ResultRows select new Event( (string)row["Title"], (DateTime)row["EventDate"], (string)row["Path"]) ).OrderByDescending(ev => ev.EventDate) .ThenBy(ev => ev.Title) .ToList(); } return(events); }
/// <summary> /// Executes a keyword query against Office search service. /// </summary> /// <param name="keywordQuery">A keyword query instance.</param> /// <param name="refiners">A list of <see cref="SearchRefiner"/> objects where refinement results are populated.</param> /// <returns>Results returned from Office search service.</returns> public static ResultTable ExecuteQuery(KeywordQuery keywordQuery, SearchRefiner[] refiners) { CommonHelper.ConfirmNotNull(keywordQuery, "keywordQuery"); LastQueryText = keywordQuery.QueryText; if (refiners != null) { keywordQuery.Refiners = String.Join(",", refiners.Select(v => v.PropertyName).ToArray()); keywordQuery.RefinementFilters.AddRange(refiners.Where(v => v.RefinementToken != null).Select(v => v.RefinementToken).ToArray()); } SearchExecutor executor = new SearchExecutor(); ResultTableCollection queryResults = executor.ExecuteQuery(keywordQuery); ResultTable relevantResults = queryResults.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault(); if (relevantResults == null) { throw new Exception("Search executor did not return result table of type RelevantResults"); } if (refiners != null) { ResultTable refinementResults = queryResults.Filter("TableType", KnownTableTypes.RefinementResults).FirstOrDefault(); if (refinementResults == null) { throw new Exception("Search executor did not return result table of type RefinementResults"); } foreach (SearchRefiner refiner in refiners) { foreach (DataRow row in refinementResults.Table.Rows.OfType <DataRow>().Where(v => refiner.PropertyName.Equals(v["RefinerName"]))) { refiner.AddRefinement((string)row["RefinementName"], (string)row["RefinementToken"], (int)row["RefinementCount"]); } } } return(relevantResults); }
protected override void ProcessRecord() { base.ProcessRecord(); try { KeywordQuery query = new KeywordQuery(this.Site.Read()); query.QueryText = this.Query; query.SelectProperties.AddRange(this.Select); SearchExecutor executor = new SearchExecutor(); ResultTableCollection result = executor.ExecuteQuery(query); ResultTable resultTable = result.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault(); if (resultTable == null) { throw new Exception("Search executor did not return result table of type RelevantResults"); } DataTable dataTable = new DataTable(); dataTable.Load(resultTable); foreach (DataRow row in dataTable.Rows) { PSObject obj = new PSObject(); foreach (DataColumn column in dataTable.Columns) { obj.Members.Add(new PSNoteProperty(column.Caption, row[column])); } WriteObject(obj); } } catch (Exception ex) { ThrowTerminatingError(ex, ErrorCategory.NotSpecified); } }
private void RunSearch(string searchText) { SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); Uri hostWeb = spContext.SPHostUrl; using (var context = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity)) { //Get current user User currentUser = context.Web.CurrentUser; context.Load(currentUser); context.ExecuteQuery(); //Get current user's tasks KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = searchText; var searchExecutor = new SearchExecutor(context); ClientResult<ResultTableCollection> resultsCollection = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); //Bind them to the grid IEnumerable<IDictionary<string, object>> results = resultsCollection.Value[0].ResultRows; List<Task> tasks = new List<Task>(); foreach (var result in results) { Task task = new Task(); task.Title = result["Title"].ToString(); task.Path = result["Path"].ToString(); tasks.Add(task); } SearchResultsView.DataSource = tasks; SearchResultsView.DataBind(); } }
private void SelectSharePointSite_Load( object sender, EventArgs e ) { if ( _ctx == null ) { throw new ArgumentException( "You must set the SharePoint RootSite Url before opening this form." ); } KeywordQuery kwq = new KeywordQuery( _ctx ) { QueryText = "contentclass =\"STS_Web\" OR contentclass=\"STS_Site\"" }; SearchExecutor seExecute = new SearchExecutor( _ctx ); var results = seExecute.ExecuteQuery( kwq ); _ctx.ExecuteQuery(); lstSharePointSites.DisplayMember = "SiteName"; lstSharePointSites.ValueMember = "Path"; lstSharePointSites.DataSource = ( from r in results.Value[ 0 ].ResultRows where !r[ "Author" ].ToString().Equals( "System Account" ) && !string.IsNullOrEmpty( r[ "Author" ].ToString() ) && !r[ "Path" ].ToString().Contains( "-my" ) select new { SiteName = r[ "Title" ] + " -|- " + r[ "Author" ], Path = r[ "Path" ] } ).ToArray(); this.Closed += ( s, args ) => { _ctx.Dispose(); }; }
private void RunSearch(string searchText) { SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); Uri hostWeb = spContext.SPHostUrl; using (var context = spContext.CreateUserClientContextForSPHost()) { //Get current user User currentUser = context.Web.CurrentUser; context.Load(currentUser); context.ExecuteQuery(); //Get current user's tasks KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = searchText; var searchExecutor = new SearchExecutor(context); ClientResult <ResultTableCollection> resultsCollection = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); //Bind them to the grid IEnumerable <IDictionary <string, object> > results = resultsCollection.Value[0].ResultRows; List <SearchResult> tasks = new List <SearchResult>(); foreach (var result in results) { SearchResult searchResult = new SearchResult(); searchResult.Title = result["Title"].ToString(); searchResult.Path = result["Path"].ToString(); tasks.Add(searchResult); } SearchResultsView.DataSource = tasks; SearchResultsView.DataBind(); } }
/// <summary> /// Query SharePoint Search and fetch information about each file (URL and name). /// </summary> /// <param name="client">Existing SharePoint ClientContext</param> /// <param name="folderUrl">Full server folder URL</param> /// <returns>List of files information</returns> static async Task <IEnumerable <SPFileInfo> > GetFilesFromFolderAsync(ClientContext client, string folderUrl) { KeywordQuery query = new KeywordQuery(client) { QueryText = $"IsContainer=false Path:\"{folderUrl}\"", RowLimit = 500 }; SearchExecutor searchExecutor = new SearchExecutor(client); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(query); await client.ExecuteQueryAsync(); var relevantResults = results.Value.Where(x => x.TableType == "RelevantResults").FirstOrDefault(); if (relevantResults == null) { return(Array.Empty <SPFileInfo>()); } var files = new List <SPFileInfo>(); foreach (IDictionary <string, object> item in relevantResults.ResultRows) { var fileKey = item.Where(x => x.Key == "Path").FirstOrDefault(); Uri filePath = new Uri(fileKey.Value.ToString()); files.Add(new SPFileInfo() { ServerRelativeUrl = filePath.PathAndQuery, FileName = filePath.PathAndQuery.Substring(filePath.PathAndQuery.LastIndexOf("/") + 1) }); } return(files); }
private void QuerySearchEngineRecursive(ClientContext ctx, string kql, Action<IDictionary<string, object>> procesResultRow, int startRow) { Logger.Verbose($"Fetching results in range {startRow} to {startRow + BatchSize + 1}"); var executor = new SearchExecutor(ctx); var results = executor.ExecuteQuery( new KeywordQuery(ctx) { QueryText = kql, StartRow = startRow, RowLimit = BatchSize, // beware that the TrimDuplicates setting is true by default and that its behavior may be somewhat // counter-intuitive as it removes search results which are similar to a some degree. This implies // search will treat some results as similar even though they're not, leaving out distinct results. // http://sharepoint.stackexchange.com/questions/14460/sharepoint-2010-search-when-is-a-document-a-duplicate TrimDuplicates = false }); ctx.ExecuteQuery(); var rows = results.Value[0]; Logger.Verbose($"Result contains {rows.RowCount} rows"); rows.ResultRows.ToList().ForEach(procesResultRow); if (rows.RowCount > 0) { QuerySearchEngineRecursive(ctx, kql, procesResultRow, startRow + BatchSize); } }
private static string[] GetActorIds(ClientContext clientContext, string[] siteMembersEmails) { StringBuilder searchQueryText = new StringBuilder(); foreach (string userEmail in siteMembersEmails) { if (searchQueryText.Length > 0) { searchQueryText.Append(" OR "); } searchQueryText.AppendFormat("UserName:{0}", userEmail); } KeywordQuery searchQuery = new KeywordQuery(clientContext); searchQuery.QueryText = searchQueryText.ToString(); searchQuery.SelectProperties.Add("DocId"); searchQuery.SourceId = new Guid("b09a7990-05ea-4af9-81ef-edfab16c4e31"); searchQuery.RowLimit = 100; SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(searchQuery); clientContext.ExecuteQuery(); List<string> actorIds = new List<string>(results.Value[0].ResultRows.Count()); foreach (var row in results.Value[0].ResultRows) { actorIds.Add(row["DocId"].ToString()); } return actorIds.ToArray(); }
public static void GetUnlabeledDocsFromSearch(ICollector <UnlabeledDocument> queueData, TraceWriter log) { Stopwatch sw = new Stopwatch(); //var ac = new AuthenticationContext(Constants.AuthorityUri, false); var cert = Utils.GetCertificate(Constants.AADAppCertificateThumbprint); ClientAssertionCertificate cac = new ClientAssertionCertificate(Constants.AADAppClientId, cert); var authResult = ac.AcquireTokenAsync(Constants.ResourceUri, cac).Result; using (ClientContext cc = new ClientContext(Constants.TenantRootUrl)) { cc.ExecutingWebRequest += (s, e) => { e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken; }; ClientResult <ResultTableCollection> results = new ClientResult <ResultTableCollection>(); KeywordQuery keywordQuery = new KeywordQuery(cc); int startRow = 0; var defaultRetentionLabel = Environment.GetEnvironmentVariable("defaultRetentionLabel"); sw.Start(); do { keywordQuery.StartRow = startRow; keywordQuery.QueryText = Constants.KeywordQueryForComplianceTag; keywordQuery.RowLimit = 500; keywordQuery.TrimDuplicates = false; SearchExecutor searchExec = new SearchExecutor(cc); results = searchExec.ExecuteQuery(keywordQuery); cc.ExecuteQuery(); if (results != null) { if (results.Value[0].RowCount > 0) { foreach (var row in results.Value[0].ResultRows) { var path = row["Path"].ToString(); var byteEncodedPath = HttpUtility.UrlEncode(row["Path"].ToString()); var byteEncodedWebUrl = HttpUtility.UrlEncode(row["SPWebUrl"].ToString()); log.Info("Unlabeled document at: " + path); queueData.Add(new UnlabeledDocument(byteEncodedWebUrl, byteEncodedPath, Constants.DefaultRetentionLabel)); } } } startRow += results.Value[0].RowCount; } while (results.Value[0].TotalRowsIncludingDuplicates > startRow); sw.Stop(); telemetry.TrackMetric("CSOM-GetUnlabeledDocs", sw.ElapsedMilliseconds); } }
public ResultTableCollection ExecuteSearch(ClientContext context, Guid webId, Guid siteId) { SearchExecutor searchExecutor = new SearchExecutor(context); KeywordQuery keywordQuery = SharepointCsomProvider.GetKeywordQuery(webId, siteId, context); ClientResult <ResultTableCollection> clientResult = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); return(clientResult.Value); }
public ResultTableCollection ExecuteSearch(ClientContext context, string location, bool searchOnlySiteCollection) { SearchExecutor searchExecutor = new SearchExecutor(context); KeywordQuery keywordQuery = searchOnlySiteCollection ? SharepointCsomProvider.GetKeywordQueryForSiteCollectionOnly(location, context) : SharepointCsomProvider.GetKeywordQuery(location, context); ClientResult <ResultTableCollection> clientResult = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); return(clientResult.Value); }
/* It includes methods related to SampleEntity */ #endregion #region Methods public static List <SearchModel> QuerySearchResults(string siteUrl, string queryText, string contentTypeId, int contentTypeCode, string contentTypeName, string redirectUrl) { try { List <SearchModel> searchResults = new List <SearchModel>(); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(Data.DataStatics.UserNameForService, Data.DataStatics.PasswordForService, Data.DataStatics.DomainForService); ClientContext clientContext = new ClientContext(siteUrl); clientContext.Credentials = credentials; KeywordQuery keywordQuery = new KeywordQuery(clientContext); keywordQuery.QueryText = queryText; keywordQuery.SortList.Add("Created", SortDirection.Descending); string filter1 = "contenttypeid:equals(\"{0}\")"; keywordQuery.RefinementFilters.Add(string.Format(filter1, contentTypeId)); keywordQuery.SelectProperties.Add("ContentTypeId"); keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("ListItemID"); keywordQuery.RowLimit = 10; keywordQuery.ClientType = "ContentSearchRegular"; SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); clientContext.ExecuteQuery(); IEnumerable <IDictionary <string, object> > resultTable = results.Value[0].ResultRows; if (resultTable != null) { foreach (var resultRow in resultTable) { SearchModel newSearchItem = new SearchModel(); newSearchItem.Title = resultRow["Title"].ToString(); newSearchItem.ListItemId = resultRow["ListItemID"].ToString(); newSearchItem.ContentTypeId = resultRow["ContentTypeId"].ToString(); newSearchItem.ContentTypeName = contentTypeName; newSearchItem.ContentTypeCode = contentTypeCode; newSearchItem.RedirectUrl = redirectUrl; searchResults.Add(newSearchItem); } } clientContext.Dispose(); return(searchResults); } catch (Exception ex) { EXP.RedirectToErrorPage(ex.Message); return(null); } }
public ClientResult <ResultTableCollection> Search(string keyword) { KeywordQuery keywordQuery = new KeywordQuery(clientContext); keywordQuery.QueryText = keyword; SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); clientContext.ExecuteQuery(); return(results); }
private int ProcessQuery(Web web, string keywordQueryValue, List <string> propertiesToRetrieve, List <Dictionary <string, string> > sites, KeywordQuery keywordQuery) { int totalRows = 0; keywordQuery.QueryText = keywordQueryValue; keywordQuery.RowLimit = 500; // Make the query return the requested properties foreach (var property in propertiesToRetrieve) { keywordQuery.SelectProperties.Add(property); } // Ensure sorting is done on IndexDocId to allow for performant paging keywordQuery.SortList.Add("IndexDocId", SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(web.Context); // Important to avoid trimming "similar" site collections keywordQuery.TrimDuplicates = false; ClientResult <ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); web.Context.ExecuteQueryRetry(); if (results != null) { if (results.Value[0].RowCount > 0) { totalRows = results.Value[0].TotalRows; foreach (var row in results.Value[0].ResultRows) { Dictionary <string, string> item = new Dictionary <string, string>(); foreach (var property in propertiesToRetrieve) { if (row[property] != null) { item.Add(property, row[property].ToString()); } else { item.Add(property, ""); } } sites.Add(item); } } } return(totalRows); }
/// <summary> /// Get web by title. /// </summary> /// <param name="title"></param> /// <param name="accessToken"></param> /// <returns>A BotSite representing the web if it exists, otherwise null.</returns> public async Task <List <BotSite> > SearchForWeb(string title, AuthResult auth, IBotContext context) { var retVal = new List <BotSite>(); // We need to know the resource ID. This *should be* stored in bot state from when user logged in. string lastSiteCollectionUrl = null; if (!context.UserData.TryGetValue <string>(Constants.StateKeys.LastLoggedInSiteCollectionUrl, out lastSiteCollectionUrl)) { throw new InvalidOperationException("Could not find current tenant URL in bot state."); } using (var clientContext = new ClientContext(lastSiteCollectionUrl)) { clientContext.ExecutingWebRequest += (object sender, WebRequestEventArgs e) => { e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + auth.AccessToken; }; KeywordQuery keywordQuery = new KeywordQuery(clientContext); keywordQuery.TrimDuplicates = true; keywordQuery.QueryText = $"{title} (contentclass:STS_Web OR contentclass:STS_Site)"; SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); clientContext.ExecuteQuery(); if (results.Value.Count > 0) { if (results.Value[0].RowCount > 0) { foreach (var row in results.Value[0].ResultRows) { // TODO : find a more robust way to get URL. If can't find it, then don't include this search result. if (row["SPWebUrl"] != null && !string.IsNullOrEmpty(row["SPWebUrl"].ToString())) { retVal.Add(new BotSite { Alias = string.Empty, Id = Guid.Empty, Title = row["Title"].ToString(), Url = row["SPWebUrl"].ToString() }); } } } } } return(retVal); }
private ResultTable GetResults(KeywordQuery kq) { try { SearchExecutor se = new SearchExecutor(ctx); ClientResult <ResultTableCollection> results = se.ExecuteQuery(kq); ctx.ExecuteQuery(); return(results.Value.FirstOrDefault(v => v.TableType.Equals(KnownTableTypes.RelevantResults))); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); return(null); } }
//按时间显示开始的十条 /// <summary> /// 1为博文,2为汇总 /// </summary> /// <param name="queryState"></param> /// <returns></returns> private DataTable FullQuery(int queryState) { DataTable queryDataTable = null; SPSecurity.RunWithElevatedPrivileges(delegate() { SPServiceContext context = SPServiceContext.Current;// ServerContext.Current;//ServerContext.GetContext SearchServiceApplicationProxy ssap = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site)); using (KeywordQuery qry = new KeywordQuery(ssap)) { qry.EnableStemming = true; qry.TrimDuplicates = true; if (queryState == 1) { qry.RowLimit = totalCount; } else { qry.RowLimit = 5000; } string queryText = "-author:系统帐户 -author:administrator ContentClass:STS_ListItem_Posts"; if (queryState > 1) { double dValue = -30; //if (queryState == 3) // dValue = -60; queryText = queryText + " Created:" + DateTime.Now.AddDays(dValue).ToString("yyyy-MM-dd") + ".." + DateTime.Now.ToString("yyyy-MM-dd"); } qry.QueryText = queryText;// qry.SelectProperties.AddRange(new string[] { "WorkId", "Title", "Author", "AuthorOWSUSER", "Created", "Path", "EditorOWSUSER", "HitHighlightedSummary", "ParentLink" }); qry.SortList.Add("Created", Microsoft.Office.Server.Search.Query.SortDirection.Descending); SearchExecutor searchExecutor = new SearchExecutor(); ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(qry); IEnumerator <ResultTable> iResult = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).GetEnumerator(); iResult.MoveNext(); ResultTable resultTable = iResult.Current; queryDataTable = resultTable.Table; foreach (DataRow dr in queryDataTable.Rows) { string author = dr["Author"].ToString(); if (author.IndexOf(";") > 0)//多个作者 { dr["Author"] = author.Substring(0, author.IndexOf(";")); } } queryDataTable.AcceptChanges(); } }); return(queryDataTable); }
protected override void ExecuteCmdlet() { var keywordQuery = new KeywordQuery(ClientContext); // Construct query to execute var query = "contentclass:STS_Site"; if (!string.IsNullOrEmpty(Query)) { query = query + " AND " + Query; } keywordQuery.QueryText = query; keywordQuery.RowLimit = MaxResults; keywordQuery.StartRow = StartRow; keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("Description"); keywordQuery.SelectProperties.Add("WebTemplate"); keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(ClientContext); // Important to avoid trimming "similar" site collections keywordQuery.TrimDuplicates = false; ClientResult <ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); ClientContext.ExecuteQueryRetry(); var dynamicList = new List <dynamic>(); if (results != null) { if (results.Value[0].RowCount > 0) { foreach (var row in results.Value[0].ResultRows) { dynamicList.Add( new { Title = row["Title"] != null ? row["Title"].ToString() : "", Url = row["SPSiteUrl"] != null ? row["SPSiteUrl"].ToString() : "", Description = row["Description"] != null ? row["Description"].ToString() : "", WebTemplate = row["WebTemplate"] != null ? row["WebTemplate"].ToString() : "" }); } } } WriteObject(dynamicList, true); }
static void Main(string[] args) { string SharePointOnlineUrl = ConfigurationManager.AppSettings["SharepointOnlineUrl"].ToString(); string SharePointOnlineUserLoginName = ConfigurationManager.AppSettings["SharepointOnlineUserEmail"].ToString(); string SharePointOnlineUserPassword = ConfigurationManager.AppSettings["SharepointOnlineUserPassword"].ToString(); List <string> SharePointSearchUserList = new List <string>(); using (ClientContext clientContext = new ClientContext(SharePointOnlineUrl)) { SecureString passWord = new SecureString(); foreach (char c in SharePointOnlineUserPassword.ToCharArray()) { passWord.AppendChar(c); } clientContext.Credentials = new SharePointOnlineCredentials(SharePointOnlineUserLoginName, passWord); int searchCount = 0; int cs = 500; while (cs > 499) { cs = 0; KeywordQuery query = new KeywordQuery(clientContext); query.QueryText = "RefinableInt00:1"; // Change your user filter query query.SourceId = new Guid("B09A7990-05EA-4AF9-81EF-EDFAB16C4E31"); query.RowLimit = 500; query.StartRow = searchCount; SearchExecutor search = new SearchExecutor(clientContext); ClientResult <ResultTableCollection> results = search.ExecuteQuery(query); clientContext.ExecuteQuery(); foreach (var resultRow in results.Value[0].ResultRows) { SharePointSearchUserList.Add(Convert.ToString(resultRow["WorkEmail"])); cs++; } searchCount += cs; } } }
private DataTable FullQuery(string txtFrom, string txtTo) { SPServiceContext context = SPServiceContext.Current; SearchServiceApplicationProxy ssap = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site)); using (KeywordQuery qry = new KeywordQuery(ssap)) { qry.EnableStemming = true; qry.TrimDuplicates = true; qry.RowLimit = 10000; string queryText = GetFullQueryString(); string txtTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); txtTime = txtTime.Substring(txtTime.IndexOf(" ")); qry.QueryText = "Created:" + txtFrom + ".." + txtTo + " " + queryText; qry.SelectProperties.AddRange(new string[] { "WorkId", "Title", "Author", "Created", "Path", "ContentClass", "FileExtension" }); qry.SortList.Add("Created", Microsoft.Office.Server.Search.Query.SortDirection.Descending); SearchExecutor searchExecutor = new SearchExecutor(); ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(qry); IEnumerator <ResultTable> iResult = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).GetEnumerator(); iResult.MoveNext(); ResultTable resultTable = iResult.Current; DataTable queryDataTable = resultTable.Table; if (queryDataTable.Rows.Count > 0) { foreach (DataRow dr in queryDataTable.Rows) { //小时加8 dr["Created"] = ((DateTime)dr["Created"]).AddHours(8); string author = dr["Author"].ToString(); if (author.IndexOf(";") > 0)//多个作者,修改者也加到了里面 { dr["Author"] = author.Substring(0, author.IndexOf(";")); } } queryDataTable.AcceptChanges(); //当天查询减去24小时 if (dateFrom.SelectedDate == DateTime.Today.AddDays(-1) && DateTo.SelectedDate == DateTime.Today) { DataRow[] drs = queryDataTable.Select("Created>='" + txtFrom + txtTime + "' and Created<='" + DateTo.SelectedDate.ToString("yyyy-MM-dd") + txtTime + "'", "Created desc"); DataSet ds = new DataSet(); DataTable dt = queryDataTable.Clone(); ds.Tables.Add(dt); ds.Merge(drs); queryDataTable = ds.Tables[0]; } } return(queryDataTable); } }
//查询结果 private int FullQuery(string txtFrom, string txtTo) { SPServiceContext context = SPServiceContext.Current;// ServerContext.Current;//ServerContext.GetContext SearchServiceApplicationProxy ssap = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site)); using (KeywordQuery qry = new KeywordQuery(ssap)) { qry.EnableStemming = true; qry.TrimDuplicates = true; qry.RowLimit = 10000; string queryText = "ContentClass:STS_ListItem_Posts"; //queryText = "-Author:系统帐户 -Author:administrator "; qry.QueryText = queryText + " Created:" + txtFrom + ".." + txtTo; qry.SelectProperties.AddRange(new string[] { "WorkId", "Title", "Author", "Created", "Path", "ContentClass", "FileExtension", "EditorOWSUSER", "HitHighlightedSummary", "ParentLink" }); qry.SortList.Add("Created", Microsoft.Office.Server.Search.Query.SortDirection.Descending); SearchExecutor searchExecutor = new SearchExecutor(); ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(qry); IEnumerator <ResultTable> iResult = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).GetEnumerator(); iResult.MoveNext(); ResultTable resultTable = iResult.Current; DataTable queryDataTable = resultTable.Table; Response.Clear(); for (int i = 0; i < queryDataTable.Columns.Count; i++) { //Response.Write(i.ToString() + "--name:" + queryDataTable.Columns[i].ColumnName + "--value:" + queryDataTable.Rows[0][i].ToString() + "<br>"); } for (int i = 0; i < queryDataTable.Rows.Count; i++) { for (int j = 0; j < queryDataTable.Columns.Count; j++) { string colName = queryDataTable.Columns[j].ColumnName; Response.Write(colName + ":" + queryDataTable.Rows[i][colName].ToString() + "<br>"); } } //for (int i = 0; i < queryDataTable.Rows.Count; i++) //{ // //Response.Write(i.ToString() + "<br>"); // Response.Write("Author:" + "--value:" + queryDataTable.Rows[i]["Author"].ToString() + "<br>"); // Response.Write("EditorOWSUSER:"******"--value:" + queryDataTable.Rows[i]["EditorOWSUSER"].ToString() + "<br>"); // Response.Write("ParentLink:" + "--value:" + queryDataTable.Rows[i]["ParentLink"].ToString() + "<br>"); // //Response.Write("DocId:" + "--value:" + queryDataTable.Rows[i]["DocId"].ToString() + "<br>"); // //Response.Write("EditorOWSUSER:"******"--value:" + queryDataTable.Rows[i]["EditorOWSUSER"].ToString() + "<br>"); // //Response.Write("Title:" + "--value:" + queryDataTable.Rows[i]["Title"].ToString() + "<br>"); //} return(queryDataTable.Rows.Count); } }
public static List <UserInfo> Search(string query) { using (ClientContext clientContext = new ClientContext(SharePointHelper.SearchUrl)) { ClientResult <ResultTableCollection> results; try { KeywordQuery keywordQuery = new KeywordQuery(clientContext); keywordQuery.QueryText = query + "*"; keywordQuery.TrimDuplicates = true; keywordQuery.SourceId = Guid.Parse(SharePointHelper.SourceId); SearchExecutor searchExecutor = new SearchExecutor(clientContext); results = searchExecutor.ExecuteQuery(keywordQuery); clientContext.ExecuteQuery(); } catch (MessageSecurityException ex) { results = new ClientResult <ResultTableCollection>(); } var users = new List <UserInfo>(); foreach (var result in results.Value[0].ResultRows) { if (result != null) { if (result["PreferredName"] != null && result["AccountName"] != null) { //var user = GetUser(result["AccountName"].ToString(), false, false); var user = new UserInfo() { DisplayName = result["PreferredName"].ToString(), Upn = result["AccountName"].ToString() }; if (!users.Contains(user)) { users.Add(user); } } } } return(users); } }
protected override void ExecuteCmdlet() { var keywordQuery = new KeywordQuery(ClientContext); // Construct query to execute var query = "contentclass:STS_Site"; if(!string.IsNullOrEmpty(Query)) { query = query + " AND " + Query; } keywordQuery.QueryText = query; keywordQuery.RowLimit = MaxResults; keywordQuery.StartRow = StartRow; keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("Description"); keywordQuery.SelectProperties.Add("WebTemplate"); keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(ClientContext); // Important to avoid trimming "similar" site collections keywordQuery.TrimDuplicates = false; ClientResult<ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); ClientContext.ExecuteQueryRetry(); var dynamicList = new List<dynamic>(); if (results != null) { if (results.Value[0].RowCount > 0) { foreach (var row in results.Value[0].ResultRows) { dynamicList.Add( new { Title = row["Title"] != null ? row["Title"].ToString() : "", Url = row["SPSiteUrl"] != null ? row["SPSiteUrl"].ToString() : "", Description = row["Description"] != null ? row["Description"].ToString() : "", WebTemplate = row["WebTemplate"] != null ? row["WebTemplate"].ToString() : "" }); } } } WriteObject(dynamicList, true); }
public static string SearchSharepointSite(SharepointRequest request) { string token = request.AccessToken; string relativeUrl = Utility.GetServerRelativeUrl(request.Url, request.ServerRelativeUrl); ClientContext clientContext = GetClientContext(request); using (clientContext) { KeywordQuery keywordQuery = new KeywordQuery(clientContext); keywordQuery.ClientType = "ContentSearchRegular"; keywordQuery.StartRow = 0; keywordQuery.QueryText = "(Site:" + request.Url + ") AND ((contentclass=STS_Site) AND ((WebTemplate <>POLICYCTR) AND (WebTemplate <>POINTPUBLISHINGHUB) AND (WebTemplate <>POINTPUBLISHINGTOPIC) AND (-SPSiteUrl:personal)))"; StringCollection selectProperties = keywordQuery.SelectProperties; keywordQuery.TrimDuplicates = true; keywordQuery.StartRow = 0; keywordQuery.RowLimit = 50; keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("Path"); keywordQuery.SelectProperties.Add("SiteName"); keywordQuery.SelectProperties.Add("SiteTitle"); keywordQuery.SelectProperties.Add("ContentTypeId"); keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("SPWebUrl"); keywordQuery.SelectProperties.Add("Type"); keywordQuery.TrimDuplicates = false; SearchExecutor searchExecutor = new SearchExecutor(clientContext); clientContext.ExecutingWebRequest += new EventHandler <WebRequestEventArgs>((s, e) => context_ExecutingWebRequest(s, e, token)); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); clientContext.ExecuteQuery(); List <SharepointRequest> spRequests = new List <SharepointRequest>(); foreach (var resultRow in results.Value[0].ResultRows) { SharepointRequest spRequest = new SharepointRequest(); string url = !string.IsNullOrEmpty(Convert.ToString(resultRow["SPSiteUrl"])) ? resultRow["SPSiteUrl"].ToString() : ""; spRequest.Url = url; spRequest.Name = !string.IsNullOrEmpty(Convert.ToString(resultRow["Title"])) ? resultRow["Title"].ToString() : ""; if (!string.IsNullOrEmpty(Convert.ToString(resultRow["Path"]))) { Uri uri = new Uri(resultRow["Path"].ToString()); string serverRelativeURL = uri.AbsolutePath; spRequest.ServerRelativeUrl = serverRelativeURL; } spRequests.Add(spRequest); } return(JsonHelper.ConvertToJson(spRequests)); } }
public async void LoadResults(string siteUrl, string keywords, string login, string mdp) { ObservableCollection<CortanaItem> cortanaResults = new ObservableCollection<CortanaItem>(); keywords = keywords.Trim('.').ToLower(); try { using (ClientContext context = new ClientContext(siteUrl)) { SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(login, mdp); context.Credentials = credentials; KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = keywords; keywordQuery.SourceId = new Guid(SettingsValues.SourceId); keywordQuery.EnablePhonetic = true; keywordQuery.EnableStemming = true; keywordQuery.RowLimit = 100; SearchExecutor searchExecutor = new SearchExecutor(context); ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQueryAsync().Wait(); foreach (var item in results.Value[0].ResultRows) { CortanaItem ci = new CortanaItem(); ci.Id = item["ID"] != null ? item["ID"].ToString() : string.Empty; ci.Title = item["Title"] != null ? item["Title"].ToString() : string.Empty; ci.LastModifiedDate = item["Modified"] != null ? item["Modified"].ToString() : string.Empty; ci.Url = item["Path"] != null ? item["Path"].ToString() : string.Empty; cortanaResults.Add(ci); } } LoadDataCompleted(cortanaResults); // Fire event DataLoadCompleted } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Erreur : " + ex.Message); LoadDataCompleted(null); } }
//gavdcodeend 20 //gavdcodebegin 21 static void SpCsCsomGetResultsSearch(ClientContext spCtx) { KeywordQuery keywordQuery = new KeywordQuery(spCtx); keywordQuery.QueryText = "Team"; SearchExecutor searchExecutor = new SearchExecutor(spCtx); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); spCtx.ExecuteQuery(); foreach (var resultRow in results.Value[0].ResultRows) { Console.WriteLine(resultRow["Title"] + " - " + resultRow["Path"] + " - " + resultRow["Write"]); } }
public async void LoadResults(string siteUrl, string keywords, string login, string mdp) { ObservableCollection <CortanaItem> cortanaResults = new ObservableCollection <CortanaItem>(); keywords = keywords.Trim('.').ToLower(); try { using (ClientContext context = new ClientContext(siteUrl)) { SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(login, mdp); context.Credentials = credentials; KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = keywords; keywordQuery.SourceId = new Guid(SettingsValues.SourceId); keywordQuery.EnablePhonetic = true; keywordQuery.EnableStemming = true; keywordQuery.RowLimit = 100; SearchExecutor searchExecutor = new SearchExecutor(context); ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQueryAsync().Wait(); foreach (var item in results.Value[0].ResultRows) { CortanaItem ci = new CortanaItem(); ci.Id = item["ID"] != null ? item["ID"].ToString() : string.Empty; ci.Title = item["Title"] != null ? item["Title"].ToString() : string.Empty; ci.LastModifiedDate = item["Modified"] != null ? item["Modified"].ToString() : string.Empty; ci.Url = item["Path"] != null ? item["Path"].ToString() : string.Empty; cortanaResults.Add(ci); } } LoadDataCompleted(cortanaResults); // Fire event DataLoadCompleted } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Erreur : " + ex.Message); LoadDataCompleted(null); } }
private ClientResult <ResultTableCollection> ProcessQuery(ClientContext ctx, string keywordQueryValue) { KeywordQuery keywordQuery = new KeywordQuery(ctx); keywordQuery.QueryText = keywordQueryValue; keywordQuery.RowLimit = 500; keywordQuery.StartRow = 0; keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("Description"); keywordQuery.SelectProperties.Add("WebTemplate"); keywordQuery.SortList.Add("SPSiteUrl", Microsoft.SharePoint.Client.Search.Query.SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(ctx); ClientResult <ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); ctx.ExecuteQuery(); return(results); }
static void Main(string[] args) { using (SPSite siteCollection = new SPSite("http://sp2010/sites/test")) { KeywordQuery keywordQuery = new KeywordQuery(siteCollection); keywordQuery.QueryText = "SharePoint"; keywordQuery.SortList.Add("Author", SortDirection.Ascending); keywordQuery.SortList.Add("Size", SortDirection.Descending); SearchExecutor searchExecutor = new SearchExecutor(); ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery); var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults); var resultTable = resultTables.FirstOrDefault(); DataTable dataTable = resultTable.Table; } }
static void QuerySearchEngine(ClientContext ctx, string kql, Action<IDictionary<string, object>> processRow, int startRow = 0) { const int BatchSize = 500; var executor = new SearchExecutor(ctx); var results = executor.ExecuteQuery( new KeywordQuery(ctx) { QueryText = kql, StartRow = startRow, RowLimit = BatchSize }); ctx.ExecuteQuery(); var rows = results.Value[0]; rows.ResultRows.ToList().ForEach(processRow); if (rows.RowCount > 0) { QuerySearchEngine(ctx, kql, processRow, startRow + BatchSize); } }
public ResultTable Search(string keywords, List<string> properties, Dictionary<string, bool> sorting, Guid sourceID, int startRowIndex, int rowLimit) { KeywordQuery keywordQuery = new KeywordQuery(this._ctx); keywordQuery.TrimDuplicates = false; keywordQuery.QueryText = keywords; keywordQuery.SourceId = sourceID; keywordQuery.StartRow = startRowIndex; keywordQuery.RowsPerPage = rowLimit; keywordQuery.RowLimit = rowLimit; keywordQuery.SelectProperties.Clear(); if (properties != null && properties.Count > 0) { foreach (string p in properties) keywordQuery.SelectProperties.Add(p); } if (sorting != null && sorting.Count > 0) { foreach (var sort in sorting) { if (sort.Value) keywordQuery.SortList.Add(sort.Key, SortDirection.Ascending); else keywordQuery.SortList.Add(sort.Key, SortDirection.Descending); } } SearchExecutor searchExecutor = new SearchExecutor(this._ctx); ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); this._ctx.ExecuteQuery(); return results.Value[0]; }
/// <summary> /// /// </summary> /// <param name="cc">ClientContext object of an arbitrary site collection accessible by the defined enumeration username and password</param> /// <param name="keywordQueryValue">Query to execute</param> /// <param name="sites">List of found site collections</param> /// <param name="keywordQuery">KeywordQuery instance that will perform the actual queries</param> /// <param name="startRow">Row as of which we want to see the results</param> /// <returns>Total result rows of the query</returns> private static int ProcessQuery(ClientRuntimeContext cc, string keywordQueryValue, List<string> sites, KeywordQuery keywordQuery, int startRow) { int totalRows = 0; keywordQuery.QueryText = keywordQueryValue; keywordQuery.RowLimit = 500; keywordQuery.StartRow = startRow; keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(cc); ClientResult<ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); cc.ExecuteQueryRetry(); if (results != null) { if (results.Value[0].RowCount > 0) { totalRows = results.Value[0].TotalRows; foreach (var row in results.Value[0].ResultRows) { if (row["SPSiteUrl"] != null) { sites.Add(row["SPSiteUrl"].ToString()); } } } } return totalRows; }
private int ProcessQuery(string keywordQueryValue, List<SiteData> sites, ClientContext ctx, KeywordQuery keywordQuery, int startRow) { int totalRows = 0; keywordQuery.QueryText = keywordQueryValue; keywordQuery.RowLimit = 500; keywordQuery.StartRow = startRow; keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("Description"); keywordQuery.SelectProperties.Add("WebTemplate"); keywordQuery.SortList.Add("SPSiteUrl", Microsoft.SharePoint.Client.Search.Query.SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(ctx); ClientResult<ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); ctx.ExecuteQuery(); if (results != null) { if (results.Value[0].RowCount > 0) { totalRows = results.Value[0].TotalRows; foreach (var row in results.Value[0].ResultRows) { sites.Add(new SiteData { Title = row["Title"] != null ? row["Title"].ToString() : "", Url = row["SPSiteUrl"] != null ? row["SPSiteUrl"].ToString() : "", Description = row["Description"] != null ? row["Description"].ToString() : "", }); } } } return totalRows; }
private static int ExecuteSearch(SPSite site, SPListItem item, string query, string queryTemplate, string sourceLevel, string sourceId, string sourceName, int rowlimit, out List<DynamicAsset> listItems, Dictionary<string, string> itemsProcessed) { HttpRequest httpRequest = new HttpRequest(string.Empty, site.RootWeb.Url, string.Empty); HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter())); SPControl.SetContextWeb(HttpContext.Current, site.RootWeb); Microsoft.SharePoint.SPServiceContext context = SPServiceContext.GetContext(site); // Get the search service application proxy IEnumerable<ResultTable> results = null; KeywordQuery keywordQuery = new KeywordQuery(site); if (!string.IsNullOrEmpty(sourceName)) { SearchServiceApplicationProxy searchProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy; SourceRecord resultSource = null; SearchObjectOwner owner = null; switch (sourceLevel.ToLower()) { case "ssa": owner = new SearchObjectOwner(SearchObjectLevel.Ssa); break; case "spsite": owner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb); break; default: break; } if (owner != null) { resultSource = searchProxy.GetResultSourceByName(sourceName, owner); keywordQuery.SourceId = resultSource.Id; log.TraceInformation(string.Format("Found Result Source: {0}", resultSource.Name)); } } else { keywordQuery.SourceId = new Guid(sourceId); } //filter out the path from query template queryTemplate = FilterPathQueryTemplate(queryTemplate); //replace token values e.g queryTemplate = ReplaceTokens(site, item, queryTemplate); //Dont filter expirt if query is for event type if (queryTemplate.ToLower().Contains("ListItemID:{QueryString.eventId}".ToLower())) { queryTemplate = queryTemplate.ToLower().Replace("ListItemID:{QueryString.eventId}".ToLower(), ""); } else { //filter expired items queryTemplate += AddExpiryFilter(); queryTemplate += AddPendingOrExpiringFilter(); } listItems = null; log.TraceInformation(string.Format("Preparing search execution: QueryTempalte: {0}, Query: {1}, SourceName: {2}, SourceLevel: {3}", queryTemplate, query, sourceName, sourceLevel)); if (!queryTemplate.Contains("searchboxquery")) { keywordQuery.QueryTemplate = queryTemplate; keywordQuery.QueryText = query; keywordQuery.RowLimit = 500; SearchExecutor searchExecutor = new SearchExecutor(); ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery); results = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults); if (results.Count() > 0) { ResultTable resultTable = results.FirstOrDefault(); DataTable dataTable = resultTable.Table; listItems = ProcessResults(site, dataTable, itemsProcessed); } log.TraceInformation(string.Format("Executed query with elapsed time: {0}", resultTableCollection != null ? resultTableCollection.ElapsedTime : -1)); return resultTableCollection != null ? resultTableCollection.ElapsedTime : -1; } return -1; }
// private methods /// <summary> /// Runs a query /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="keywordQueryValue">keyword query </param> /// <param name="sites">sites variable that hold the resulting sites</param> /// <param name="keywordQuery">KeywordQuery object</param> /// <param name="startRow">Start row of the resultset to be returned</param> /// <returns>Total number of rows for the query</returns> private static int ProcessQuery(this Web web, string keywordQueryValue, List<SiteEntity> sites, KeywordQuery keywordQuery, int startRow) { int totalRows = 0; keywordQuery.QueryText = keywordQueryValue; keywordQuery.RowLimit = 500; keywordQuery.StartRow = startRow; keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("Description"); keywordQuery.SelectProperties.Add("WebTemplate"); keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(web.Context); // Important to avoid trimming "similar" site collections keywordQuery.TrimDuplicates = false; ClientResult<ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); web.Context.ExecuteQueryRetry(); if (results != null) { if (results.Value[0].RowCount > 0) { totalRows = results.Value[0].TotalRows; foreach (var row in results.Value[0].ResultRows) { sites.Add(new SiteEntity { Title = row["Title"] != null ? row["Title"].ToString() : "", Url = row["SPSiteUrl"] != null ? row["SPSiteUrl"].ToString() : "", Description = row["Description"] != null ? row["Description"].ToString() : "", Template = row["WebTemplate"] != null ? row["WebTemplate"].ToString() : "", }); } } } return totalRows; }
private ClientResult<ResultTableCollection> ProcessQuery(ClientContext ctx, string keywordQueryValue) { KeywordQuery keywordQuery = new KeywordQuery(ctx); keywordQuery.QueryText = keywordQueryValue; keywordQuery.RowLimit = 500; keywordQuery.StartRow = 0; keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("SPSiteUrl"); keywordQuery.SelectProperties.Add("Description"); keywordQuery.SelectProperties.Add("WebTemplate"); keywordQuery.SortList.Add("SPSiteUrl", Microsoft.SharePoint.Client.Search.Query.SortDirection.Ascending); SearchExecutor searchExec = new SearchExecutor(ctx); ClientResult<ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery); ctx.ExecuteQuery(); return results; }
public ClientResult<ResultTableCollection> ExecuteSearchQuery( string query, string sorting = null, string rankModel = null) { var keywordQuery = new KeywordQuery(_clientContext){ QueryText = query}; // Ranking model to use if (!String.IsNullOrEmpty(rankModel)) keywordQuery.RankingModelId = rankModel; // If sorting parameter provided if (!String.IsNullOrEmpty(sorting)) keywordQuery.SortList.Add(sorting, SortDirection.Descending); // Select only this properties for documents keywordQuery.SelectProperties.Add("Title"); keywordQuery.SelectProperties.Add("Path"); keywordQuery.SelectProperties.Add("ServerRedirectedURL"); keywordQuery.SelectProperties.Add("ModifiedOWSDATE"); keywordQuery.SelectProperties.Add("ModifiedBy"); keywordQuery.SelectProperties.Add("CreatedOWSDATE"); keywordQuery.SelectProperties.Add("CreatedBy"); keywordQuery.SelectProperties.Add("SPWebUrl"); keywordQuery.SelectProperties.Add("Rank"); keywordQuery.SelectProperties.Add("LastModifiedTime"); // Select only this properties for tasks keywordQuery.SelectProperties.Add("StatusOWSCHCS"); keywordQuery.SelectProperties.Add("PercentCompleteOWSNMBR"); keywordQuery.SelectProperties.Add("AssignedTo"); keywordQuery.SelectProperties.Add("DueDateOWSDATE"); keywordQuery.SelectProperties.Add("StartDateOWSDATE"); // Select only this properties for events keywordQuery.SelectProperties.Add("EventDateOWSDATE"); keywordQuery.SelectProperties.Add("EndDateOWSDATE"); var searchExecutor = new SearchExecutor(_clientContext); var results = searchExecutor.ExecuteQuery(keywordQuery); return results; }
private static IEnumerable<TrendingDocument> GetTrendingDocuments(ClientContext clientContext, string[] actorIds) { // Build Office Graph Query string graphQueryText = null; if (actorIds.Length > 1) { StringBuilder graphQueryBuilder = new StringBuilder(); foreach (string actorId in actorIds) { if (graphQueryBuilder.Length > 0) { graphQueryBuilder.Append(","); } graphQueryBuilder.AppendFormat("actor({0},action:1020)", actorId); } graphQueryBuilder.Append(",and(actor(me,action:1021),actor(me,or(action:1021,action:1036,action:1037,action:1039)))"); graphQueryText = String.Format("or({0})", graphQueryBuilder.ToString()); } else { graphQueryText = String.Format("or(actor({0},action:1020),and(actor(me,action:1021),actor(me,or(action:1021,action:1036,action:1037,action:1039))))", actorIds[0]); } // Ensure that the Web URL is available Web web = clientContext.Web; if (!web.IsPropertyAvailable("Url")) { clientContext.Load(web, w => w.Url); clientContext.ExecuteQuery(); } // Configure Search Query KeywordQuery searchQuery = new KeywordQuery(clientContext); searchQuery.QueryText = String.Format("Path:{0}", web.Url); QueryPropertyValue graphQuery = new QueryPropertyValue(); graphQuery.StrVal = graphQueryText; graphQuery.QueryPropertyValueTypeIndex = 1; searchQuery.Properties.SetQueryPropertyValue("GraphQuery", graphQuery); QueryPropertyValue graphRankingModel = new QueryPropertyValue(); graphRankingModel.StrVal = @"{""features"":[{""function"":""EdgeWeight""}],""featureCombination"":""sum"",""actorCombination"":""sum""}"; graphRankingModel.QueryPropertyValueTypeIndex = 1; searchQuery.Properties.SetQueryPropertyValue("GraphRankingModel", graphRankingModel); searchQuery.SelectProperties.AddRange(new string[] { "Author", "AuthorOwsUser", "DocId", "DocumentPreviewMetadata", "Edges", "EditorOwsUser", "FileExtension", "FileType", "HitHighlightedProperties", "HitHighlightedSummary", "LastModifiedTime", "LikeCountLifetime", "ListID", "ListItemID", "OriginalPath", "Path", "Rank", "SPWebUrl", "SecondaryFileExtension", "ServerRedirectedURL", "SiteTitle", "Title", "ViewCountLifetime", "siteID", "uniqueID", "webID" }); searchQuery.BypassResultTypes = true; searchQuery.RowLimit = 5; searchQuery.RankingModelId = "0c77ded8-c3ef-466d-929d-905670ea1d72"; searchQuery.ClientType = "DocumentsTrendingInThisSite"; SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(searchQuery); clientContext.ExecuteQuery(); List<TrendingDocument> trendingDocuments = new List<TrendingDocument>(results.Value[0].ResultRows.Count()); foreach (var row in results.Value[0].ResultRows) { string[] lastModifiedByInfo = row["EditorOwsUser"].ToString().Split('|'); trendingDocuments.Add(new TrendingDocument( row["Title"].ToString(), row["ServerRedirectedURL"].ToString(), GetPreviewImageUrl(row, web.Url), (DateTime)row["LastModifiedTime"], lastModifiedByInfo[1].Trim(), GetUserPhotoUrl(lastModifiedByInfo[0].Trim(), web.Url))); } return trendingDocuments; }
/*private static string GetContentSourcesSearchCondition(string contentSources) { var contentSourcesSearchConditions = string.Empty; var sources = contentSources.Split(','); foreach (var source in sources) { if (contentSourcesSearchConditions.Length > 0) contentSourcesSearchConditions += " OR "; contentSourcesSearchConditions += Settings.Default.SP2013ContentSourceName + "=\"" + source + "\""; } if (contentSourcesSearchConditions.Length > 0) contentSourcesSearchConditions = " AND (" + contentSourcesSearchConditions + ")"; return contentSourcesSearchConditions; }*/ public SearchResponseDto GetSearchResults(string searchTerm, Dictionary<string, string> sources, Dictionary<string, string> refiners, int skip, int take) { SearchResponseDto retVal = null; List<SearchContentSourceDto> srcs = null; using (var ctx = new ClientContext(Settings.Default.SP2013SearchUrl)) { // get the content sources for the query var contentSources = string.Empty; if (!string.IsNullOrEmpty(Settings.Default.SP2013ContentSources)) { srcs = GetContentSourcesList(Settings.Default.SP2013ContentSources); if ((sources != null) && (sources.Count > 0)) srcs = SetSearchedContentSourcesList(sources, srcs); contentSources = GetContentSourcesSearchCondition(srcs); } var query = new KeywordQuery(ctx) { QueryText = searchTerm + contentSources, StartRow = skip, RowLimit = take }; //query.Refiners = "COB,BkrPsu,UwrPsu,AccYr"; // TODO: why aren't bkrpsu and accyr working? query.Refiners = Settings.Default.SearchRefinersList; if (refiners != null) { foreach (var refiner in refiners) { query.RefinementFilters.Add(String.Format("{0}:{1}", refiner.Key, refiner.Value)); } } var returnProps = Settings.Default.SP2013Properties.Split(','); foreach (var prop in returnProps) { query.SelectProperties.Add(prop); } var executor = new SearchExecutor(ctx); var results = executor.ExecuteQuery(query); ctx.ExecuteQuery(); if (results.Value[0] != null) { retVal = new SearchResponseDto(skip + 1, take, results.Value[0].TotalRowsIncludingDuplicates); if (srcs != null) retVal.ContentSources = srcs; retVal.SearchResults.AddRange( results.Value[0].ResultRows.Select(GetSearchContentDto).Where(contentDto => contentDto != null)); retVal.Properties = returnProps; retVal.Refiners = results.Value.FirstOrDefault(v => v.TableType == "RefinementResults"); } } return retVal; }
/// <summary> /// Find the default list of tenant user profile photo thumbnails so we can use them as a source for training. /// </summary> public void findTrainingPhotosFromUserProfile() { using (ClientContext context = Login(SharePointURL)) { try { KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = "*"; keywordQuery.SourceId = Guid.Parse(peopleSourceID); keywordQuery.SelectProperties.Add("PictureURL"); keywordQuery.SelectProperties.Add("PreferredName"); keywordQuery.SelectProperties.Add("AccountName"); SearchExecutor searchExecutor = new SearchExecutor(context); ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); foreach (var resultRow in results.Value[0].ResultRows) { if (resultRow["PictureURL"] != null) { string name = (string) resultRow["PreferredName"]; string imageURL = (string) resultRow["PictureURL"]; string user = (string)resultRow["AccountName"]; imageURL = imageURL.Replace("MThumb", "LThumb"); addProfilePictureToTrainingList(name, name, imageURL, "", "", user); } } } catch (Exception e) { throw; } } }
/// <summary> /// Fires query on SharePoint Search and fills the result data. /// </summary> /// <param name="clientContext">The client context.</param> /// <param name="keywordQuery">The keyword query.</param> /// <param name="searchObject">The search object.</param> /// <param name="isMatterSearch">The flag to determine weather call is from Search Matter or Search Document.</param> /// <param name="managedProperties">List of managed properties</param> /// <returns>It returns a string object, that contains all the results combined with dollar pipe dollar separator.</returns> internal static string FillResultData(ClientContext clientContext, KeywordQuery keywordQuery, SearchObject searchObject, Boolean isMatterSearch, List<string> managedProperties) { string result = string.Empty; Boolean isReadOnly; try { if (null != searchObject.Sort) { keywordQuery.EnableSorting = true; keywordQuery = SearchHelperFunctions.GetSortByProperty(keywordQuery, searchObject, isMatterSearch); } SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult<ResultTableCollection> resultsTableCollection = searchExecutor.ExecuteQuery(keywordQuery); Users currentLoggedInUser = UIUtility.GetLoggedInUserDetails(clientContext); if (null != resultsTableCollection && null != resultsTableCollection.Value && 0 < resultsTableCollection.Value.Count && null != resultsTableCollection.Value[0].ResultRows) { if (isMatterSearch && 0 < resultsTableCollection.Value.Count && null != resultsTableCollection.Value[0].ResultRows && (!string.IsNullOrWhiteSpace(currentLoggedInUser.Name) || !string.IsNullOrWhiteSpace(currentLoggedInUser.Email))) { foreach (IDictionary<string, object> matterMetadata in resultsTableCollection.Value[0].ResultRows) { isReadOnly = false; if (null != matterMetadata) { // Decode matter properties DecodeMatterProperties(matterMetadata); string readOnlyUsers = Convert.ToString(matterMetadata[SearchConstants.ManagedPropertyBlockedUploadUsers], CultureInfo.InvariantCulture); if (!string.IsNullOrWhiteSpace(readOnlyUsers)) { isReadOnly = IsUserReadOnlyForMatter(isReadOnly, currentLoggedInUser.Name, currentLoggedInUser.Email, readOnlyUsers); } matterMetadata.Add(TextConstants.IsReadOnlyUser, isReadOnly); } } } else { /*Keeping the code to clean the author values*/ foreach (IDictionary<string, object> documentMetadata in resultsTableCollection.Value[0].ResultRows) { if (null != documentMetadata) { string authorData = Convert.ToString(documentMetadata[SearchConstants.ManagedPropertyAuthor], CultureInfo.InvariantCulture); int ltIndex = authorData.IndexOf(ConstantStrings.OpeningAngularBracket, StringComparison.Ordinal); int gtIndex = authorData.IndexOf(ConstantStrings.ClosingAngularBracket, StringComparison.Ordinal); authorData = (0 <= ltIndex && ltIndex < gtIndex) ? authorData.Remove(ltIndex, (gtIndex - ltIndex) + 1) : authorData; authorData = authorData.Replace(ServiceConstantStrings.DoubleQuotes, string.Empty); documentMetadata[SearchConstants.ManagedPropertyAuthor] = authorData.Trim(); } } } if (1 < resultsTableCollection.Value.Count) { result = string.Concat(JsonConvert.SerializeObject(resultsTableCollection.Value[0].ResultRows), ConstantStrings.DOLLAR, ConstantStrings.Pipe, ConstantStrings.DOLLAR, resultsTableCollection.Value[0].TotalRows, ConstantStrings.DOLLAR, ConstantStrings.Pipe, ConstantStrings.DOLLAR, JsonConvert.SerializeObject(resultsTableCollection.Value[1].ResultRows)); } else { if (0 == resultsTableCollection.Value[0].TotalRows) { result = SearchHelperFunctions.NoDataRow(managedProperties); } else { result = string.Concat(JsonConvert.SerializeObject(resultsTableCollection.Value[0].ResultRows), ConstantStrings.DOLLAR, ConstantStrings.Pipe, ConstantStrings.DOLLAR, resultsTableCollection.Value[0].TotalRows); } } } else { result = SearchHelperFunctions.NoDataRow(managedProperties); } } catch (Exception exception) { result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } return result; }
/// <summary> /// This method executes te search api to get most popular items from the current site /// </summary> /// <param name="clientContext"></param> /// <param name="propListName"></param> /// <param name="errMSG"></param> /// <returns></returns> public static string GetFAQFromSearchAPI(string propListName, string errMSG) { string mostPopular = string.Empty; try { Web oWeb = clientContext.Web; clientContext.Load(oWeb); clientContext.ExecuteQuery(); KeywordQuery keywordQuery = new KeywordQuery(clientContext); Uri uri = new Uri(oWeb.Url.ToString()); string urlPath = System.Web.HttpUtility.UrlPathEncode(uri.GetLeftPart(UriPartial.Authority) + GetListUrlByTitle(propListName)[0]); string actualURL = string.Format(@"path:{0}", urlPath); StringCollection selectProperties = keywordQuery.SelectProperties; selectProperties.Add("LastModifiedTime"); selectProperties.Add("ContentTypeId"); selectProperties.Add("Title"); selectProperties.Add("Answer"); keywordQuery.QueryText = actualURL; SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); clientContext.ExecuteQuery(); mostPopular = GenerateFAQHTML(results, errMSG); } catch (Exception ex) { mostPopular = errMSG; Logger.WriteLog(Logger.Category.Unexpected, string.Format("{0}-{1}", "CommonHelper", "GetFAQFromSearchAPI"), ex.StackTrace); } return mostPopular; }
private List<string> GetMemberSites() { var siteUri = new Uri(ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]); using (var context = this.contextFactory.GetContext(siteUri.ToString())) { var keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = "rdoyle AND SiteGroup:\"Team\""; keywordQuery.TrimDuplicates = false; var searchExecutor = new SearchExecutor(context); var results = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); } return new List<string>(); }
/// <summary> /// Fires query on SharePoint Search and fills the result data. /// </summary> /// <param name="clientContext">The client context.</param> /// <param name="keywordQuery">The keyword query.</param> /// <param name="searchObject">The search object.</param> /// <param name="isMatterSearch">The flag to determine weather call is from Search Matter or Search Document.</param> /// <param name="managedProperties">List of managed properties</param> /// <returns>It returns a string object, that contains all the results combined with dollar pipe dollar separator.</returns> private SearchResponseVM FillResultData(ClientContext clientContext, KeywordQuery keywordQuery, SearchRequestVM searchRequestVM, Boolean isMatterSearch, List<string> managedProperties) { SearchResponseVM searchResponseVM = new SearchResponseVM(); Boolean isReadOnly; try { var searchObject = searchRequestVM.SearchObject; //var client = searchRequestVM.Client; if (null != searchObject.Sort) { keywordQuery.EnableSorting = true; keywordQuery = GetSortByProperty(keywordQuery, searchObject, isMatterSearch); } if(keywordQuery.QueryText.Length > 4000) { return new SearchResponseVM(); } SearchExecutor searchExecutor = new SearchExecutor(clientContext); ClientResult<ResultTableCollection> resultsTableCollection = searchExecutor.ExecuteQuery(keywordQuery); Users currentLoggedInUser = userDetails.GetLoggedInUserDetails(clientContext); if (null != resultsTableCollection && null != resultsTableCollection.Value && 0 < resultsTableCollection.Value.Count && null != resultsTableCollection.Value[0].ResultRows) { if (isMatterSearch && 0 < resultsTableCollection.Value.Count && null != resultsTableCollection.Value[0].ResultRows && !string.IsNullOrWhiteSpace(currentLoggedInUser.Email)) { foreach (IDictionary<string, object> matterMetadata in resultsTableCollection.Value[0].ResultRows) { isReadOnly = false; if (null != matterMetadata) { // Decode matter properties DecodeMatterProperties(matterMetadata); string readOnlyUsers = Convert.ToString(matterMetadata[searchSettings.ManagedPropertyBlockedUploadUsers], CultureInfo.InvariantCulture); if (!string.IsNullOrWhiteSpace(readOnlyUsers)) { isReadOnly = IsUserReadOnlyForMatter(isReadOnly, currentLoggedInUser.Name, currentLoggedInUser.Email, readOnlyUsers); } matterMetadata.Add(generalSettings.IsReadOnlyUser, isReadOnly); } } } else { /*Keeping the code to clean the author values*/ foreach (IDictionary<string, object> documentMetadata in resultsTableCollection.Value[0].ResultRows) { if (null != documentMetadata) { string authorData = Convert.ToString(documentMetadata[searchSettings.ManagedPropertyAuthor], CultureInfo.InvariantCulture); int ltIndex = authorData.IndexOf(ServiceConstants.OPENING_ANGULAR_BRACKET, StringComparison.Ordinal); int gtIndex = authorData.IndexOf(ServiceConstants.CLOSING_ANGULAR_BRACKET, StringComparison.Ordinal); authorData = (0 <= ltIndex && ltIndex < gtIndex) ? authorData.Remove(ltIndex, (gtIndex - ltIndex) + 1) : authorData; authorData = authorData.Replace(ServiceConstants.ENCODED_DOUBLE_QUOTES, string.Empty); documentMetadata[searchSettings.ManagedPropertyAuthor] = authorData.Trim(); } } } if (resultsTableCollection.Value.Count > 1) { searchResponseVM.TotalRows = resultsTableCollection.Value[0].TotalRows; searchResponseVM.SearchResults = resultsTableCollection.Value[0].ResultRows; } else { if (resultsTableCollection.Value[0].TotalRows == 0) { searchResponseVM = NoDataRow(managedProperties); } else { searchResponseVM.TotalRows = resultsTableCollection.Value[0].TotalRows; searchResponseVM.SearchResults = resultsTableCollection.Value[0].ResultRows; } } } else { searchResponseVM = NoDataRow(managedProperties); } } catch (Exception exception) { customLogger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable); throw; } return searchResponseVM; }
private List<string> GetHiddenProjectSites() { var siteUri = new Uri(ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]); var resultsList = new List<string>(); using (var context = this.contextFactory.GetContext(siteUri.ToString())) { var keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = "Project AND HiddenSite AND ContentType=\"Site Collection Metadata\""; keywordQuery.TrimDuplicates = false; keywordQuery.SelectProperties.Clear(); keywordQuery.SelectProperties.Add("SiteNumFollowers"); keywordQuery.SelectProperties.Add("SiteTitle"); keywordQuery.SelectProperties.Add("SiteMembers"); var searchExecutor = new SearchExecutor(context); var results = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQuery(); var result = results.Value[0]; foreach (var res in result.ResultRows) { var siteTitle = res["SiteName"]; resultsList.Add(siteTitle.ToString()); } } return resultsList; }