private bool IsRunningFast() { var ssaProxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.Current); return(ssaProxy.FASTAdminProxy != null); }
public SearchConfigurationManager(SPSite siteCollection) { _siteCollection = siteCollection; _searchService = GetSearchServiceApplicationProxy(); _searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, _siteCollection.RootWeb); _resultTypeManager = new ResultItemTypeManager(_searchService); }
private DataTable GetItems() { DataTable resultsDataTable = new DataTable(); if (tags.Length > 0) { SPSite site = new SPSite(SPContext.Current.Site.Url); /* * FullTextSqlQuery query = new FullTextSqlQuery(site); * query.Hint = QueryHint.OptimizeWithPropertyStore; * // inserito per prendere tutto. BUG della search * query.TrimDuplicates = false; * query.QueryText = "SELECT Path, title, Created, Tags, TipoContenuto, SiteTitle, SiteName FROM scope() WHERE \"scope\"='All Sites' AND (CONTAINS(Tags,'\"" + tags[0] + "\"')"; * if (tags.Length > 1) * { * for (int i = 1; i < tags.Length; i++) * { * query.QueryText += " OR CONTAINS(Tags,'\"" + tags[i] + "\"')"; * } * } * query.QueryText += ") ORDER BY LastModifiedTime Desc"; * query.SiteContext = new Uri(site.Url); * query.ResultTypes = ResultType.RelevantResults; * */ SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site)); KeywordQuery query = new KeywordQuery(proxy); //query.EnableFQL = true; query.QueryText = propertyName + ":\"" + tags[0] + "\""; if (tags.Length > 1) { for (int i = 1; i < tags.Length; i++) { query.QueryText += " OR " + propertyName + ":\"" + tags[i] + "\""; } } query.ResultsProvider = SearchProvider.Default; query.ResultTypes = ResultType.RelevantResults; query.StartRow = 0; query.RowLimit = 5000; query.TrimDuplicates = false; query.SelectProperties.Add("Path"); query.SelectProperties.Add("title"); query.SelectProperties.Add("Descrizione"); query.SelectProperties.Add(propertyName); query.SelectProperties.Add("TipoContenuto"); query.SelectProperties.Add("Created"); query.SelectProperties.Add("SiteTitle"); query.SelectProperties.Add("SiteName"); query.SortList.Add("Rank", Microsoft.Office.Server.Search.Query.SortDirection.Descending); // ResultTableCollection resultTables = query.Execute(); ResultTable relevantResults = resultTables[ResultType.RelevantResults]; resultsDataTable.Load(relevantResults, LoadOption.OverwriteChanges); } return(resultsDataTable); }
/// <summary> /// Gets a search service application connected to the specified site collection. /// </summary> /// <param name="site">A site collection object.</param> /// <returns>A search service application.</returns> public static SearchServiceApplication GetSearchServiceApplication(SPSite site) { CommonHelper.ConfirmNotNull(site, "site"); SPServiceContext serviceContext = SPServiceContext.GetContext(site); SearchServiceApplicationProxy searchApplicationProxy = (SearchServiceApplicationProxy)serviceContext.GetDefaultProxy(typeof(SearchServiceApplicationProxy)); Guid applicationId = searchApplicationProxy.GetSearchServiceApplicationInfo().SearchServiceApplicationId; return(SearchService.Service.SearchApplications.GetValue <SearchServiceApplication>(applicationId)); }
public SearchServiceApplicationProxy GetSearchServiceApplicationProxy() { SPServiceContext serviceContext = SPServiceContext.GetContext(_siteCollection); SearchServiceApplicationProxy defaultProxy = serviceContext.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy; if (defaultProxy == null) { throw new ApplicationException("Search service application proxy not found."); } return(defaultProxy); }
private SearchSettingsUtility(SPSite site) { _searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb); SPServiceContext context = SPServiceContext.GetContext(site); _searchProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy; if (_searchProxy == null) { throw new ArgumentException("SearchServiceApplicationProxy not found for site collection {0}", site.Url); } }
//按时间显示开始的十条 /// <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); }
//查询结果 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); } }
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); } }
public string GetSearchResult(string messageInput) { string k = GetSearchKeyWord(messageInput); string ret = string.Empty; using (SPMonitoredScope scope = new SPMonitoredScope("MyCustomMessageHandler.GetSearchResult")) { //KeywordQuery keywordquery = new KeywordQuery(SPContext.Current.Site); //keywordquery.ResultTypes = ResultType.RelevantResults; //keywordquery.QueryText = string.Concat("ContentSource=", contentSourceName, " ", AppearInWeChat, "=True"); //keywordquery.SelectProperties.Add(WeChatResult); //keywordquery.TrimDuplicates = false; //keywordquery.RowsPerPage = 0; //keywordquery.RowLimit = 10; //keywordquery.Timeout = 5000; //SearchExecutor searchexecutor = new SearchExecutor(); //2013 foundation 里面的SearchExecutor这里没有 //ResultTableCollection resulttablecollection = searchexecutor.ExecuteQuery(keywordquery); //ResultTable resulttable = resulttablecollection.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault(); //https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ms493601(v=office.14) SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site)); KeywordQuery query = new KeywordQuery(proxy); query.ResultsProvider = Microsoft.Office.Server.Search.Query.SearchProvider.Default; query.QueryText = string.Concat("ContentSource=", contentSourceName, " ", AppearInWeChat, "=True"); query.ResultTypes |= ResultType.RelevantResults; ResultTableCollection searchResults = query.Execute(); if (searchResults.Exists(ResultType.RelevantResults)) { ResultTable searchResult = searchResults[ResultType.RelevantResults]; DataTable result = new DataTable(); result.TableName = "Result"; result.Load(searchResult, LoadOption.OverwriteChanges); StringBuilder sb = new StringBuilder(); foreach (DataRow r in result.Rows) { sb.Append(r[WeChatResult]); sb.Append(System.Environment.NewLine); } ret = sb.ToString(); } } return(ret); }
public static void PopulateSynonyms(Dictionary <string, List <string> > synonymLookup) { SPSecurity.RunWithElevatedPrivileges( delegate { try { var ssaProxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.Current); if (ssaProxy.FASTAdminProxy != null) { var fastProxy = ssaProxy.FASTAdminProxy; KeywordContext keywordContext = fastProxy.KeywordContext; SearchSettingGroupCollection searchSettingGroupCollection = keywordContext.SearchSettingGroups; DateTime currentDate = DateTime.Now; foreach (SearchSettingGroup searchSettingGroup in searchSettingGroupCollection) { foreach (Keyword keyword in searchSettingGroup.Keywords) { foreach (Synonym synonym in keyword.Synonyms) { if (synonym.StartDate < currentDate || synonym.EndDate > currentDate) { continue; } AddSynonym(keyword.Term, synonym.Term, synonymLookup); if (synonym.ExpansionType == SynonymExpansionType.TwoWay) { AddSynonym(synonym.Term, keyword.Term, synonymLookup); } } } } } } catch (SecurityException secEx) { Logger.Instance.Error("Failed to populated synonyms", secEx, DiagnosticsCategories.eCaseSearch); throw secEx; } } ); }
void searchButton_Click(object sender, EventArgs e) { //Only search if there are search terms if (searchTermsTextbox.Text != string.Empty) { //First, we must connect to the service application proxy SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site)); //Create and configure a Keyword Query object KeywordQuery query = new KeywordQuery(proxy); query.ResultsProvider = SearchProvider.Default; query.QueryText = searchTermsTextbox.Text; //Relevant Results are the main search results query.ResultTypes = ResultType.RelevantResults; //Now we can execute the query ResultTableCollection searchResults = query.Execute(); if (searchResults.Exists(ResultType.RelevantResults)) { //There are relevant results. We need them in a Data Table //so we can bind them to the Data Grid for display ResultTable resultTable = searchResults[ResultType.RelevantResults]; //Tell the user how many results we got resultsLabel.Text = String.Format("There are {0} results", resultTable.TotalRows.ToString()); //Set up and load the data table DataTable resultDataTable = new DataTable(); resultDataTable.TableName = "Result"; resultDataTable.Load(resultTable, LoadOption.OverwriteChanges); //Bind the datatable to the Data Grid resultsGrid.DataSource = resultDataTable; resultsGrid.DataBind(); } else { //Search executed but found nothing resultsLabel.Text = "There were no relevant results. Try other search terms"; } } else { //No search terms in the textbox resultsLabel.Text = "Please enter at least one search term"; } }
//按时间显示开始的十条 /// <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; qry.RowLimit = TotalCount; string titleQue = ""; if (CourseKeyword.Trim().Length > 0) { string[] titles = CourseKeyword.Split(';'); foreach (string titel in titles) { titleQue = titleQue + " title:\"" + titel + "\""; } } string queryText = "ContentClass:STS_ListItem_Posts" + titleQue; SPUser spUser = SPContext.Current.Web.CurrentUser; if (LoginUser == 1 && spUser != null) { queryText = "author:" + spUser.Name + " " + queryText; } ////this.Controls.Add(new LiteralControl(queryText)); qry.QueryText = queryText;// qry.SelectProperties.AddRange(new string[] { "WorkId", "Title", "Author", "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; } }); return(queryDataTable); }
public static void PopulateManagedProperties(Dictionary <string, string> propertyLookup) { SPSecurity.RunWithElevatedPrivileges( delegate { var ssaProxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.Current); if (ssaProxy.FASTAdminProxy != null) { var fastProxy = ssaProxy.FASTAdminProxy; SchemaContext schemaContext = fastProxy.SchemaContext; foreach (ManagedProperty property in schemaContext.Schema.AllManagedProperties.Where(property => property.Queryable)) { propertyLookup.Add(property.Name.ToLower(), GetFqlType(property.Type)); } } } ); }
protected void ExecuteSearchQuery(string searchQueryText) { Logging.Logger.Instance.Info("Executing Search Query"); //TODO: Refactor this to allow reuse with the btnSave code below SPServiceContext serviceContext = SPServiceContext.Current; SPServiceApplicationProxy proxy = serviceContext.GetDefaultProxy(typeof(SearchServiceApplicationProxy)); SearchServiceApplicationProxy searchAppProxy = proxy as SearchServiceApplicationProxy; string scopeName = String.Empty; if (SPContext.Current.Site.RootWeb.AllProperties.Contains(SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_SAVED_SEARCH_RESULTS_SCOPE)) { scopeName = SPContext.Current.Site.RootWeb.AllProperties[SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_SAVED_SEARCH_RESULTS_SCOPE] as string; } Logging.Logger.Instance.Info(String.Format("Scope retrieved from property bag setting. Scope: {0}; Setting Name: {1} ; Site: {2}", scopeName, SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_SAVED_SEARCH_RESULTS_SCOPE, SPContext.Current.Site.RootWeb.Url), Logging.DiagnosticsCategories.eCaseSearch); if (!String.IsNullOrEmpty(searchQueryText)) { using (KeywordQuery query = new KeywordQuery(SPContext.Current.Site)) { int rowsPerSet = 50; query.QueryText = queryLabel.Text; query.ResultsProvider = SearchProvider.Default; query.ResultTypes = ResultType.RelevantResults; query.RowLimit = rowsPerSet; query.TrimDuplicates = false; query.EnableStemming = true; if (!String.IsNullOrEmpty(scopeName)) { query.HiddenConstraints = "scope:\"" + scopeName + "\""; } ResultTableCollection resultsTableCollection = query.Execute(); rowCountSpan.InnerText = resultsTableCollection[ResultType.RelevantResults].TotalRows.ToString(); } } }
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 = ""; //queryText = "-Author:系统帐户 -Author:administrator "; qry.QueryText = queryText + "Created:" + txtFrom + ".." + txtTo; 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; return(queryDataTable.Rows.Count); } }
public static void PopulateScopes(Dictionary <string, string> scopeLookup) { SPSecurity.RunWithElevatedPrivileges( delegate { var ssaProxy = (SearchServiceApplicationProxy) SearchServiceApplicationProxy.GetProxy(SPServiceContext.Current); var searchApplictionInfo = ssaProxy.GetSearchServiceApplicationInfo(); var searchApplication = SearchService.Service.SearchApplications.GetValue <SearchServiceApplication>( searchApplictionInfo.SearchServiceApplicationId); Scopes scopes = new Scopes(searchApplication); foreach (Scope scope in scopes.GetScopesForSite(null)) { if (!string.IsNullOrEmpty(scope.Filter)) { scopeLookup[scope.Name.ToLower()] = scope.Filter; } } } ); }
private static void RebuildMetadataProperties(XNode config, SPServiceContext context) { // Get the search service application proxy var searchProxy = SearchServiceApplicationProxy.GetProxy(context); // Another alternative is the following line ;) // * var searchProxy = // context.GetDefaultProxy(typeof (SearchServiceApplicationProxy)) as SearchServiceApplicationProxy; if (searchProxy == null) { throw new InvalidOperationException("Search Service Application was not found."); } // Get the search service application info object so we can find the Id of // our Search Service Application. var ssai = searchProxy.GetSearchServiceApplicationInfo(); // Get the application itself var searchApp = SearchService.Service.SearchApplications.GetValue <SearchServiceApplication>(ssai.SearchServiceApplicationId); // Get the schema of our Search Service Application var schema = new Schema(searchApp); var crawledPropsCache = new List <CrawledProperty>(); var categories = schema.AllCategories; // Remove Managed Properties var managedPropsRemove = config.XPathSelectElements("/SearchConfiguration/ManagedProperties/remove"); RemoveManagedProperties(schema, managedPropsRemove); var loadedCategories = new HashSet <string>(); // Add / update crawled properties under different categories // SearchConfiguration > CrawledProperties > Category foreach (var categoryCfg in config.XPathSelectElements("/SearchConfiguration/CrawledProperties/Category")) { // If crawled properties in this category are not loaded // load them and add category name to the list. var categoryName = TryGetAttributeValue(categoryCfg, "Name"); if (string.IsNullOrEmpty(categoryName)) { Logger.LogMessage(SeverityLevels.Critical, LogCategory, string.Format(CategoryAttributeMissingLogFormat, "Name")); continue; } var cat = categories[categoryName]; if (!loadedCategories.Contains(categoryName)) { crawledPropsCache.AddRange(categories[categoryName].GetAllCrawledProperties().Cast <CrawledProperty>()); loadedCategories.Add(categoryName); } // SearchConfiguration > CrawledProperties > Category > * (clear | CrawledProperty) foreach (var crawledPropCfg in categoryCfg.Elements()) { if (crawledPropCfg.Name == "clear") { ClearCrawledPropertiesInCategory(crawledPropsCache, cat, categoryCfg); } else if (crawledPropCfg.Name == "CrawledProperty") { // Create the crawled property if it doesn't exist CreateCrawledPropertyIfDoesNotExist(crawledPropsCache, cat, crawledPropCfg); } } } // Get all the managed properties // Create all required managed properties // SearchConfiguration > ManagedProperties > ManagedProperty // foreach (var managedPropCfg in config.Element("SearchConfiguration").Element("ManagedProperties").Elements("ManagedProperty")) foreach (var managedPropCfg in config.XPathSelectElements("/SearchConfiguration/ManagedProperties/ManagedProperty")) { var managedPropName = TryGetAttributeValue(managedPropCfg, "Name"); if (string.IsNullOrEmpty(managedPropName)) { Logger.LogMessage(SeverityLevels.Critical, LogCategory, string.Format(UnknownManagedPropertyAttributeMissingLogFormat, "Name")); continue; } var managedPropType = TryGetAttributeValue(managedPropCfg, "Type"); if (string.IsNullOrEmpty(managedPropType)) { Logger.LogMessage(SeverityLevels.Critical, LogCategory, string.Format(KnownManagedPropertyAttributeMissingLogFormat, managedPropName, "Type")); continue; } var managedProp = CreateOrGetManagedProperty(schema, managedPropName, managedPropType); // Create all the required mappings for the current Managed Property var isMappingChanged = false; MappingCollection mappings = null; foreach (var mapCfg in managedPropCfg.Elements()) { if (mapCfg.Name == "clear") { // Clear all mappings of this ManagedProperty managedProp.DeleteAllMappings(); isMappingChanged = true; } else if (mapCfg.Name == "Map") { // Add new mappings mappings = managedProp.GetMappings(); var crawledPropName = mapCfg.Value; var mappingCategoryName = TryGetAttributeValue(mapCfg, "Category"); var crawledProp = FindCrawledProperty(schema, crawledPropName, mappingCategoryName, crawledPropsCache, loadedCategories); // Map the managed property to the crawled property (if found) if (crawledProp != null) { var mapping = new Mapping( crawledProp.Propset, crawledPropName, crawledProp.VariantType, managedProp.PID); if (!mappings.Contains(mapping)) { mappings.Add(mapping); isMappingChanged = true; } } else { Logger.LogMessage(SeverityLevels.Critical, LogCategory, string.Format(PropertyMappingFailedExceptionFormat, managedPropName)); } } } if (isMappingChanged) { managedProp.SetMappings(mappings); } } }
private void RecreateContentSources(XNode config, SPServiceContext context) { // Get the search service application proxy var searchProxy = SearchServiceApplicationProxy.GetProxy(context); if (searchProxy == null) { throw new Exception(DefaultSsaProxyNotFoundExceptionMessage); } var ssaInfo = searchProxy.GetSearchServiceApplicationInfo(); var searchApp = SearchService.Service.SearchApplications.GetValue <SearchServiceApplication>(ssaInfo.SearchServiceApplicationId); var content = new Content(searchApp); // Remove content sources specified by remove tag in configuration XML. var removeContentSourceElements = config.XPathSelectElements("/SearchConfiguration/ContentSources/remove"); foreach (var removeContentSourceElement in removeContentSourceElements) { var contentSourceName = TryGetAttributeValue(removeContentSourceElement, "Name"); if (content.ContentSources.Exists(contentSourceName)) { var contentSource = content.ContentSources[contentSourceName]; contentSource.Delete(); } else { Logger.LogMessage( SeverityLevels.Warning, LogCategory, string.Format(ContentSourceNotFoundRemovalFailedLogFormat, contentSourceName)); } } // Create new Content Sources (if they don't exist) var contentSourceElements = config.XPathSelectElements("/SearchConfiguration/ContentSources/ContentSource"); foreach (var contentSourceElement in contentSourceElements) { var contentSourceName = TryGetAttributeValue(contentSourceElement, "Name"); var contentSourceExists = content.ContentSources.Exists(contentSourceName); if (contentSourceExists) { Logger.LogMessage( SeverityLevels.Information, LogCategory, string.Format(ContentSourceExistsLogFormat, contentSourceName)); var recreateAttr = contentSourceElement.Attribute("RecreateIfExists"); if (recreateAttr != null && bool.Parse(recreateAttr.Value)) { var contentSource = content.ContentSources[contentSourceName]; if (contentSource.StartAddresses.Count > 0) { contentSource.StartAddresses.Clear(); contentSource.Update(); } contentSource.Delete(); contentSourceExists = false; } } if (!contentSourceExists) { var contentSourceTypeName = TryGetAttributeValue(contentSourceElement, "Type"); var startFullCrawl = bool.Parse(contentSourceElement.AttributeOrDefault("StartFullCrawl", "false")); var contentSourceType = GetContentSourceTypeFromString(contentSourceTypeName); var contentSource = content.ContentSources.Create(contentSourceType, contentSourceName); ConstructStartAddresses(contentSource, contentSourceElement.Elements("StartAddress")); contentSource.Update(); if (startFullCrawl) { contentSource.StartFullCrawl(); } } } }
public SearchServiceApplicationProxyInstance(ScriptEngine engine, SearchServiceApplicationProxy searchServiceApplicationProxy) : base(engine) { m_searchServiceApplicationProxy = searchServiceApplicationProxy; this.PopulateFunctions(); }
public static string CreateBestBetXml(List <string> queryWords, bool exactMatchOnTerms) { List <string> bestBets = new List <string>(); List <string> termDefs = new List <string>(); SPSecurity.RunWithElevatedPrivileges( delegate { var ssaProxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.Current); if (ssaProxy.FASTAdminProxy != null) { var fastProxy = ssaProxy.FASTAdminProxy; KeywordContext keywordContext = fastProxy.KeywordContext; SearchSettingGroupCollection searchSettingGroupCollection = keywordContext.SearchSettingGroups; DateTime currentDate = DateTime.Now; string fullQuery = string.Join(" ", queryWords.ToArray()); foreach (SearchSettingGroup searchSettingGroup in searchSettingGroupCollection) { foreach (Keyword keyword in searchSettingGroup.Keywords) { List <string> terms = exactMatchOnTerms ? GetFullTermAndSynonymWords(keyword) : GetPartialTermAndSynonymWords(keyword); foreach (string bestBetTerms in terms) { //TODO: fullquery - check any combination with exact match on the best bet if (!_reNonChar.IsMatch(bestBetTerms)) //a-z only { Regex reBoundaryMatch = new Regex(@"\b" + bestBetTerms + @"\b"); if (!reBoundaryMatch.IsMatch(fullQuery)) { continue; } } if (!queryWords.Contains(bestBetTerms)) { continue; } string termDef = GetTermDefXml(keyword); if (!string.IsNullOrEmpty(termDef) && !termDefs.Contains(termDef)) { termDefs.Add(termDef); } foreach (BestBet bestBet in keyword.BestBets) { if (bestBet.StartDate < currentDate || bestBet.EndDate > currentDate) { continue; } string xml = BuildBestBetXml(keyword, bestBet); if (!bestBets.Contains(xml)) { bestBets.Add(xml); } } } } } } } ); return("<All_Results>" + string.Join("", termDefs.ToArray()) + "<BestBetResults>" + string.Join("", bestBets.ToArray()) + "</BestBetResults></All_Results>"); }
public void ProcessRequest(HttpContext context) { if (context.Request.HttpMethod != "GET") { return; } string relativeUri = context.Request.QueryString["url"]; string query = context.Request.QueryString["query"]; string language = context.Request.QueryString["language"]; string sourceId = context.Request.QueryString["sourceId"]; int numberOfQuerySuggestions; int.TryParse(context.Request.QueryString["numberOfQuerySuggestions"], out numberOfQuerySuggestions); int numberOfResultSuggestions; int.TryParse(context.Request.QueryString["numberOfResultSuggestions"], out numberOfResultSuggestions); bool preQuerySuggestions; bool.TryParse(context.Request.QueryString["preQuerySuggestions"], out preQuerySuggestions); bool hitHighlighting; bool.TryParse(context.Request.QueryString["hitHighlighting"], out hitHighlighting); bool showPeopleNameSuggestions; bool.TryParse(context.Request.QueryString["showPeopleNameSuggestions"], out showPeopleNameSuggestions); bool capitalizeFirstLetters; bool.TryParse(context.Request.QueryString["capitalizeFirstLetters"], out capitalizeFirstLetters); bool prefixMatchAllTerms; bool.TryParse(context.Request.QueryString["prefixMatchAllTerms"], out prefixMatchAllTerms); var uri = new Uri(context.Request.Url, relativeUri); using (var site = new SPSite(uri.AbsoluteUri)) { ISearchServiceApplication ssaProxy = SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(site)); if (string.IsNullOrWhiteSpace(relativeUri)) { relativeUri = "/"; } using (SPWeb web = site.OpenWeb(relativeUri)) { if (!string.IsNullOrWhiteSpace(context.Request.QueryString["trimsuggestions"])) { bool trim; bool.TryParse(context.Request.QueryString["trimsuggestions"], out trim); web.SetProperty("mAdcOWQuerySuggestions_TrimSuggestions", trim); context.Response.Write("Security trimming og search suggestions: " + trim); return; } // Make sure SPContect.Current works from ajax if (SPContext.Current == null) { HttpContext.Current.Items["HttpHandlerSPWeb"] = web; } var qp = GetQueryProperties(query, showPeopleNameSuggestions, sourceId, language); if (IsUserAnonymous) { numberOfResultSuggestions = 0; } QuerySuggestionResults results = ssaProxy.GetQuerySuggestionsWithResults(qp, numberOfQuerySuggestions, numberOfResultSuggestions, preQuerySuggestions, hitHighlighting, capitalizeFirstLetters, prefixMatchAllTerms); bool trimSuggestions; bool.TryParse(web.GetProperty("mAdcOWQuerySuggestions_TrimSuggestions") + "", out trimSuggestions); if (trimSuggestions) { results.Queries = SecurityTrimSearchSuggestions(results.Queries, web, qp.SourceId, qp.Culture); } var serializer = new JavaScriptSerializer(); context.Response.ContentType = "application/json"; context.Response.Write(serializer.Serialize(results)); } } }
protected void saveSearchResultsButton_Click(object sender, EventArgs e) { Logging.Logger.Instance.Info("Begin Saving Search Results"); string scopeName = String.Empty; if (SPContext.Current.Site.RootWeb.AllProperties.Contains(SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_SAVED_SEARCH_RESULTS_SCOPE)) { scopeName = SPContext.Current.Site.RootWeb.AllProperties[SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_SAVED_SEARCH_RESULTS_SCOPE] as string; } Logging.Logger.Instance.Info(String.Format("Scope retrieved from property bag setting. Scope: {0}; Setting Name: {1} ; Site: {2}", scopeName, SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_SAVED_SEARCH_RESULTS_SCOPE, SPContext.Current.Site.RootWeb.Url), Logging.DiagnosticsCategories.eCaseSearch); SPServiceContext serviceContext = SPServiceContext.Current; SPServiceApplicationProxy proxy = serviceContext.GetDefaultProxy(typeof(SearchServiceApplicationProxy)); SearchServiceApplicationProxy searchAppProxy = proxy as SearchServiceApplicationProxy; if (!String.IsNullOrEmpty(savedSearchNameTextBox.Text)) //&& !String.IsNullOrEmpty(Request.QueryString["query"])) { using (KeywordQuery query = new KeywordQuery(SPContext.Current.Site)) { int rowsPerSet = 50; query.QueryText = queryLabel.Text; query.ResultsProvider = SearchProvider.Default; query.ResultTypes = ResultType.RelevantResults; query.TrimDuplicates = false; query.EnableStemming = true; if (!String.IsNullOrEmpty(scopeName)) { Logging.Logger.Instance.Info(String.Format("Adding scope to hidden constraints: {0}", scopeName), Logging.DiagnosticsCategories.eCaseSearch); query.HiddenConstraints = "scope:\"" + scopeName + "\""; } query.RowLimit = rowsPerSet; ResultTableCollection resultsTableCollection = query.Execute(); if (resultsTableCollection.Count > 0) { //save search result entry string connectionString = SPContext.Current.Site.RootWeb.Properties[SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_DB_CONNECTION_STRING]; Int64 searchRowIdentity = 0; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString)) { Logging.Logger.Instance.Info(String.Format("Opening database connection to: {0}", connectionString)); conn.Open(); using (System.Data.SqlClient.SqlTransaction trans = conn.BeginTransaction()) { //Insert the Saved Search Results Parent Entry using (System.Data.SqlClient.SqlCommand parentInsertCommand = new System.Data.SqlClient.SqlCommand()) { parentInsertCommand.Connection = conn; parentInsertCommand.Transaction = trans; parentInsertCommand.CommandType = CommandType.StoredProcedure; parentInsertCommand.CommandText = "CreateSavedSearchResult"; if (!IsNew) { parentInsertCommand.Parameters.AddWithValue("@Id", Request.QueryString["id"]); } parentInsertCommand.Parameters.AddWithValue("@Name", savedSearchNameTextBox.Text); parentInsertCommand.Parameters.AddWithValue("@Description", savedSearchDescriptionTextBox.Text); parentInsertCommand.Parameters.AddWithValue("@Query", queryLabel.Text); parentInsertCommand.Parameters.AddWithValue("@Owner", SPContext.Current.Web.CurrentUser.LoginName); searchRowIdentity = (Int64)parentInsertCommand.ExecuteScalar(); } using (System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter()) { if (IsNew) //skip updating the results if this isn't a new result set to save time and effort { string maxResultsString = SPContext.Current.Site.RootWeb.Properties[SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagKeys.ECASE_SAVED_SEARCH_RESULTS_MAX_RESULTS]; int maxResults; if (!int.TryParse(maxResultsString, out maxResults)) { int.TryParse(SusDeb.DOI.Common.Utilities.eCaseConstants.PropertyBagDefaultValues.ECASE_SAVED_SEARCH_RESULTS_MAX_RESULTS, out maxResults); } Logging.Logger.Instance.Info(String.Format("Results limit: {0}", maxResults), Logging.DiagnosticsCategories.eCaseSearch); ResultTable results = resultsTableCollection[ResultType.RelevantResults]; int startRow = 0; int rowsFound = 0; int lastRow = startRow + results.RowCount; using (System.Data.SqlClient.SqlCommand childInsertCommand = new System.Data.SqlClient.SqlCommand()) { childInsertCommand.Connection = conn; childInsertCommand.Transaction = trans; childInsertCommand.CommandText = @"INSERT INTO SavedSearchResultItems ( SavedSearchResultId, WorkId, Rank, Author, Size, Path, Description, SiteName, HitHighlightedSummary, HitHighlightedProperties, ContentClass, IsDocument, PictureThumbnailUrl, Url, ServerRedirectedUrl, FileExtension, SpSiteUrl, docvector, fcocount, fcoid, PictureWidth, PictureHeight ) VALUES ( @SavedSearchResultId, @WorkId, @Rank, @Author, @Size, @Path, @Description, @SiteName, @HitHighlightedSummary, @HitHighlightedProperties, @ContentClass, @IsDocument, @PictureThumbnailUrl, @Url, @ServerRedirectedUrl, @FileExtension, @SpSiteUrl, @docvector, @fcocount, @fcoid, @PictureWidth, @PictureHeight )"; childInsertCommand.Parameters.Add("@SavedSearchResultId", System.Data.SqlDbType.BigInt); childInsertCommand.Parameters["@SavedSearchResultId"].Value = searchRowIdentity; childInsertCommand.Parameters.Add("@WorkId", System.Data.SqlDbType.NVarChar, 50, "WorkId"); childInsertCommand.Parameters.Add("@Rank", System.Data.SqlDbType.Int, 0, "Rank"); childInsertCommand.Parameters.Add("@Author", System.Data.SqlDbType.NVarChar, 50, "Author"); childInsertCommand.Parameters.Add("@Size", System.Data.SqlDbType.Int, 50, "Size"); childInsertCommand.Parameters.Add("@Path", System.Data.SqlDbType.NVarChar, 500, "Path"); childInsertCommand.Parameters.Add("@Description", System.Data.SqlDbType.NVarChar, 500000, "Description"); childInsertCommand.Parameters.Add("@SiteName", System.Data.SqlDbType.NVarChar, 500, "SiteName"); childInsertCommand.Parameters.Add("@HitHighlightedSummary", System.Data.SqlDbType.NVarChar, 500000, "HitHighlightedSummary"); childInsertCommand.Parameters.Add("@HitHighlightedProperties", System.Data.SqlDbType.NVarChar, 500000, "HitHighlightedProperties"); childInsertCommand.Parameters.Add("@ContentClass", System.Data.SqlDbType.NVarChar, 50, "ContentClass"); childInsertCommand.Parameters.Add("@IsDocument", System.Data.SqlDbType.Bit, 0, "IsDocument"); childInsertCommand.Parameters.Add("@PictureThumbnailUrl", System.Data.SqlDbType.NVarChar, 500, "PictureThumbnailUrl"); childInsertCommand.Parameters.Add("@Url", System.Data.SqlDbType.NVarChar, 500, "Url"); childInsertCommand.Parameters.Add("@ServerRedirectedUrl", System.Data.SqlDbType.NVarChar, 500, "ServerRedirectedUrl"); childInsertCommand.Parameters.Add("@FileExtension", System.Data.SqlDbType.NVarChar, 500, "FileExtension"); childInsertCommand.Parameters.Add("@SpSiteUrl", System.Data.SqlDbType.NVarChar, 500, "SpSiteUrl"); childInsertCommand.Parameters.Add("@docvector", System.Data.SqlDbType.NVarChar, 500, "docvector"); childInsertCommand.Parameters.Add("@fcocount", System.Data.SqlDbType.Int, 0, "fcocount"); childInsertCommand.Parameters.Add("@fcoid", System.Data.SqlDbType.NVarChar, 50, "fcoid"); childInsertCommand.Parameters.Add("@PictureWidth", System.Data.SqlDbType.Int, 0, "PictureWidth"); childInsertCommand.Parameters.Add("@PictureHeight", System.Data.SqlDbType.Int, 0, "PictureHeight"); da.InsertCommand = childInsertCommand; //if we've found a number of rows <= the total rows in the result set AND //the current result set contains > 0 results (there are still new results being found) AND //we've found <= the maximum number of rows we're allowing to be saved while (rowsFound <= results.TotalRows && results.RowCount > 0 && rowsFound <= maxResults) { da.Update(results.Table); //set the start row = the last row we found query.StartRow = lastRow; //increment the last row we found by the number of results we retrieved lastRow += results.RowCount; rowsFound += results.RowCount; Logging.Logger.Instance.Info(String.Format("Results Found: {0}; Last Result Found: {1}", rowsFound, query.StartRow), Logging.DiagnosticsCategories.eCaseSearch); resultsTableCollection = query.Execute(); results = resultsTableCollection[ResultType.RelevantResults]; } } } using (System.Data.SqlClient.SqlDataAdapter permsAdapter = new System.Data.SqlClient.SqlDataAdapter()) { //for permissions, always remove all items and then add them back using (System.Data.SqlClient.SqlCommand permsDeleteCommand = new System.Data.SqlClient.SqlCommand()) { permsDeleteCommand.Connection = conn; permsDeleteCommand.Transaction = trans; permsDeleteCommand.CommandText = @"DELETE FROM SavedSearchResultPermissions WHERE SavedSearchResultsId = @SavedSearchResultsId "; permsDeleteCommand.Parameters.Add("@SavedSearchResultsId", System.Data.SqlDbType.BigInt); permsDeleteCommand.Parameters["@SavedSearchResultsId"].Value = searchRowIdentity; permsDeleteCommand.ExecuteNonQuery(); } using (System.Data.SqlClient.SqlCommand permsInsertCommand = new System.Data.SqlClient.SqlCommand()) { permsInsertCommand.Connection = conn; permsInsertCommand.Transaction = trans; permsInsertCommand.CommandText = @"INSERT INTO SavedSearchResultPermissions ( SavedSearchResultsId, PermissionName ) VALUES ( @SavedSearchResultsId, @PermissionName )"; permsInsertCommand.Parameters.Add("@SavedSearchResultsId", System.Data.SqlDbType.BigInt); permsInsertCommand.Parameters["@SavedSearchResultsId"].Value = searchRowIdentity; permsInsertCommand.Parameters.Add("@PermissionName", System.Data.SqlDbType.NVarChar, 100, "PermissionName"); foreach (object account in shareWithPeopleEditor.Accounts) { permsInsertCommand.Parameters["@PermissionName"].Value = account.ToString(); permsInsertCommand.ExecuteNonQuery(); } } } } trans.Commit(); Microsoft.SharePoint.Utilities.SPUtility.Redirect( Microsoft.SharePoint.Utilities.SPUtility.GetPageUrlPath(Context) + String.Format("?id={0}", searchRowIdentity), Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, Context ); } } } } } PopulateSavedSearchResultsSetsInfo(); SetFormDisplayMode(false); }
protected SearchServiceApplicationProxyInstance(ObjectInstance prototype, SearchServiceApplicationProxy searchServiceApplicationProxy) : base(prototype) { m_searchServiceApplicationProxy = searchServiceApplicationProxy; }
private void 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 = 500; string queryText = ""; //获取id和显示名称 if (userID.ResolvedEntities.Count > 0) { string name = ((PickerEntity)userID.ResolvedEntities[0]).DisplayText; queryText = "Author:" + name + " ";; // userID.CommaSeparatedAccounts.Replace(";", "") + " "; } else { queryText = "-Author:系统帐户 -Author:administrator "; } qry.QueryText = queryText + "Created:" + txtFrom + ".." + txtTo; 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; DataTable distinctTable = queryDataTable.Clone(); foreach (DataRow dr in queryDataTable.Rows) { //小时加8 dr["Created"] = ((DateTime)dr["Created"]).AddHours(8); switch (dr["ContentClass"].ToString()) { case "STS_ListItem_TasksWithTimelineAndHierarchy": dr["ContentClass"] = "任务"; break; case "STS_ListItem_GenericList": dr["ContentClass"] = "自定义列表"; break; case "STS_ListItem_Posts": dr["ContentClass"] = "博客文章"; break; case "STS_ListItem_851": //Asset Library / Video Channel dr["ContentClass"] = "资产库"; break; case "STS_ListItem_DocumentLibrary": dr["ContentClass"] = "文档库"; break; case "STS_ListItem_MySiteDocumentLibrary": dr["ContentClass"] = "个人网站文档库"; break; case "STS_Site": dr["ContentClass"] = "网站集"; break; case "STS_ListItem_Announcements": dr["ContentClass"] = "通知新闻"; break; case "STS_ListItem_PictureLibrary": dr["ContentClass"] = "图片库"; break; case "STS_ListItem_Comments": dr["ContentClass"] = "博客评论"; break; case "STS_ListItem_Categories": dr["ContentClass"] = "博客类别"; break; case "STS_Web": dr["ContentClass"] = "网站"; break; case "STS_ListItem_544": //MicroBlogList (MicroFeed) dr["ContentClass"] = "新闻源"; break; case "STS_ListItem_Survey": dr["ContentClass"] = "调查"; break; } string author = dr["Author"].ToString(); if (author.IndexOf(";") > 0) //多个作者 { dr["Author"] = author.Substring(0, author.IndexOf(";")); } string url = dr["Path"].ToString(); try { dr["Path"] = url.Substring(url.IndexOf("/", 7)); } catch { } DataRow[] drs = distinctTable.Select("Path='" + dr["Path"] + "'"); if (drs.Length == 0) { distinctTable.Rows.Add(dr.ItemArray); } } queryDataTable.AcceptChanges(); _gvtable = distinctTable.Copy(); errlable.Text = "本次查询共 " + _gvtable.Rows.Count + " 条数据!"; } }