private void backgroundWorkerFind_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // Do not access the form's BackgroundWorker reference directly.
                // Instead, use the reference provided by the sender parameter.
                BackgroundWorker worker = sender as BackgroundWorker;

                if (worker.CancellationPending == false)
                {
                    SearchArguments arg = e.Argument as SearchArguments;
                    this.GetUriList(worker, e, arg);
                }

                // If the operation was canceled by the user,
                // set the DoWorkEventArgs.Cancel property to true.
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                }
            }
            catch (Exception)
            {
                //throw the exception so that RunWorkerCompleted can catch it.
                throw;
            }
        }
Пример #2
0
        }     // End Sub Test

        public static System.Collections.Generic.List <SearchResult> SearchContent(
            SearchArguments searchArguments)
        {
            System.Collections.Generic.List <SearchResult> searchResults = new System.Collections.Generic.List <SearchResult>();

            string[] filez = System.IO.Directory.GetFiles(searchArguments.LookIn, searchArguments.FileName, System.IO.SearchOption.AllDirectories);

            for (int i = 0; i < filez.Length; ++i)
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(filez[i]))
                {
                    for (int lineNumber = 1; !reader.EndOfStream; ++lineNumber)
                    {
                        string line = reader.ReadLine();
                        int    pos  = line.IndexOf(searchArguments.ContainingText, System.StringComparison.OrdinalIgnoreCase);

                        if (pos != -1)
                        {
                            searchResults.Add(new SearchResult(filez[i], line, lineNumber, pos));
                        } // End if (pos != -1)
                    }     // Whend
                }         // End Using reader
            }             // Next i

            return(searchResults);
        } // End Function SearchContent
Пример #3
0
        public IActionResult Search(string searchPhrase, decimal?minPrice, decimal?maxPrice,
                                    Market?market, OfferType offerType, int?minRoomCount, int?maxRoomCount,
                                    int?minArea, int?maxArea,
                                    int page = 1)
        {
            var searchArguments = new SearchArguments()
            {
                MaxPrice     = maxPrice,
                MinPrice     = minPrice,
                Page         = page,
                SearchPhrase = searchPhrase,
                OfferType    = offerType,
                MinArea      = minArea,
                MaxRoomCount = maxRoomCount,
                MinRoomCount = minRoomCount,
                Market       = market == Market.Both ? null : market,
                MaxArea      = maxArea
            };
            var offers    = _offerService.SearchOffers(searchArguments);
            var offerDtos = new List <OfferDto>();

            foreach (var offer in offers)
            {
                var offerDto = _mapper.Map <OfferDto>(offer);
                offerDto.Images = CreateUrlsToPhotos(offer.Images);
                offerDtos.Add(offerDto);
            }
            return(Ok(offerDtos));
        }
Пример #4
0
 public void SetArguments(SearchArguments args)
 {
     isArgsInitialized = true;
     if (IsSearching)
     {
         throw new Exception("Search was not ended");
     }
     this.Arguments = args;
 }
Пример #5
0
 private void HookThingsUp()
 {
     argumentsBindingSource.DataSource = arguments =
         new SearchArguments("C:\\", "*", string.Empty);
     SearchWorker.SearchProgressed += new SearchWorker.SearchProgressHandler(SearchWorker_SearchProgressed);
     SearchWorker.ResultFound      += new SearchWorker.ResultFoundHandler(SearchWorker_ResultFound);
     SearchWorker.StateChanged     += new SearchWorker.StateChangedHandler(SearchWorker_StateChanged);
     SearchWorker.SearchError      += new SearchWorker.SearchErrorHandler(SearchWorker_SearchError);
 }
Пример #6
0
 private void HookThingsUp()
 {
     argumentsBindingSource.DataSource = arguments =
     new SearchArguments("C:\\", "*", string.Empty);
       SearchWorker.SearchProgressed += new SearchWorker.SearchProgressHandler(SearchWorker_SearchProgressed);
       SearchWorker.ResultFound += new SearchWorker.ResultFoundHandler(SearchWorker_ResultFound);
       SearchWorker.StateChanged += new SearchWorker.StateChangedHandler(SearchWorker_StateChanged);
       SearchWorker.SearchError += new SearchWorker.SearchErrorHandler(SearchWorker_SearchError);
 }
Пример #7
0
        public HttpResponseMessage GetSearch([FromUri] SearchViewModel searchViewModel)
        {
            SearchArguments searchArguments = _searchModelConverter.GetModel(searchViewModel, User.Id);

            SearchResult result = _searchService.Search(searchArguments);

            var resultViewModel = new SearchResultViewModel
            {
                Items            = result.Value.Select(found => _searchModelConverter.GetViewModel(found)),
                SearchCacheToken = result.SearchCacheToken
            };

            return(Request.CreateResponse(HttpStatusCode.OK, resultViewModel));
        }
