Ejemplo n.º 1
0
        private SharepointValidationResult GetValidationResult(ResultTableCollection queryResults, ClientContext context)
        {
            SharepointValidationResult result = null;

            foreach (ResultTable resultTable in queryResults)
            {
                if (resultTable.TableType == KnownTableTypes.RelevantResults)
                {
                    foreach (IDictionary <string, object> dictionary in resultTable.ResultRows)
                    {
                        string text  = null;
                        string text2 = null;
                        if (dictionary.ContainsKey("WebId") && dictionary.ContainsKey("SiteId"))
                        {
                            text  = (dictionary["WebId"] as string);
                            text2 = (dictionary["SiteId"] as string);
                        }
                        if (!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(text2))
                        {
                            Guid   webId  = new Guid(text);
                            Guid   siteId = new Guid(text2);
                            string text3  = dictionary["contentclass"] as string;
                            if (text3 == "STS_Web" || text3 == "STS_Site")
                            {
                                result = this.GetValidationResult(webId, siteId, text3, dictionary, context);
                                break;
                            }
                            result = this.ValidateLocation(webId, siteId, context);
                            break;
                        }
                    }
                }
            }
            return(result);
        }
        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);
            }
        }
Ejemplo n.º 3
0
        public static DataTable ExecuteQuery(string SiteCollection, string QueryString)
        {
            SPSite        col = new SPSite(SiteCollection);
            ServerContext ctx = ServerContext.GetContext(col);

            FullTextSqlQuery ftq = new FullTextSqlQuery(ctx);

            ftq.ResultTypes    = ResultType.RelevantResults;
            ftq.EnableStemming = true;
            ftq.TrimDuplicates = true;
            ftq.QueryText      = QueryString;

            ResultTableCollection allresults = ftq.Execute();

            ResultTable relevant = allresults[ResultType.RelevantResults];

            DataTable dt = null;

            if (relevant.RowCount > 0)
            {
                dt = new DataTable("Search Result");
                dt.Columns.Add("Title");
                dt.Columns.Add("URL");
                while (relevant.Read())
                {
                    DataRow row = dt.NewRow();
                    row[0] = relevant.GetString(0);
                    row[1] = relevant.GetString(1);
                    dt.Rows.Add(row);
                }
            }

            return(dt);
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
0
        /// <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);
        }
        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);
        }
        public ResultTableCollectionInstance(ObjectInstance prototype, ResultTableCollection resultTableCollection)
            : this(prototype)
        {
            if (resultTableCollection == null)
            {
                throw new ArgumentNullException("resultTableCollection");
            }

            m_resultTableCollection = resultTableCollection;
        }
Ejemplo n.º 8
0
        private bool HasMultipleSitesUnderLocation(string location, ClientContext context)
        {
            ResultTableCollection resultTableCollection = SharepointValidator.CsomProvider.ExecuteSearch(context, location, true);

            foreach (ResultTable resultTable in resultTableCollection)
            {
                if (resultTable.TableType == KnownTableTypes.RelevantResults && resultTable.RowCount > 1)
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 9
0
        //按时间显示开始的十条
        /// <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);
        }
Ejemplo n.º 10
0
        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);
            }
        }
Ejemplo n.º 11
0
        //查询结果
        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);
            }
        }
Ejemplo n.º 12
0
        private static ResultTable RealizarBusqueda(string guid)
        {
            FullTextSqlQuery query            = new FullTextSqlQuery(new SPSite(urlBusqueda));
            ResultType       resultType       = ResultType.RelevantResults;
            string           strQuery         = String.Format("SELECT Title, Path, Fecha FROM SCOPE() WHERE (\"" + property + "\"='#{0}')", guid);
            FullTextSqlQuery fullTextSqlQuery = new FullTextSqlQuery(new SPSite(urlBusqueda));

            fullTextSqlQuery.QueryText      = strQuery;
            fullTextSqlQuery.ResultTypes    = resultType;
            fullTextSqlQuery.RowLimit       = 0;
            fullTextSqlQuery.TrimDuplicates = false;
            ResultTableCollection resultTableCollection = fullTextSqlQuery.Execute();
            ResultTable           resultTable           = resultTableCollection[resultType];

            return(resultTable);
        }
Ejemplo n.º 13
0
        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);
        }
        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";
            }
        }
Ejemplo n.º 15
0
        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;
            }
        }