Пример #8
0
        private static string GetLinqExpression(string filterExpressionCompare, SearchArguments args, bool caseSensitive, Type dataType)
        {
            string str          = caseSensitive ? args.SearchString : args.SearchString.ToLower();
            string searchColumn = args.SearchColumn;

            if (((dataType != null) && (dataType == typeof(string))) && !caseSensitive)
            {
                searchColumn = string.Format("{0}.ToLower()", args.SearchColumn);
            }
            switch (args.SearchOperation)
            {
            case SearchOperation.IsEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, "=", str));

            case SearchOperation.IsNotEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, "<>", str));

            case SearchOperation.IsLessThan:
                return(string.Format(filterExpressionCompare, searchColumn, "<", str));

            case SearchOperation.IsLessOrEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, "<=", str));

            case SearchOperation.IsGreaterThan:
                return(string.Format(filterExpressionCompare, searchColumn, ">", str));

            case SearchOperation.IsGreaterOrEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, ">=", str));

            case SearchOperation.BeginsWith:
                return(string.Format("{0}.StartsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.DoesNotBeginWith:
                return(string.Format("!{0}.StartsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.EndsWith:
                return(string.Format("{0}.EndsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.DoesNotEndWith:
                return(string.Format("!{0}.EndsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.Contains:
                return(string.Format("{0}.Contains(\"{1}\")", searchColumn, str));

            case SearchOperation.DoesNotContain:
                return(string.Format("!{0}.Contains(\"{1}\")", searchColumn, str));
            }
            throw new Exception("Invalid search operation.");
        }
Пример #9
0
 public static string GetWhereClause(JQGrid grid, string filters)
 {
     JsonMultipleSearch search = new JavaScriptSerializer().Deserialize<JsonMultipleSearch>(filters);
     string str = "";
     foreach (MultipleSearchRule rule in search.rules)
     {
         SearchArguments args = new SearchArguments {
             SearchColumn = rule.field,
             SearchString = rule.data,
             SearchOperation = GetSearchOperationFromString(rule.op)
         };
         string str2 = (str.Length > 0) ? (" " + search.groupOp + " ") : "";
         str = str + str2 + ConstructLinqFilterExpression(grid, args);
     }
     return str;
 }
Пример #10
0
        public static string GetWhereClause(CoreGrid grid, string searchField, string searchString, string searchOper)
        {
            string          text      = " && ";
            string          text2     = "";
            Hashtable       hashtable = new Hashtable();
            SearchArguments args      = new SearchArguments
            {
                SearchColumn    = searchField,
                SearchString    = searchString,
                SearchOperation = GetSearchOperationFromString(searchOper)
            };
            string str  = (text2.Length > 0) ? text : "";
            string str2 = ConstructLinqFilterExpression(grid, args);

            return(text2 + str + str2);
        }
Пример #11
0
        public static string GetWhereClause(JQGrid grid, string searchField, string searchString, string searchOper)
        {
            string str  = " && ";
            string str2 = "";

            new Hashtable();
            SearchArguments arguments2 = new SearchArguments();

            arguments2.SearchColumn    = searchField;
            arguments2.SearchString    = searchString;
            arguments2.SearchOperation = GetSearchOperationFromString(searchOper);
            SearchArguments args = arguments2;
            string          str3 = (str2.Length > 0) ? str : "";
            string          str4 = ConstructLinqFilterExpression(grid, args);

            return(str2 + str3 + str4);
        }
Пример #12
0
        public static string GetWhereClause(JQGrid grid, string filters)
        {
            JsonMultipleSearch search = new JavaScriptSerializer().Deserialize <JsonMultipleSearch>(filters);
            string             str    = "";

            foreach (MultipleSearchRule rule in search.rules)
            {
                SearchArguments arguments2 = new SearchArguments();
                arguments2.SearchColumn    = rule.field;
                arguments2.SearchString    = rule.data;
                arguments2.SearchOperation = GetSearchOperationFromString(rule.op);
                SearchArguments args = arguments2;
                string          str2 = (str.Length > 0) ? (" " + search.groupOp + " ") : "";
                str = str + str2 + ConstructLinqFilterExpression(grid, args);
            }
            return(str);
        }
Пример #13
0
        public async Task SearchSucceeds()
        {
            var args = new SearchArguments {
                ExactMatch = false, FindString = "de heer", PageIndex = 0, PageSize = 10
            };

            kitabDb.ActivePublications = new [] { "AB" };
            var page = 0;
            Response <string> results = null;
            var totalC = 0;
            var start  = Environment.TickCount;

            while (page >= 0)
            {
                args.PageIndex = page++;
                results        = await kitabDb.Search(args);

                totalC += results.Data.Count();
                if (!results.Data.Any())
                {
                    break;
                }
            }
            Assert.IsNotNull(results, "Search should have a result");
            Assert.AreEqual(totalC, 632, "Search should ahve a result");
            Debug.WriteLine("searching using paging took {0}ms", Environment.TickCount - start);

            page           = 0;
            args.PageSize  = totalC;
            args.PageIndex = 0;
            totalC         = 0;
            start          = Environment.TickCount;
            while (page >= 0)
            {
                args.PageIndex = page++;
                results        = await kitabDb.Search(args);

                totalC += results.Data.Count();
                if (!results.Data.Any())
                {
                    break;
                }
            }
            Debug.WriteLine("searching using paging took {0}ms", Environment.TickCount - start);
        }
 public int SearchResultCount(BaristaIndexDefinition indexDefinition, SearchArguments arguments)
 {
     try
     {
         using (var searchClient = GetSearchClient())
         {
             return(searchClient.SearchResultCount(indexDefinition, arguments));
         }
     }
     catch (CommunicationObjectFaultedException ex)
     {
         if (ex.InnerException != null)
         {
             throw ex.InnerException;
         }
         throw;
     }
 }
Пример #15
0
        public static string GetWhereClause(CoreGrid grid, string filters)
        {
            JsonMultipleSearch jsonMultipleSearch = JsonConvert.DeserializeObject <JsonMultipleSearch>(filters);
            string             text = "";

            foreach (MultipleSearchRule rule in jsonMultipleSearch.rules)
            {
                SearchArguments args = new SearchArguments
                {
                    SearchColumn    = rule.field,
                    SearchString    = rule.data,
                    SearchOperation = GetSearchOperationFromString(rule.op)
                };
                string str = (text.Length > 0) ? (" " + jsonMultipleSearch.groupOp + " ") : "";
                text = text + str + ConstructLinqFilterExpression(grid, args);
            }
            return(text);
        }
        private void backgroundWorkerFind_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (this.Dispatcher.CheckAccess() == false)
            {
                this.Dispatcher.Invoke(new backgroundWorkerFind_RunWorkerCompletedDelegate(backgroundWorkerFind_RunWorkerCompleted), new object[] { sender, e });
            }
            else
            {
                try
                {
                    if (e.Error != null)
                    {
                        ModernDialog.ShowMessage(e.Error.Message, "Error setting Log", MessageBoxButton.OK);
                    }
                    else
                    {
                        SearchArguments arg = e.Result as SearchArguments;

                        Dictionary <string, string> view = new Dictionary <string, string>();

                        List <string> staticComponentList;
                        foreach (KeyValuePair <string, List <string> > item in arg.ComponentDictionary)
                        {
                            staticComponentList = this.GetStaticComponentList(item.Key, arg.ComponentDictionary);
                            staticComponentList.Sort();

                            view.Add(item.Key, string.Join("; ", staticComponentList));
                        }

                        dataGridComponentTable.ItemsSource = view;
                    }
                }
                catch (Exception ex)
                {
                    ModernDialog.ShowMessage(ex.Message, "Error", MessageBoxButton.OK);
                }
                finally
                {
                    buttonShow.Content    = "Show";
                    buttonUnion.IsEnabled = true;
                }
            }
        }
        public async Task <ProductsSearchResult> SearchForProducts(SearchArguments args = null)
        {
            var config = _getConfiguration();

            string facetsFilter = null;

            if (args?.FacetValues?.Any() ?? false)
            {
                facetsFilter = string.Join(" and ", args?.FacetValues?.Select(GenerateFacetFilterString).ToArray());
            }

            var searchParameters = new SearchParameters {
                SearchMode = SearchMode.Any,
                IncludeTotalResultCount = true,
                HighlightFields         = config.HighlightFields?.ToList(),
                Skip   = (int)args?.SkipAmount,
                Facets = config.ProductFacets?.Select(GenerateFacetString).ToList(),
                Filter = facetsFilter,
                Top    = args?.PageSize
            };

            var productsResult = await _searchClient.Documents.SearchAsync <AWProduct>(args?.FilterText, searchParameters);

            var pageProducts = productsResult.Results.Select(productResult => new ProductHitResult {
                Product           = productResult.Document,
                HitHighlightsHtml = productResult.Highlights?.SelectMany(x => x.Value)
            }).ToArray();
            var productFacets = productsResult.Facets.Select(facet => {
                var facetName    = facet.Key;
                var friendlyName = GetFacetFriendlyName(facet.Key);
                var values       = facet.Value.Select(value => GetFacetValue(facet.Key, value));
                return(new FacetsHit(facetName, friendlyName, values));
            }).ToArray();

            var searchResult = new ProductsSearchResult {
                ProductHits  = pageProducts,
                Facets       = productFacets,
                ResultsCount = productsResult.Count ?? 0L,
                SkipCount    = args?.SkipAmount ?? 0L
            };

            return(searchResult);
        }
Пример #18
0
        public IEnumerable <Core.Models.Domain.Offer> Search(SearchArguments searchArguments)
        {
            var searchResponse = _elasticClient.Search <Offer>(s => s
                                                               .Query(q => q
                                                                      .Bool(b => b
                                                                            .Must(mu => mu
                                                                                  .Match(m => m
                                                                                         .Field(f => f.Title)
                                                                                         .Query(searchArguments.SearchPhrase)
                                                                                         ), mu => mu
                                                                                  .Match(m => m
                                                                                         .Field(f => f.Description)
                                                                                         .Query(searchArguments.SearchPhrase)
                                                                                         )
                                                                                  )
                                                                            .Filter(fi => fi.Range(r => r
                                                                                                   .Field(f => f.Price)
                                                                                                   .GreaterThanOrEquals((double?)searchArguments.MinPrice)
                                                                                                   .LessThanOrEquals((double?)searchArguments.MaxPrice))
                                                                                    ,
                                                                                    fi => fi.Range(r => r
                                                                                                   .Field(f => f.Area)
                                                                                                   .GreaterThanOrEquals(searchArguments.MinArea)
                                                                                                   .LessThanOrEquals(searchArguments.MaxArea))
                                                                                    ,
                                                                                    fi => fi.Range(r => r
                                                                                                   .Field(f => f.RoomCount)
                                                                                                   .GreaterThanOrEquals(searchArguments.MinRoomCount)
                                                                                                   .LessThanOrEquals(searchArguments.MaxRoomCount))
                                                                                    ,
                                                                                    bs => bs.Term(p => p.Market, searchArguments.Market)
                                                                                    ,
                                                                                    bs => bs.Term(p => p.OfferType, searchArguments.OfferType)

                                                                                    )))
                                                               .From((searchArguments.Page - 1) * PageSize)
                                                               .Size(PageSize));

            var offers = _mapper.Map <IEnumerable <Core.Models.Domain.Offer> >(searchResponse.Documents);

            return(offers);
        }
Пример #19
0
        private static string ConstructLinqFilterExpression(JQGrid grid, SearchArguments args)
        {
            JQGridColumn column = grid.Columns.Find(delegate(JQGridColumn c) {
                return(c.DataField == args.SearchColumn);
            });

            if (column.DataType == null)
            {
                throw new DataTypeNotSetException("JQGridColumn.DataType must be set in order to perform search operations.");
            }
            string filterExpressionCompare = (column.DataType == typeof(string)) ? "{0} {1} \"{2}\"" : "{0} {1} {2}";

            if (column.DataType == typeof(DateTime))
            {
                DateTime time = DateTime.Parse(args.SearchString);
                string   str2 = string.Format("({0},{1},{2})", time.Year, time.Month, time.Day);
                filterExpressionCompare = "{0} {1} DateTime" + str2;
            }
            return(string.Format("{0} != null AND ", args.SearchColumn) + GetLinqExpression(filterExpressionCompare, args, column.SearchCaseSensitive, column.DataType));
        }
Пример #20
0
        public string Search(SearchArguments args)
        {
            string token = GetToken();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                $"{BaseUrl}/v1/search?q={Uri.EscapeDataString(args.Query)}" +
                $"&limit={args.MaxItems}&type={args.Filters}");

            request.Method = WebRequestMethods.Http.Get;
            request.Accept = "application/json";
            request.Headers["Authorization"] = "Bearer " + token;

            string responseJson;

            using (var response = (HttpWebResponse)request.GetResponse())
                using (var sr = new StreamReader(response.GetResponseStream()))
                    responseJson = sr.ReadToEnd();

            return(responseJson);
        }
Пример #21
0
        //internal static string ConstructLinqFilterExpression(CoreGrid grid, SearchArguments args)
        //{
        //    CoreColumn coreColumn = grid.Columns.Find((CoreColumn c) => c.DataField == args.SearchColumn);
        //    if (coreColumn.DataType == null)
        //    {
        //        throw new DataTypeNotSetException("CoreGridColumn.DataType must be set in order to perform search operations.");
        //    }

        //    string filterExpressionCompare = ((coreColumn.DataType == typeof(string)) ? true : false) ? "{0} {1} \"{2}\"" : "{0} {1} {2}";
        //    if (coreColumn.DataType == typeof(DateTime))
        //    {
        //        DateTime dateTime = DateTime.Parse(args.SearchString);
        //        string str = $"({dateTime.Year},{dateTime.Month},{dateTime.Day})";
        //        filterExpressionCompare = "{0} {1} DateTime" + str;
        //    }
        //    string str2 = $"{args.SearchColumn} != null AND ";
        //    return str2 + GetLinqExpression(filterExpressionCompare, args, coreColumn.SearchCaseSensitive, coreColumn.DataType);
        //}

        //private static string GetLinqExpression(string filterExpressionCompare, SearchArguments args, bool caseSensitive, Type dataType)
        //{
        //    string text = caseSensitive ? args.SearchString : args.SearchString.ToLower();
        //    string arg = args.SearchColumn;
        //    if (dataType != null && dataType == typeof(string) && !caseSensitive)
        //    {
        //        arg = $"{args.SearchColumn}.ToLower()";
        //    }
        //    switch (args.SearchOperation)
        //    {
        //        case SearchOperation.IsEqualTo:
        //            return string.Format(filterExpressionCompare, arg, "=", text);
        //        case SearchOperation.IsNotEqualTo:
        //            return string.Format(filterExpressionCompare, arg, "<>", text);
        //        case SearchOperation.IsLessOrEqualTo:
        //            return string.Format(filterExpressionCompare, arg, "<=", text);
        //        case SearchOperation.IsLessThan:
        //            return string.Format(filterExpressionCompare, arg, "<", text);
        //        case SearchOperation.IsGreaterOrEqualTo:
        //            return string.Format(filterExpressionCompare, arg, ">=", text);
        //        case SearchOperation.IsGreaterThan:
        //            return string.Format(filterExpressionCompare, arg, ">", text);
        //        case SearchOperation.BeginsWith:
        //            return $"{arg}.StartsWith(\"{text}\")";
        //        case SearchOperation.Contains:
        //            return $"{arg}.Contains(\"{text}\")";
        //        case SearchOperation.EndsWith:
        //            return $"{arg}.EndsWith(\"{text}\")";
        //        case SearchOperation.DoesNotBeginWith:
        //            return $"!{arg}.StartsWith(\"{text}\")";
        //        case SearchOperation.DoesNotContain:
        //            return $"!{arg}.Contains(\"{text}\")";
        //        case SearchOperation.DoesNotEndWith:
        //            return $"!{arg}.EndsWith(\"{text}\")";
        //        default:
        //            throw new Exception("Invalid search operation.");
        //    }
        //}

        #endregion

        #region Старая версия

        internal static string ConstructLinqFilterExpression(CoreGrid grid, SearchArguments args)
        {
            var column = grid.Columns.Find(c => c.DataField == args.SearchColumn);

            if (column.DataType == null)
            {
                throw new DataTypeNotSetException("CoreGridColumn.DataType must be set in order to perform search operations.");
            }

            if (!string.IsNullOrEmpty(column.SearchDataField))
            {
                args.SearchColumn = column.SearchDataField;
                if (grid.Columns.Any(c => c.DataField == args.SearchColumn))
                {
                    return(ConstructLinqFilterExpression(grid, args));
                }
            }

            string filterExpressionCompare = (column.DataType == typeof(string)) ? "{0} {1} \"{2}\"" : "{0} {1} {2}";

            return(string.Format("{0} != null AND ", args.SearchColumn) + GetLinqExpression(filterExpressionCompare, args, column.SearchCaseSensitive, column.DataType));
        }
Пример #22
0
 public static string GetWhereClause(JQGrid grid, NameValueCollection queryString)
 {
     string str = " && ";
     string str2 = "";
     new Hashtable();
     foreach (JQGridColumn column in grid.Columns)
     {
         string str3 = queryString[column.DataField];
         if (!string.IsNullOrEmpty(str3))
         {
             SearchArguments args = new SearchArguments {
                 SearchColumn = column.DataField,
                 SearchString = str3,
                 SearchOperation = column.SearchToolBarOperation
             };
             string str4 = (str2.Length > 0) ? str : "";
             string str5 = ConstructLinqFilterExpression(grid, args);
             str2 = str2 + str4 + str5;
         }
     }
     return str2;
 }
Пример #23
0
        // /root/github/RedmineMailService/RedmineMailService/Redmine/API.cs (132):   , SecretManager.GetSecret<string>("RedmineSuperUser")
        // /root/github/RedmineMailService/RedmineMailService/Redmine/API.cs (133):   , SecretManager.GetSecret<string>("RedmineSuperUserPassword")
        // /root/github/SchemaPorter/SchemaPorter/FileSearch.cs (55):                    if (line.IndexOf("RedmineSuperUser") != -1)
        // /root/github/CorMine/RedmineClient/RedmineFactory.cs (43):                 , TestPlotly.SecretManager.GetSecret<string>("RedmineSuperUser")
        // /root/github/CorMine/RedmineClient/RedmineFactory.cs (44):                 , TestPlotly.SecretManager.GetSecret<string>("RedmineSuperUserPassword")
        // /root/github/CorMine/CorMine/AppCode/RedmineFactory.cs (42):               , SecretManager.GetSecret<string>("RedmineSuperUser")
        // /root/github/CorMine/CorMine/AppCode/RedmineFactory.cs (43):               , SecretManager.GetSecret<string>("RedmineSuperUserPassword")


        // SchemaPorter.FileSearch.Test();
        public static void Test()
        {
            string path = @"/root/github";

            path = @"D:\username\Documents\Visual Studio 2017\Projects";
            string searchTerm = @"RedmineSuperUser";
            string pattern    = "*.cs";

            SearchArguments searchArguments = new SearchArguments()
            {
                LookIn         = path,
                FileName       = pattern,
                ContainingText = searchTerm
            };

            System.Collections.Generic.List <SearchResult> ls = SearchContent(searchArguments);

            for (int j = 0; j < ls.Count; ++j)
            {
                System.Console.WriteLine(ls[j].File + " (" + ls[j].LineNumber.ToString() + "):\t" + ls[j].Line);
            } // Next j
        }     // End Sub Test
Пример #24
0
        public static string GetWhereClause(CoreGrid grid, Dictionary <string, string> queryString)
        {
            string    text      = " && ";
            string    text2     = "";
            Hashtable hashtable = new Hashtable();

            foreach (CoreColumn column in grid.Columns)
            {
                if (queryString.TryGetValue(column.DataField, out string value))
                {
                    SearchArguments args = new SearchArguments
                    {
                        SearchColumn    = column.DataField,
                        SearchString    = value,
                        SearchOperation = column.SearchToolBarOperation
                    };
                    string str  = (text2.Length > 0) ? text : "";
                    string str2 = ConstructLinqFilterExpression(grid, args);
                    text2 = text2 + str + str2;
                }
            }
            return(text2);
        }
Пример #25
0
        public static string GetWhereClause(JQGrid grid, NameValueCollection queryString)
        {
            string str  = " && ";
            string str2 = "";

            new Hashtable();
            foreach (JQGridColumn column in grid.Columns)
            {
                string str3 = queryString[column.DataField];
                if (!string.IsNullOrEmpty(str3))
                {
                    SearchArguments arguments2 = new SearchArguments();
                    arguments2.SearchColumn    = column.DataField;
                    arguments2.SearchString    = str3;
                    arguments2.SearchOperation = column.SearchToolBarOperation;
                    SearchArguments args = arguments2;
                    string          str4 = (str2.Length > 0) ? str : "";
                    string          str5 = ConstructLinqFilterExpression(grid, args);
                    str2 = str2 + str4 + str5;
                }
            }
            return(str2);
        }
 private void buttonFind_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (backgroundWorkerFind.IsBusy == false &&
             buttonFind.Content.ToString() == "Find")
         {
             SearchArguments arg = new SearchArguments(textBoxPath.Text, textBoxPattern.Text);
             buttonFind.Content      = "Cancel";
             progressBarSearch.Value = 0;
             textBoxLog.Text         = "Stating Log!\r\n";
             backgroundWorkerFind.RunWorkerAsync(arg);
         }
         else if (buttonFind.Content.ToString() == "Cancel")
         {
             backgroundWorkerFind.CancelAsync();
         }
     }
     catch (Exception ex)
     {
         ModernDialog.ShowMessage(ex.Message, "Error", MessageBoxButton.OK);
     }
 }
        private void buttonShow_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (backgroundWorkerFind.IsBusy == false &&
                    buttonShow.Content.ToString() == "Show")
                {
                    SearchArguments arg = new SearchArguments(Properties.Settings.Default.ServerUri);
                    progressBarSearch.Value = 0;
                    buttonShow.Content      = "Cancel";
                    buttonUnion.IsEnabled   = false;

                    backgroundWorkerFind.RunWorkerAsync(arg);
                }
                else if (buttonShow.Content.ToString() == "Cancel")
                {
                    backgroundWorkerFind.CancelAsync();
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage(ex.Message, "Error", MessageBoxButton.OK);
            }
        }
        private SearchArguments CoerceSearchArguments(object query, object maxResults, object groupByFields)
        {
            var args = new Barista.Search.SearchArguments();

            if (query == null || query == Null.Value || query == Undefined.Value)
            {
                args.Query = new MatchAllDocsQuery();
                if (maxResults != Undefined.Value && maxResults != Null.Value && maxResults != null)
                {
                    args.Take = JurassicHelper.GetTypedArgumentValue(Engine, maxResults, DefaultMaxResults);
                }
            }
            else if (TypeUtilities.IsString(query))
            {
                args.Query = new QueryParserQuery
                {
                    Query = TypeConverter.ToString(query)
                };

                if (maxResults != Undefined.Value && maxResults != Null.Value && maxResults != null)
                {
                    args.Take = JurassicHelper.GetTypedArgumentValue(Engine, maxResults, DefaultMaxResults);
                }

                if (groupByFields != null && groupByFields != Undefined.Value && groupByFields != Null.Value &&
                    groupByFields is ArrayInstance)
                {
                    args.GroupByFields = ((ArrayInstance)groupByFields)
                                         .ElementValues
                                         .Select(t => TypeConverter.ToString(t))
                                         .ToList();
                }
            }
            else
            {
                var instance = query as SearchArgumentsInstance;
                if (instance != null)
                {
                    var searchArgumentsInstance = instance;
                    args = searchArgumentsInstance.GetSearchArguments();
                }
                else if (query.GetType().IsAssignableFrom(typeof(IQuery <>)))
                {
                    args = new SearchArguments();

                    var pi = typeof(IQuery <>).GetProperty("Query");
                    args.Query = (Query)pi.GetValue(query, null);
                }
                else
                {
                    var obj = query as ObjectInstance;
                    if (obj != null)
                    {
                        var argumentsObj = obj;

                        args = new SearchArguments();

                        //Duck Type for the win
                        if (argumentsObj.HasProperty("query"))
                        {
                            var queryObj     = argumentsObj["query"];
                            var queryObjType = queryObj.GetType();

                            var queryProperty = queryObjType.GetProperty("Query", BindingFlags.Instance | BindingFlags.Public);
                            if (queryProperty != null && typeof(Query).IsAssignableFrom(queryProperty.PropertyType))
                            {
                                args.Query = queryProperty.GetValue(queryObj, null) as Query;
                            }
                        }
                        else
                        {
                            var queryObjType = obj.GetType();

                            var queryProperty = queryObjType.GetProperty("Query", BindingFlags.Instance | BindingFlags.Public);
                            if (queryProperty != null && typeof(Query).IsAssignableFrom(queryProperty.PropertyType))
                            {
                                args.Query = queryProperty.GetValue(obj, null) as Query;
                            }

                            if (maxResults != Undefined.Value && maxResults != Null.Value && maxResults != null)
                            {
                                args.Take = JurassicHelper.GetTypedArgumentValue(Engine, maxResults, DefaultMaxResults);
                            }
                        }

                        if (argumentsObj.HasProperty("filter"))
                        {
                            var filterObj     = argumentsObj["filter"];
                            var filterObjType = filterObj.GetType();

                            var filterProperty = filterObjType.GetProperty("Filter", BindingFlags.Instance | BindingFlags.Public);
                            if (filterProperty != null && typeof(Filter).IsAssignableFrom(filterProperty.PropertyType))
                            {
                                args.Filter = filterProperty.GetValue(filterObj, null) as Filter;
                            }
                        }

                        if (argumentsObj.HasProperty("groupByFields"))
                        {
                            var groupByFieldsValue = argumentsObj["groupByFields"] as ArrayInstance;
                            if (groupByFieldsValue != null)
                            {
                                args.GroupByFields = groupByFieldsValue
                                                     .ElementValues
                                                     .Select(t => TypeConverter.ToString(t))
                                                     .ToList();
                            }
                        }

                        if (argumentsObj.HasProperty("sort") && argumentsObj["sort"] is SortInstance)
                        {
                            var sortValue = (SortInstance)argumentsObj["sort"];
                            args.Sort = sortValue.Sort;
                        }

                        if (argumentsObj.HasProperty("skip"))
                        {
                            var skipObj = argumentsObj["skip"];
                            args.Skip = TypeConverter.ToInteger(skipObj);
                        }

                        if (argumentsObj.HasProperty("take"))
                        {
                            var takeObj = argumentsObj["take"];
                            args.Take = TypeConverter.ToInteger(takeObj);
                        }
                    }
                    else
                    {
                        throw new JavaScriptException(Engine, "Error", "Unable to determine the search arguments.");
                    }
                }
            }

            return(args);
        }
Пример #29
0
        internal static string ConstructLinqFilterExpression(CoreAutoComplete autoComplete, SearchArguments args)
        {
            Guard.IsNotNull(autoComplete.DataField, "DataField", "must be set in order to perform search operations. If you get this error from search/export method, make sure you setup(initialize) the grid again prior to filtering/exporting.");
            string filterExpressionCompare = "{0} {1} \"{2}\"";

            return(GetLinqExpression(filterExpressionCompare, args, false, typeof(string)));
        }
Пример #30
0
        private static string GetLinqExpression(string filterExpressionCompare, SearchArguments args, bool caseSensitive, Type dataType)
        {
            string str          = caseSensitive ? args.SearchString : args.SearchString.ToLower();
            string searchColumn = args.SearchColumn;

            if (((dataType != null) && (dataType == typeof(string))) && !caseSensitive)
            {
                searchColumn = string.Format("{0}.ToLower()", args.SearchColumn);
            }

            if (((dataType != null) && ((dataType == typeof(DateTime)) || (dataType == typeof(DateTime?)))))
            {
                DateTime time  = DateTime.Parse(args.SearchString);
                DateTime time2 = time.AddDays(1);

                if (args.SearchOperation == SearchOperation.IsEqualTo) //берем текущую дату и след день - промежуток между ними - для поиска, если дата содержит минуты и часы
                {
                    filterExpressionCompare =
                        String.Format("{0} >= DateTime({1},{2},{3}) AND {0} < DateTime({4},{5},{6})",
                                      args.SearchColumn, time.Year, time.Month, time.Day,
                                      time2.Year, time2.Month, time2.Day);
                    return(filterExpressionCompare);
                }

                if (args.SearchOperation == SearchOperation.IsGreaterThan)
                {
                    filterExpressionCompare =
                        String.Format("{0} >= DateTime({1},{2},{3})",
                                      args.SearchColumn, time2.Year, time2.Month, time2.Day);
                    return(filterExpressionCompare);
                }

                string str2 = string.Format("({0},{1},{2})", time.Year, time.Month, time.Day);
                filterExpressionCompare = "{0} {1} DateTime" + str2;
            }

            switch (args.SearchOperation)
            {
            case SearchOperation.IsEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, "=", str.Replace("\"", "\"\"")));   //добавляем двойные кавычки, чтобы искало в поиске, если строка содержит двойные кавычки


            case SearchOperation.IsNotEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, "<>", str));

            case SearchOperation.IsLessThan:
                return(string.Format(filterExpressionCompare, searchColumn, "<", str));

            case SearchOperation.IsLessOrEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, "<=", str));

            case SearchOperation.IsGreaterThan:
                return(string.Format(filterExpressionCompare, searchColumn, ">", str));

            case SearchOperation.IsGreaterOrEqualTo:
                return(string.Format(filterExpressionCompare, searchColumn, ">=", str));

            case SearchOperation.BeginsWith:
                return(string.Format("{0}.StartsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.DoesNotBeginWith:
                return(string.Format("!{0}.StartsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.EndsWith:
                return(string.Format("{0}.EndsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.DoesNotEndWith:
                return(string.Format("!{0}.EndsWith(\"{1}\")", searchColumn, str));

            case SearchOperation.Contains:
                return(string.Format("{0}.Contains(\"{1}\")", searchColumn, str));

            case SearchOperation.DoesNotContain:
                return(string.Format("!{0}.Contains(\"{1}\")", searchColumn, str));

            case SearchOperation.IsIn:
            {
                return("(" + String.Join(" EJ ", str.Split('|').Select(z => searchColumn + "=\"" + z + "\"")) + ")");
            }
            }
            throw new Exception("Invalid search operation.");
        }
Пример #31
0
 private static string ConstructLinqFilterExpression(JQGrid grid, SearchArguments args)
 {
     JQGridColumn column = grid.Columns.Find(c => c.DataField == args.SearchColumn);
     if (column.DataType == null)
     {
         throw new DataTypeNotSetException("JQGridColumn.DataType must be set in order to perform search operations.");
     }
     string filterExpressionCompare = (column.DataType == typeof(string)) ? "{0} {1} \"{2}\"" : "{0} {1} {2}";
     if (column.DataType == typeof(DateTime))
     {
         DateTime time = DateTime.Parse(args.SearchString);
         string str2 = string.Format("({0},{1},{2})", time.Year, time.Month, time.Day);
         filterExpressionCompare = "{0} {1} DateTime" + str2;
     }
     return (string.Format("{0} != null AND ", args.SearchColumn) + GetLinqExpression(filterExpressionCompare, args, column.SearchCaseSensitive, column.DataType));
 }
Пример #32
0
 private static void Search(SearchArguments arguments)
 {
     try
       {
     Search(new DirectoryInfo(arguments.Folder), arguments);
       }
       catch (Exception ex)
       {
     state = SearchState.Stopping;
     if (SearchError != null)
       SearchError(ex);
       }
 }
Пример #33
0
        } // End Function SearchContent

        public static System.Collections.Generic.IEnumerable <SearchResult> SearchContent2(SearchArguments searchArguments)
        {
            foreach (string file in System.IO.Directory.EnumerateFiles(searchArguments.LookIn, searchArguments.FileName, System.IO.SearchOption.AllDirectories))
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(file))
                {
                    for (int lineNumber = 1; !reader.EndOfStream; ++lineNumber)
                    {
                        string line = reader.ReadLine();
                        int    pos  = line.IndexOf(searchArguments.ContainingText, System.StringComparison.OrdinalIgnoreCase);

                        if (pos != -1)
                        {
                            yield return(new SearchResult(file, line, lineNumber, pos));
                        } // End if (pos != -1)
                    }     // Whend
                }         // End Using reader
            }             // Next file
        }                 // End Function SearchContent
Пример #34
0
        }                 // End Function SearchContent

        public static System.Collections.Generic.IEnumerable <SearchResult> SearchAndReplace(SearchArguments searchArguments)
        {
            string modifiedFilesPath = @"D:\username\Desktop\Modified";

            foreach (string file in System.IO.Directory.EnumerateFiles(searchArguments.LookIn, searchArguments.FileName, System.IO.SearchOption.AllDirectories))
            {
                string fileName = System.IO.Path.GetFileName(file);

                string originalText = System.IO.File.ReadAllText(file);



                int pos = originalText.IndexOf(searchArguments.ContainingText, System.StringComparison.Ordinal);
                if (pos == -1)
                {
                    continue;
                }



                string newFileName = System.IO.Path.Combine(modifiedFilesPath, fileName);

                using (System.IO.FileStream fs = new System.IO.FileStream(newFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8))
                    {
                        // Warning: will report only first instance on LINE

                        using (System.IO.StringReader reader = new System.IO.StringReader(originalText))
                        {
                            string line = null;

                            for (int lineNumber = 1; (line = reader.ReadLine()) != null; ++lineNumber)
                            {
                                while ((pos = line.IndexOf(searchArguments.ContainingText, System.StringComparison.Ordinal)) != -1)
                                {
                                    yield return(new SearchResult(file, line, lineNumber, pos));

                                    line = line.Replace(searchArguments.ContainingText, searchArguments.ReplacementText); // Case-Sensitive !
                                    // line = line.Replace(searchArguments.ContainingText, searchArguments.ReplacementText, System.StringComparison.Ordinal);
                                } // Whend (pos != -1)

                                sw.WriteLine(line);
                            } // Whend
                        }     // End Using reader
                    }         // End Using sw
                }             // End Using fs



                //pos = -1;
                //System.Text.StringBuilder text = new System.Text.StringBuilder(originalText);
                //while ((pos = text.IndexOf(searchArguments.ContainingText, 0, false)) != -1)
                //{
                //    text = text.Replace(searchArguments.ContainingText, searchArguments.ReplacementText);
                //} // Whend
                // System.IO.File.WriteAllText(newFileName, text.ToString(), System.Text.Encoding.UTF8);
            } // Next file
        }     // End Function SearchContent
Пример #35
0
 public static string GetWhereClause(JQGrid grid, string searchField, string searchString, string searchOper)
 {
     string str = " && ";
     string str2 = "";
     new Hashtable();
     SearchArguments args = new SearchArguments {
         SearchColumn = searchField,
         SearchString = searchString,
         SearchOperation = GetSearchOperationFromString(searchOper)
     };
     string str3 = (str2.Length > 0) ? str : "";
     string str4 = ConstructLinqFilterExpression(grid, args);
     return (str2 + str3 + str4);
 }
Пример #36
0
 internal static string ConstructLinqFilterExpression(JQAutoComplete autoComplete, SearchArguments args)
 {
     Guard.IsNotNull(autoComplete.DataField, "DataField", "must be set in order to perform search operations. If you get this error from search/export method, make sure you setup(initialize) the grid again prior to filtering/exporting.");
     string filterExpressionCompare = "{0} {1} \"{2}\"";
     return GetLinqExpression(filterExpressionCompare, args, false, typeof(string));
 }
Пример #37
0
        private static string GetLinqExpression(string filterExpressionCompare, SearchArguments args, bool caseSensitive, Type dataType)
        {
            string str = caseSensitive ? args.SearchString : args.SearchString.ToLower();
            string searchColumn = args.SearchColumn;
            if (((dataType != null) && (dataType == typeof(string))) && !caseSensitive)
            {
                searchColumn = string.Format("{0}.ToLower()", args.SearchColumn);
            }
            switch (args.SearchOperation)
            {
                case SearchOperation.IsEqualTo:
                    return string.Format(filterExpressionCompare, searchColumn, "=", str);

                case SearchOperation.IsNotEqualTo:
                    return string.Format(filterExpressionCompare, searchColumn, "<>", str);

                case SearchOperation.IsLessThan:
                    return string.Format(filterExpressionCompare, searchColumn, "<", str);

                case SearchOperation.IsLessOrEqualTo:
                    return string.Format(filterExpressionCompare, searchColumn, "<=", str);

                case SearchOperation.IsGreaterThan:
                    return string.Format(filterExpressionCompare, searchColumn, ">", str);

                case SearchOperation.IsGreaterOrEqualTo:
                    return string.Format(filterExpressionCompare, searchColumn, ">=", str);

                case SearchOperation.BeginsWith:
                    return string.Format("{0}.StartsWith(\"{1}\")", searchColumn, str);

                case SearchOperation.DoesNotBeginWith:
                    return string.Format("!{0}.StartsWith(\"{1}\")", searchColumn, str);

                case SearchOperation.EndsWith:
                    return string.Format("{0}.EndsWith(\"{1}\")", searchColumn, str);

                case SearchOperation.DoesNotEndWith:
                    return string.Format("!{0}.EndsWith(\"{1}\")", searchColumn, str);

                case SearchOperation.Contains:
                    return string.Format("{0}.Contains(\"{1}\")", searchColumn, str);

                case SearchOperation.DoesNotContain:
                    return string.Format("!{0}.Contains(\"{1}\")", searchColumn, str);
            }
            throw new Exception("Invalid search operation.");
        }