Ejemplo n.º 16
0
        private SharepointValidationResult ValidateLocationBySearch(string location)
        {
            SharepointValidationResult validationResult = null;

            Utils.WrapSharePointCsomCall(this.spSiteContextUrl, this.credentials, delegate(ClientContext context)
            {
                ResultTableCollection queryResults = SharepointValidator.CsomProvider.ExecuteSearch(context, location, false);
                validationResult = this.GetValidationResult(queryResults, context);
            });
            if (validationResult == null)
            {
                base.LogOneEntry(ExecutionLog.EventType.Error, "InvalidArgument: {0}", new object[]
                {
                    Strings.SpLocationValidationFailed(location)
                });
                validationResult = SharepointValidator.CreateFailedResult(Strings.SpLocationValidationFailed(location));
            }
            return(validationResult);
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            string SPSiteAdress = ConfigurationManager.AppSettings["SPSiteAddress"].ToString();

            Console.WindowWidth  = 150;
            Console.WindowHeight = 50;
            Console.WriteLine(SPSiteAdress);

            SPSite     objSite      = new SPSite(SPSiteAdress); //Replace with yours
            SPWeb      objTargetWeb = objSite.OpenWeb(SPSiteAdress);
            ResultType resultType   = ResultType.RelevantResults;


            Console.WriteLine("type your query....");
            string strQuery = Console.ReadLine();

            Console.WriteLine("type your ranking model ID....");
            string rankikgModelId = Console.ReadLine();

            KeywordQuery   keywordQuery   = new KeywordQuery(objSite);
            SearchExecutor searchExecutor = new SearchExecutor();

            keywordQuery.QueryText   = strQuery;
            keywordQuery.ResultTypes = resultType;
            //This is where we specify the custom ranking model to use.
            keywordQuery.RankingModelId = rankikgModelId;
            ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
            ResultTable           resultTable           = resultTableCollection[resultType];
            int    index     = 0;
            string separator = "  ";

            while (resultTable.Read())
            {
                index++;
                if (index > 9)
                {
                    separator = " ";
                }
                Console.WriteLine(index + separator + "Rank: " + String.Format("{0:0.00000}", resultTable["RANK"]) + " Title: " + resultTable["TITLE"].ToString());
            }

            Console.ReadLine();
        }
Ejemplo n.º 18
0
        //按时间显示开始的十条
        /// <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);
        }
Ejemplo n.º 19
0
        private static Stream ToJson(ResultTableCollection value)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();

            List <JavaScriptConverter> converters = new List <JavaScriptConverter>();

            converters.Add(new DataRowConverter());
            converters.Add(new ResultTableCollectionConverter());
            ser.RegisterConverters(converters);

            var resultStream = new MemoryStream();
            var writer       = new StreamWriter(resultStream);

            writer.Write(ser.Serialize(value));

            writer.Flush();
            resultStream.Position = 0;

            return(resultStream);
        }
        public IEnumerable <IncidentTask> GetAllOpenIncidentTasks()
        {
            FullTextSqlQuery sqlQuery = new FullTextSqlQuery(ServerContext.Current);

            sqlQuery.QueryText   = Resources.PartnerRollupFullTextQuery;
            sqlQuery.ResultTypes = ResultType.RelevantResults;

            // Write the query to the trace log, so developers can debug it more easily.
            ILogger logger = SharePointServiceLocator.Current.GetInstance <ILogger>();

            logger.TraceToDeveloper(
                string.Format(CultureInfo.CurrentCulture,
                              Resources.IncidentTasksFullTextSqlQuery,
                              sqlQuery.QueryText));

            ResultTableCollection queryResults = sqlQuery.Execute();
            DataTable             resultsTable = new DataTable();

            resultsTable.Locale = CultureInfo.CurrentCulture;
            resultsTable.Load(queryResults[ResultType.RelevantResults]);

            List <IncidentTask> results = new List <IncidentTask>();

            foreach (DataRow datarow in resultsTable.Rows)
            {
                IncidentTask result = new IncidentTask();
                result.Path       = datarow[PathField] == DBNull.Value ? string.Empty : (string)datarow[PathField];
                result.Title      = datarow[TitleField] == DBNull.Value ? string.Empty : (string)datarow[TitleField];
                result.AssignedTo = datarow[AssignedToField] == DBNull.Value
                                        ? string.Empty
                                        : (string)datarow[AssignedToField];

                // For some reason, the the Status field is returned as an array of strings. The status can be accessed
                // using the index 0.
                result.Status   = datarow[StatusField] == DBNull.Value ? string.Empty : ((string[])datarow[StatusField])[0];
                result.Priority = datarow[PriorityField] == DBNull.Value ? string.Empty : (string)datarow[PriorityField];
                results.Add(result);
            }
            return(results);
        }
Ejemplo n.º 21
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            SPSite                 col       = new SPSite(txtSC.Text);
            ServerContext          ctx       = ServerContext.GetContext(col);
            DropDownHelper <Scope> dds       = (DropDownHelper <Scope>)cbScope.SelectedItem;
            string                 ScopeName = dds.Item.Name;

            string query = "Select title, url FROM Scope() where \"Scope\" = '" + ScopeName + "' AND Freetext('" + txtPhrase.Text + " ')";


            FullTextSqlQuery ftq = new FullTextSqlQuery(ctx);

            ftq.ResultTypes    = ResultType.RelevantResults;
            ftq.EnableStemming = true;
            ftq.TrimDuplicates = true;
            ftq.QueryText      = query;

            ResultTableCollection allresults = ftq.Execute();

            ResultTable relevant = allresults[ResultType.RelevantResults];

            DataTable dt = null;

            if (relevant.RowCount > 0)
            {
                dt = new DataTable("Search Result");
                dt.Columns.Add("Title");
                dt.Columns.Add("URL");
                while (relevant.Read())
                {
                    DataRow row = dt.NewRow();
                    row[0] = relevant.GetString(0);
                    row[1] = relevant.GetString(1);
                    dt.Rows.Add(row);
                }

                gvResult.DataSource = dt;
                gvResult.AutoResizeColumns();
            }
        }