Пример #38
0
        private static void Search(DirectoryInfo dir, SearchArguments arguments)
        {
            if (state != SearchState.Running)
            return;

              if (SearchProgressed != null)
            SearchProgressed(dir.FullName);

              try
              {
            FileInfo[] files = dir.GetFiles(arguments.NameSearch);

            foreach (FileInfo file in files)
            {
              if (state != SearchState.Running)
            return;

              if (string.IsNullOrEmpty(arguments.ContentSearch))
              {
            if (ResultFound != null)
              ResultFound(new SearchResult(file.FullName));

            continue;
              }
              else
              {
            try
            {
              string contentSearch = arguments.ContentSearch.ToLower();
              using (StreamReader sire = new StreamReader(file.FullName))
              {
                for (string line = sire.ReadLine();
                     line != null;
                     line = sire.ReadLine())
                {
                  if (state != SearchState.Running)
                    return;

                  if (line.ToLower().Contains(contentSearch))
                  {
                    if (ResultFound != null)
                      ResultFound(new SearchResult(file.FullName));

                    break;
                  }
                }
              }
            }
            catch (IOException) { }
              }
            }

            DirectoryInfo[] subDirs = dir.GetDirectories();
            foreach (DirectoryInfo subDir in subDirs)
            {
              Search(subDir, arguments);
            }
              }
              catch (UnauthorizedAccessException)
              {
            return;
              }
        }
Пример #39
0
        public static void StartSearch(SearchArguments arguments)
        {
            lock (searchLockObject)
              {
            if (state != SearchState.Ready)
              return;

            state = SearchState.Running;
            if (StateChanged != null)
              StateChanged(state, Transition.Started);
              }

              lastSearchThread = new Thread(delegate()
              {
            Search(arguments);
            SearchState stoppingState = state;
            state = SearchState.Ready;
            if (StateChanged != null)
              StateChanged(state, stoppingState == SearchState.Stopping ? Transition.Cancelled : Transition.Complete);
              });
              lastSearchThread.IsBackground = true;
              lastSearchThread.Start();
        }
Пример #40
0
        public SearchArguments GetSearchArguments()
        {
            var result = new SearchArguments();

            //Determine the Query value.
            if (this.Query == null || this.Query == Null.Value || this.Query == Undefined.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "The Query property of the argument instance cannot be null or undefined.");
            }

            var searchQueryType = this.Query.GetType();

            if (searchQueryType.IsSubclassOfRawGeneric(typeof(QueryInstance <>)))
            {
                var queryProperty = searchQueryType.GetProperty("Query", BindingFlags.Instance | BindingFlags.Public);
                result.Query = queryProperty.GetValue(this.Query, null) as Query;
            }
            else
            {
                var parser = new QueryParserQuery
                {
                    Query = TypeConverter.ToString(this.Query)
                };
                result.Query = parser;
            }

            //Determine the Filter value.

            var searchFilterType = this.Filter.GetType();

            if (searchFilterType.IsSubclassOfRawGeneric(typeof(FilterInstance <>)))
            {
                var filterProperty = searchFilterType.GetProperty("Filter", BindingFlags.Instance | BindingFlags.Public);
                result.Filter = filterProperty.GetValue(this.Filter, null) as Filter;
            }
            else
            {
                var parser = new QueryParserQuery
                {
                    Query = TypeConverter.ToString(this.Query)
                };
                result.Filter = new QueryWrapperFilter {
                    Query = parser
                };
            }

            //Determine the Sort value.
            if (this.Sort is SortInstance)
            {
                result.Sort = (this.Sort as SortInstance).Sort;
            }
            else if (TypeUtilities.IsString(this.Sort))
            {
                result.Sort = new Sort
                {
                    SortFields = new List <SortField>
                    {
                        new SortField
                        {
                            FieldName = this.Sort as string,
                            Type      = SortFieldType.String
                        }
                    }
                };
            }

            if (this.GroupByFields != null && this.GroupByFields.Length > 0)
            {
                result.GroupByFields = this.GroupByFields.ElementValues.Select(v => TypeConverter.ToString(v)).ToList();
            }

            if (Skip > 0)
            {
                result.Skip = this.Skip;
            }

            if (Take > 0)
            {
                result.Take = this.Take;
            }

            return(result);
        }