Ejemplo n.º 22
0
        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();
                }
            }
        }
Ejemplo n.º 23
0
        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);
            }
        }
Ejemplo n.º 24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetPageTitles("Tìm kiếm");
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            string k = Request.QueryString["k"];

                            KeywordQuery keywordQuery = new KeywordQuery(web);

                            keywordQuery.QueryText  = k;
                            keywordQuery.QueryText += "(contentclass:STS_List OR contentclass:STS_List_DocumentLibrary) CustomeURL:.aspx";
                            //keywordQuery.QueryText = "scope:\"All Sites\" AND (contentclass:\"STS_Site\" OR contentclass:\"STS_Web\")";
                            keywordQuery.StartRow = 0;
                            keywordQuery.RowLimit = 500;
                            //keywordQuery.SourceId = PeopleSearch;
                            keywordQuery.EnableNicknames = true;
                            keywordQuery.EnablePhonetic  = true;
                            keywordQuery.TrimDuplicates  = false;

                            //which columns should be returned in the query result.

                            keywordQuery.SelectProperties.Add("title");
                            keywordQuery.SelectProperties.Add("CustomeURL");
                            keywordQuery.SelectProperties.Add("ImageUrl");

                            SearchExecutor searchExecutor = new SearchExecutor();
                            ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
                            var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);

                            if (resultTables != null && resultTables.Any())
                            {
                                var resultTable = resultTables.FirstOrDefault();

                                if (resultTable != null)
                                {
                                    DataTable dataTable = resultTable.Table;
                                    //rpResult.DataSource = dataTable;
                                    //rpResult.DataBind();
                                    BindDataIntoRepeater(dataTable);
                                    table = dataTable;
                                }
                                else
                                {
                                    table = new DataTable();
                                }
                            }
                            else
                            {
                                table = new DataTable();
                            }
                        }
                    }
                });
            }
        }
Ejemplo n.º 25
0
        public List <Record> DoSharePointSearch(GDPRSubject search)
        {
            GDPRCore.Current.Log("Starting SharePoint Search");

            List <Record> records = new List <Record>();

            try
            {
                using (SPSite siteCollection = GetFirstSPSite())
                {
                    KeywordQuery   keywordQuery   = new KeywordQuery(siteCollection);
                    SearchExecutor searchExecutor = new SearchExecutor();

                    foreach (GDPRSubjectEmail se in search.EmailAddresses)
                    {
                        keywordQuery.QueryText = se.EmailAddress;
                        ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
                        ResultTable           resultTable           = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault();
                        DataTable             dataTable             = resultTable.Table;

                        if (dataTable.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dataTable.Rows)
                            {
                                Record r = GetSearchRecord(dr);

                                if (r != null)
                                {
                                    records.Add(r);
                                }
                            }
                        }
                    }

                    foreach (GDPRSubjectPhone se in search.Phones)
                    {
                        keywordQuery.QueryText = se.Raw;
                        ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
                        ResultTable           resultTable           = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault();
                        DataTable             dataTable             = resultTable.Table;

                        if (dataTable.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dataTable.Rows)
                            {
                                Record r = GetSearchRecord(dr);

                                if (r != null)
                                {
                                    records.Add(r);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //GDPRCore.Current.Log(ex, LogLevel.Error);
            }

            return(records);
        }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
0
        private SharepointValidationResult GetValidationResult(Guid webId, Guid siteId, ResultTableCollection queryResults, ClientContext context)
        {
            SharepointValidationResult result = null;

            foreach (ResultTable resultTable in queryResults)
            {
                if (resultTable.TableType == KnownTableTypes.RelevantResults)
                {
                    foreach (IDictionary <string, object> dictionary in resultTable.ResultRows)
                    {
                        if (dictionary.ContainsKey("Path"))
                        {
                            string contentClass = dictionary["contentclass"] as string;
                            result = this.GetValidationResult(webId, siteId, contentClass, dictionary, context);
                            break;
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 28
0
        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 + " 条数据!";
            }
        }
Ejemplo n.º 29
0
        private SharepointValidationResult ValidateLocation(Guid webId, Guid siteId, ClientContext context)
        {
            ResultTableCollection queryResults = SharepointValidator.CsomProvider.ExecuteSearch(context, webId, siteId);

            return(this.GetValidationResult(webId, siteId, queryResults, context));
        }