예제 #1
0
 public List<GrepSearchResult> Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
 {
     using (FileStream fileStream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         return Search(fileStream, file, searchPattern, searchType, searchOptions, encoding);
     }
 }
 //Attempts to click the element on the page, with specific and default exception handling
 public void Click(SearchType type, string text){
     try{
         if (type == SearchType.Id){
             WebDriver.FindElement(By.Id(text)).Click();
         }
         else if (type == SearchType.LinkText){
             WebDriver.FindElement(By.LinkText(text)).Click();
         }
         else if (type == SearchType.Name){
             WebDriver.FindElement(By.Name(text)).Click();
         }
         else if (type == SearchType.Xpath){
             WebDriver.FindElement(By.XPath(text)).Click();
         }
         else{
             System.Console.WriteLine(type.ToString() + " is an unsupported SearchType for this method.");
         }
     }
     catch (NoSuchElementException ex){
         System.Console.WriteLine("Error, could not find webElement of type " + type.ToString() + " with id {0}", text);
         System.Console.WriteLine(ex.ToString());
         return;
     }
     catch (Exception ex){
         System.Console.WriteLine("Unspecified exception in Click().");
         System.Console.WriteLine(ex.ToString());
         return;
     }
 }
 //Attempts to enter the given text string in a specific element on the page, with specific and default exception handling
 public void TextEntry(SearchType type, string searchText, string input)
 {
     try{
         IWebElement textField;
         if (type == SearchType.Id){
             textField = WebDriver.FindElement(By.Id(searchText));
         }
         else if (type == SearchType.LinkText){
             textField = WebDriver.FindElement(By.LinkText(searchText));
         }
         else if (type == SearchType.Name){
             textField = WebDriver.FindElement(By.Name(searchText));
         }
         else if (type == SearchType.Xpath){
             textField = WebDriver.FindElement(By.XPath(searchText));
         }
         else{
             textField = null;
             System.Console.WriteLine(type.ToString() + " is an unsupported SearchType for this method.");
         }
         textField.Clear();
         textField.SendKeys(input);
         System.Console.WriteLine("Text '{0}' entered successfully in '{1}'", input, searchText);
     }
     catch (NoSuchElementException ex){
         System.Console.WriteLine("Could not successfully enter text '{0}' in '{1}'", input, searchText);
         System.Console.WriteLine(ex.ToString());
         return;
     }
     catch (Exception ex){
         System.Console.WriteLine("Unspecified exception in TextEntry().");
         System.Console.WriteLine(ex.ToString());
         return;
     }
 }
예제 #4
0
        /// <summary>動画を検索するストリームを取得する</summary>
        /// <param name="Keyword">検索キーワード</param>
        /// <param name="SearchPage">検索ページの指定、1~nの間の数値を指定する</param>
        /// <param name="SearchType">検索方法を指定する</param>
        /// <param name="SearchOption">検索オプションを指定する</param>
        public Streams<Video.VideoInfoResponse> OpenSearchStreams(
            string          Keyword,
            int             SearchPage,
            SearchType      SearchType,
            SearchOption    SearchOption)
        {
            var serialize = new DataContractJsonSerializer(typeof(Serial.Search.Contract));
            var streamDataList = new List<StreamData>();
            Video.VideoInfoResponse lastData = null;

            streamDataList.Add(
                new StreamData()
                {
                    StreamType = StreamType.Read,
                    GetStream = () =>
                    {
                        return context.Client.OpenDownloadStream(
                            String.Format(
                                ApiUrls.VideoSearch,
                                SearchType.ToKey(),
                                Keyword,
                                SearchPage,
                                SearchOption.ToKey()));
                    },
                    SetReadData = (data) =>
                    {
                        lastData = converter.ConvertVideoInfoResponse(
                            (Serial.Search.Contract)serialize.ReadObject(new MemoryStream(data)));
                    }
                });

            return new Streams<Video.VideoInfoResponse>(
                streamDataList.ToArray(),
                () => lastData);
        }
예제 #5
0
		/// <summary>
		/// Creates a new form used to get input for a search
		/// </summary>
		/// <param name="type">The type of search</param>
		public SearchForm( SearchType type )
		{
			InitializeComponent();

			Pandora.Localization.LocalizeControl( this );

			if ( type != SearchType.Deco )
			{
				rID.Visible = false;
				rName.Visible = false;
			}

			switch ( type )
			{
				case SearchType.Deco:
				case SearchType.Item:

					Text = "Find Item";
					break;

				case SearchType.Location:

					Text = Pandora.Localization.TextProvider[ "Misc.FindLoc" ];
					break;

				case SearchType.Mobile:

					Text = Pandora.Localization.TextProvider[ "Misc.FindMob" ];
					break;
			}
		}
 /// <summary>
 /// Selects the person by search text.
 /// </summary>
 /// <param name="personsParty">The persons party.</param>
 /// <param name="searchText">The search text.</param>
 /// <param name="searchType">Type of the search.</param>
 /// <param name="visitorSearchType">Type of the visitor search.</param>
 /// <returns>Instance of PersonsParty</returns>
 internal static PersonsParty SelectPersonBySearchText(PersonsParty personsParty, string searchText, SearchType searchType, VisitorSearchType visitorSearchType)
 {
     if (visitorSearchType != VisitorSearchType.None)
     {
         AssignSelectedPerson(personsParty, personsParty.RetrievePersons().FirstOrDefault(), null);
     }
     else if (searchType == SearchType.LastName)
     {
         AssignSelectedPerson(personsParty, RetrievePersonByName(personsParty.RetrievePersons(), searchText).FirstOrDefault(), null);
     }
     else if (searchType == SearchType.Stateroom)
     {
         AssignSelectedPerson(personsParty, personsParty.RetrievePersons().FirstOrDefault(), null);
     }
     else if (searchType == SearchType.Reservation)
     {
         AssignSelectedPerson(personsParty, RetrievePersonByReservationNumber(personsParty.RetrievePersons(), searchText).FirstOrDefault(), null);
     }
     else if (searchType == SearchType.PassportNumber)
     {
         AssignSelectedPerson(personsParty, personsParty.RetrievePersons().FirstOrDefault(), null);
     }
     else if (searchType == SearchType.EmployeeNumber)
     {
         AssignSelectedPerson(personsParty, personsParty.RetrievePersons().FirstOrDefault(), null);
     }
     else if (searchType == SearchType.BarcodeScanning || searchType == SearchType.MagneticStripe || searchType == SearchType.RFID)
     {
         AssignSelectedPerson(personsParty, personsParty.RetrievePersons().FirstOrDefault(), null);
     }
     
     return personsParty;
 }
        /// <summary>
        /// Performs a breadth-first-search on the TreeView's nodes in search of the passed value. The matching conditions are based on the passed search type parameter.
        /// </summary>
        /// <param name="value">Value to search for in the TreeView. Matching on this value is based on the search type.</param>
        /// <param name="searchType">Determines the matching of the value. For example, full/partial text search or full path search.</param>
        /// <returns>A collection of nodes who match the conditions based on the search type.</returns>
        public IReadOnlyCollection<TreeNode> Search(string value, bool isCaseSensitive, SearchType searchType)
        {
            IReadOnlyCollection<TreeNode> results = new List<TreeNode>().AsReadOnly();

            // if the user is not choosing case sensitive, then lower everything so we clear out any case
            if(!isCaseSensitive) { value = value.ToLower(); }

            if(searchType == SearchType.FileNameExactMatch)
            {
                results = this.Nodes.Find(value, true).ToList();
            }
            else if(searchType == SearchType.FileNamePartialMatch)
            {
                Func<TreeNode, string, bool> matchFunction = (node, searchText) =>
                {
                    return node.Text.ToLower().Contains(searchText);
                };
                results = Search(value, matchFunction);
            }
            else if(searchType == SearchType.FullPath)
            {
                Func<TreeNode, string, bool> matchFunction = (node, searchText) =>
                {
                    return node.FullPath.ToLower().Contains(searchText);
                };
                results = Search(value, matchFunction);
            }

            return results;
        }
예제 #8
0
        public FormitizeCMSWhere addCriteria(string key, object value, SearchType searchType = SearchType.Equals)
        {
            string search = "equal";
            switch(searchType)
            {
                case SearchType.Equals:
                    search = "equal";
                    break;
                case SearchType.Contains:
                    search = "contain";
                    break;
                case SearchType.NotEquals:
                    search = "notequal";
                    break;
            }

            Dictionary<string, object> newVal = new Dictionary<string, object>();

            newVal["value"] = value;
            newVal["search"] = search;

            values[key] = newVal;

            return this;
        }
예제 #9
0
		public SearchTypeVM(SearchType searchType, string name, string toolTip, ImageReference imageReference, VisibleMembersFlags flags) {
			SearchType = searchType;
			Name = name;
			ToolTip = toolTip;
			Image = imageReference;
			Flags = flags;
		}
예제 #10
0
        public List<GrepSearchResult> Search(Stream input, string fileName, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
		{
			SearchDelegates.DoSearch searchMethod = doTextSearchCaseSensitive;
			switch (searchType)
			{
				case SearchType.PlainText:
                    if ((searchOptions & GrepSearchOption.CaseSensitive) == GrepSearchOption.CaseSensitive)
					{
						searchMethod = doTextSearchCaseSensitive;
					}
					else
					{
						searchMethod = doTextSearchCaseInsensitive;
					}
					break;
				case SearchType.Regex:
					searchMethod = doRegexSearch;
					break;
				case SearchType.XPath:
					searchMethod = doXPathSearch;
					break;
                case SearchType.Soundex:
                    searchMethod = doFuzzySearchMultiline;
                    break;
			}

			if ((searchOptions & GrepSearchOption.Multiline) == GrepSearchOption.Multiline || searchType == SearchType.XPath)
                return searchMultiline(input, fileName, searchPattern, searchOptions, searchMethod, encoding);
			else
				return search(input, fileName, searchPattern, searchOptions, searchMethod, encoding);
		}
예제 #11
0
        public SearchCriteria(string search)
        {
            if (string.IsNullOrEmpty(search))
            {
                throw new ArgumentNullException("search");
            }

            SearchType = SearchType.Unknown;

            if (StringHelper.IndexOfIgnoreCase(search, "upnp:class") != -1 &&
                StringHelper.IndexOfIgnoreCase(search, "derivedfrom") != -1)
            {
                if (StringHelper.IndexOfIgnoreCase(search, "object.item.audioItem") != -1)
                {
                    SearchType = SearchType.Audio;
                }
                else if (StringHelper.IndexOfIgnoreCase(search, "object.item.imageItem") != -1)
                {
                    SearchType = SearchType.Image;
                }
                else if (StringHelper.IndexOfIgnoreCase(search, "object.item.videoItem") != -1)
                {
                    SearchType = SearchType.Video;
                }
                else if (StringHelper.IndexOfIgnoreCase(search, "object.container.playlistContainer") != -1)
                {
                    SearchType = SearchType.Playlist;
                }
            }
        }
예제 #12
0
        /// <summary>動画を検索する</summary>
        /// <param name="Keyword">検索キーワード</param>
        /// <param name="SearchPage">検索ページの指定、1~nの間の数値を指定する</param>
        /// <param name="SearchType">検索方法を指定する</param>
        /// <param name="SearchOption">検索オプションを指定する、Filterメンバは無効</param>
        public Session<Response<VideoInfo[]>> Search(
            string Keyword,
            int SearchPage,
            SearchType SearchType,
            SearchOption SearchOption)
        {
            var session = new Session<Response<VideoInfo[]>>();

            session.SetAccessers(new Func<byte[], APIs.IAccesser>[]
            {
                (data) =>
                {
                    var accesser = new APIs.search.Accesser();
                    accesser.Setting(
                        context.CookieContainer,
                        SearchType.ToKey(),
                        Keyword,
                        SearchPage.ToString(),
                        SearchOption.SortOrder.ToKey(),
                        SearchOption.SortTarget.ToKey());

                    return accesser;
                }
            },
            (data) =>
                Converter.VideoInfoResponse(context, new APIs.search.Parser().Parse(data)));

            return session;
        }
        public static void LaunchSearch(string searchTerm, SearchType searchType)
        {
            if (!string.IsNullOrEmpty(searchTerm))
            {
                searchTerm = searchTerm.Replace(' ', '+');
                string str = string.Empty;
                switch (searchType)
                {
                    case SearchType.GOOGLE:
                        str = "http://www.google.com/search?q={0}";
                        break;

                    case SearchType.LINKEDIN:
                        str = "http://www.linkedin.com/search?pplSearchOrigin=GLHD&keywords={0}&search=";
                        break;

                    case SearchType.FACEBOOK:
                        str = "http://www.facebook.com/srch.php?nm={0}";
                        break;

                    case SearchType.TWITTER:
                        str = "http://twitter.com/search/users?q={0}&category=people&source=users";
                        break;
                }
                if (!string.IsNullOrEmpty(str))
                {
                    LaunchUrl(Uri.EscapeUriString(string.Format(CultureInfo.InvariantCulture, str, new object[] { searchTerm })));
                }
            }
        }
예제 #14
0
파일: CASCSearch.cs 프로젝트: Kruithne/W3DT
        private static void Explore(CASCFolder folder, string findFile, SearchType type, List<CASCFile> found)
        {
            foreach (KeyValuePair<string, ICASCEntry> node in folder.Entries)
            {
                ICASCEntry entry = node.Value;

                if (entry is CASCFolder)
                {
                    Explore((CASCFolder)entry, findFile, type, found);
                }
                else if (entry is CASCFile)
                {
                    CASCFile file = (CASCFile)entry;
                    string fileName = file.FullName.ToLower();

                    if (type == SearchType.COMPLETE && fileName.Equals(fileName))
                    {
                        found.Add(file);
                        break;
                    }

                    if (type == SearchType.STARTS_WITH && fileName.StartsWith(findFile))
                    {
                        found.Add(file);
                        continue;
                    }

                    if (type == SearchType.ENDS_WITH && fileName.EndsWith(findFile))
                    {
                        found.Add(file);
                        continue;
                    }
                }
            }
        }
예제 #15
0
 internal Search(SearchType searchMethod)
 {
     IsDone = false;
     NextKey = null;
     Matches = new List<Document>();
     SearchMethod = searchMethod;
 }
예제 #16
0
        public SearchCriteria(string search)
        {
            if (string.IsNullOrEmpty(search))
            {
                throw new ArgumentNullException("search");
            }

            SearchType = SearchType.Unknown;

            if (search.IndexOf("upnp:class", StringComparison.OrdinalIgnoreCase) != -1 &&
                search.IndexOf("derivedfrom", StringComparison.OrdinalIgnoreCase) != -1)
            {
                if (search.IndexOf("object.item.audioItem", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    SearchType = SearchType.Audio;
                }
                else if (search.IndexOf("object.item.imageItem", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    SearchType = SearchType.Image;
                }
                else if (search.IndexOf("object.item.videoItem", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    SearchType = SearchType.Video;
                }
                else if (search.IndexOf("object.container.playlistContainer", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    SearchType = SearchType.Playlist;
                }
            }
        }
    //--------------------------------------------------------------------------------------------------
    // メインウィンドウ左側描画領域.
    // 検索条件などを指定する領域.
    private void drawMainLeftElem()
    {
        EditorGUILayout.BeginVertical( GUI.skin.box, GUILayout.Width( MAIN_LEFT_ELEM_WIDTH ) );

        this.searchType = ( SearchType )EditorGUILayout.EnumPopup( "検索タイプ", this.searchType );
        this.searchScope = ( SearchScope )EditorGUILayout.EnumPopup( "検索範囲", this.searchScope );
        this.wholeWord = EditorGUILayout.Toggle( "完全一致か否か.", this.wholeWord );
        if ( !this.wholeWord )
            this.caseSencitive = EditorGUILayout.Toggle( "大小文字一致比較.", this.caseSencitive );

        switch ( this.searchType ){
            case SearchType.Name: EditorGUILayout.LabelField( "Input ObjectName" );	break;
            case SearchType.Component: EditorGUILayout.LabelField( "Input ComponentName" ); break;
            default: break;
        }
        this.searchText = EditorGUILayout.TextField( this.searchText, GUI.skin.textField );

        if ( GUILayout.Button( "Search" ) ){
            Debug.Log( "捜索します." );
            this.search();
        }

        MyEditorLayout.space( 3 );
        MyEditorLayout.separatorLine( MAIN_LEFT_ELEM_WIDTH );
        this.dumpFoldout = EditorGUILayout.Foldout( this.dumpFoldout, "Show Dump Palameter" );
        if ( this.dumpFoldout )
            this.drawDumpPalameter();

        EditorGUILayout.EndVertical();
    }
예제 #18
0
 public NativeSearch(
     ISession session,
     string query,
     int trackOffset,
     int trackCount,
     int albumOffset,
     int albumCount,
     int artistOffset,
     int artistCount,
     int playlistOffset,
     int playlistCount,
     SearchType searchType,
     object userData)
     : base(session, IntPtr.Zero)
 {
     _query = query;
     _trackOffset = trackOffset;
     _trackCount = trackCount;
     _albumOffset = albumOffset;
     _albumCount = albumCount;
     _artistOffset = artistOffset;
     _artistCount = artistCount;
     _playlistOffset = playlistOffset;
     _playlistCount = playlistCount;
     _searchType = searchType;
     _userData = userData;
 }
예제 #19
0
		public bool Replace(Stream readStream, Stream writeStream, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
		{
			SearchDelegates.DoReplace replaceMethod = doTextReplaceCaseSensitive;
			switch (searchType)
			{
				case SearchType.PlainText:
                    if ((searchOptions & GrepSearchOption.CaseSensitive) == GrepSearchOption.CaseSensitive)
					{
						replaceMethod = doTextReplaceCaseSensitive;
					}
					else
					{
						replaceMethod = doTextReplaceCaseInsensitive;
					}
					break;
				case SearchType.Regex:
					replaceMethod = doRegexReplace;
					break;
				case SearchType.XPath:
					replaceMethod = doXPathReplace;
					break;
                case SearchType.Soundex:
                    replaceMethod = doFuzzyReplace;
                    break;
			}

            if ((searchOptions & GrepSearchOption.Multiline) == GrepSearchOption.Multiline)
                return replaceMultiline(readStream, writeStream, searchPattern, replacePattern, searchOptions, replaceMethod, encoding);
			else
				return replace(readStream, writeStream, searchPattern, replacePattern, searchOptions, replaceMethod, encoding);
		}
예제 #20
0
 /// <summary>
 /// Constructor
 /// </summary>
 public WindowSearchResult(Window window, List<int> matchesInTitle, List<int> matchesInProcessName, SearchType matchType)
 {
     this.ResultWindow = window;
     this.SearchMatchesInTitle = matchesInTitle;
     this.SearchMatchesInProcessName = matchesInProcessName;
     this.SearchResultMatchType = matchType;
     this.CalculateScore();
 }
예제 #21
0
 public bool Replace(string sourceFile, string destinationFile, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
 {
     using (FileStream readStream = File.Open(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     using (FileStream writeStream = File.OpenWrite(destinationFile))
     {
         return Replace(readStream, writeStream, searchPattern, replacePattern, searchType, searchOptions, encoding);
     }
 }
예제 #22
0
파일: SearchBox.xaml.cs 프로젝트: neiz/Wish
 public SearchBox(SearchType type, IEnumerable<string> uniqueList, Action<string> callback)
 {
     InitializeComponent();
     _onSelected = callback;
     _viewModel = _viewModelDictionary[type];
     _viewModel.BaseCollection = uniqueList;
     DataContext = _viewModel;
 }
예제 #23
0
 public void prepareGross (string query)
 {
    search_type = SearchType.GROSS;
    int res = BingoCore.lib.mangoSetupMatch("GROSS", query, "");
    if (res < 0)
       throw new Exception(BingoCore.lib.bingoGetError());
    where_clause = BingoCore.mangoGrossGetConditions();
 }
예제 #24
0
 public void prepareSimilarity (string query, string options, float min, float max)
 {
    int res = BingoCore.lib.mangoSetupMatch("SIM", query, options);
    if (res < 0)
       throw new Exception(BingoCore.lib.bingoGetError());
    BingoCore.lib.mangoSimilaritySetMinMaxBounds(min, max);
    search_type = SearchType.SIM;
 }
예제 #25
0
 public SearchOptions(SearchType type, string query, bool newTab, bool caseSensitive, bool useRegex)
 {
     this.Type = type;
     this.Query = query;
     this.NewTab = newTab;
     this.CaseSensitive = caseSensitive;
     this.UseRegex = useRegex;
 }
예제 #26
0
 /// <summary>
 /// Default property values are: Language = "local", MaxRows = 100, Style = ResultStyle.Full.
 /// </summary>
 public SearchOptions(SearchType searchType, string text)
 {
     Language = "local";
     MaxRows = 100;
     Style = ResultStyle.Medium;
     SearchType = searchType;
     Text = text;
 }
예제 #27
0
 public SearchTypeVM(IImageManager imageManager, SearchType searchType, string name, string toolTip, string imageName, VisibleMembersFlags flags)
 {
     this.imageManager = imageManager;
     this.searchType = searchType;
     this.name = name;
     this.toolTip = toolTip;
     this.imageReference = new ImageReference(GetType().Assembly, imageName);
     this.flags = flags;
 }
예제 #28
0
파일: CASCSearch.cs 프로젝트: Kruithne/W3DT
        public static List<CASCFile> Search(string file, SearchType type = SearchType.COMPLETE)
        {
            List<CASCFile> found = new List<CASCFile>();

            if (Program.IsCASCReady)
                Explore(Program.Root, file.ToLower(), type, found);

            return found;
        }
예제 #29
0
        public NicoNicoSearch(SearchViewModel vm, string keyword, SearchType type, string sort)
        {
            SearchVM = vm;
            Type = type;
            Keyword = keyword;

            Sort = "&sort=" + sort.Split(':')[0];
            Order = "&order=" + sort.Split(':')[1];
        }
예제 #30
0
 private void PerformPropertySearch(SearchType searchType, Dictionary<string, object> settings)
 {
     bool cancel;
     var options = _search.SetPropertySearchOptions(searchType, settings, out cancel);
     if (!cancel)
     {
         Cursor = Cursors.AppStarting;
         _search.ExecuteSearch(string.Empty, searchType, options);
     }
 }
예제 #31
0
 /// <summary>
 ///     Sets the SearchType of this column (text, select or datepicker) (default: text)
 ///     WarningSS: To use datepicker jQueryUI javascript should be included
 /// </summary>
 /// <param name = "searchType">Search type</param>
 public GridColumn SetSearchType(SearchType searchType)
 {
     _searchType = searchType;
     return(this);
 }
예제 #32
0
        /// <summary>
        /// Use this call to search for archived transfers which match a specific search term.
        /// </summary>
        /// <param name="searchType">The type of search.</param>
        /// <param name="filter">The search term.</param>
        /// <param name="pageNumber">The page number (starting at 1).</param>
        /// <param name="entriesPerPage">The number of entries to be returned per page.</param>
        /// <returns>A paged result containing the relevant transfers.</returns>
        public GenericPagedResult <WarehouseTransfer> GetArchivedTransfersFiltered(SearchType searchType, String filter, Int32 pageNumber, Int32 entriesPerPage)
        {
            var response = GetResponse("WarehouseTransfer/GetArchivedTransfersFiltered", "searchType=" + searchType.ToString() + "&filter=" + System.Net.WebUtility.UrlEncode(filter) + "&pageNumber=" + pageNumber + "&entriesPerPage=" + entriesPerPage + "");

            return(JsonFormatter.ConvertFromJson <GenericPagedResult <WarehouseTransfer> >(response));
        }
예제 #33
0
 public SearchableAttribute(SearchType SearchType, string accessPath)
 {
     this.AccessPath = AccessPath;
     this.SearchType = SearchType;
 }
예제 #34
0
        public static Expression Build <T>(Expression <Func <T, string> >[] propertiesToSearch, ICollection <string> searchTerms, SearchType searchType)
        {
            Expression result = null;

            foreach (var propertyToSearch in propertiesToSearch)
            {
                var containsExpression = Build(propertyToSearch, searchTerms, searchType);
                result = ExpressionHelper.JoinOrExpression(result, containsExpression);
            }

            if (searchType == SearchType.WholeWords)
            {
                var terms = searchTerms.ToArray();
                var startsWithExpression = QueryableStartsWithExpressionBuilder.Build(propertiesToSearch, terms, searchType);
                result = ExpressionHelper.JoinOrExpression(result, startsWithExpression);
                var endsWithExpression = QueryableEndsWithExpressionBuilder.Build(propertiesToSearch, terms, searchType);
                result = ExpressionHelper.JoinOrExpression(result, endsWithExpression);

                var equalsExpression = QueryableEqualsExpressionBuilder.Build(propertiesToSearch, terms);
                result = ExpressionHelper.JoinOrExpression(result, equalsExpression);
            }

            return(result);
        }
예제 #35
0
    void OnWizardOtherButton()
    {
        if (!noSearch)
        {
            // 一度サーチをやった後はNextで検索するだけ
            NextResultMenuItem();
            Debug.Log("NextItem!");
        }
        else
        {
            noSearch = false;

            //set static records
            lastSearch      = searchFor;
            lastSearchType  = searchBy;
            lastSearchWhole = wholeWord;

            //search space and results
            Object[] allObjects;
            foundItems = new ArrayList();

            if (inSelectionOnly)
            {
                allObjects = Selection.objects;
            }
            else
            {
                allObjects = FindObjectsOfTypeAll(typeof(GameObject));
            }

            if (searchBy == SearchType.Name)
            {
                //name comparison
                if (wholeWord)
                {
                    if (caseSensitive)
                    {
                        foreach (GameObject anObject in allObjects)
                        {
                            if (anObject.name.ToLower().Equals(lastSearch.ToLower()))
                            {
                                foundItems.Add(anObject);
                            }
                        }
                    }
                    else
                    {
                        foreach (GameObject anObject in allObjects)
                        {
                            if (anObject.name.Equals(lastSearch))
                            {
                                foundItems.Add(anObject);
                            }
                        }
                    }
                    if (foundItems.Count == 0)
                    {
                        Debug.Log("No active objects were found with the name \"" + lastSearch + "\"");
                        foundIndex = -1;
                    }
                    else
                    {
                        foundIndex = 0;
                        SelectObject(0);
                        AnnounceResult();
                    }
                }
                else
                {
                    if (caseSensitive)
                    {
                        foreach (GameObject anObject in allObjects)
                        {
                            if (anObject.name.IndexOf(lastSearch) > -1)
                            {
                                foundItems.Add(anObject);
                            }
                        }
                    }
                    else
                    {
                        foreach (GameObject anObject in allObjects)
                        {
                            if (anObject.name.ToLower().IndexOf(lastSearch.ToLower()) > -1)
                            {
                                foundItems.Add(anObject);
                            }
                        }
                    }
                    if (foundItems.Count == 0)
                    {
                        Debug.Log("No active objects were found with names containing \"" + lastSearch + "\"");
                        foundIndex = -1;
                    }
                    else
                    {
                        foundIndex = 0;
                        SelectObject(0);
                        AnnounceResult();
                    }
                }
            }
            else
            {
                //component comparison
                foreach (GameObject objectByType in allObjects)
                {
                    if (objectByType.GetComponent(lastSearch))
                    {
                        foundItems.Add(objectByType);
                    }
                }

                if (foundItems.Count == 0)
                {
                    Debug.Log("No active objects were found with attached " +
                              "component \"" + lastSearch + "\"");
                    foundIndex = -1;
                }
                else
                {
                    foundIndex = 0;
                    SelectObject(0);
                    AnnounceResult();
                }
            }
        }
    }
 private void PeopleButtonTap(object sender, EventArgs e)
 {
     _searchType = SearchType.People;
     SwitchSearchType();
 }
예제 #37
0
        private async void execMethod(string cmd, string obj)
        {
            if (cmd == "open" && !SpotifyLocalAPI.IsSpotifyRunning()) // Start Spotify
            {
                Console.WriteLine("Abrir Spotify");
                SpotifyLocalAPI.RunSpotify();
                SpotifyLocalAPI.RunSpotifyWebHelper();
                Connect();
                AuthConnect();
                t.Speak("O que queres ouvir?");
            }

            if (SpotifyLocalAPI.IsSpotifyRunning())
            {
                if (cmd == "pause") // Pausar
                {
                    Console.WriteLine("Pausa");
                    await _spotify.Pause();

                    t.Speak("Estarei aqui à tua espera.");
                }

                if (cmd == "play") // Retomar
                {
                    Console.WriteLine("Retomar");
                    await _spotify.Play();
                }

                if (cmd == "mute") // Silenciar
                {
                    Console.WriteLine("Silenciar");
                    _spotify.Mute();
                    t.Speak("Já podes atender.");
                }

                if (cmd == "unmute") // Volume
                {
                    Console.WriteLine("Volume");
                    _spotify.UnMute();
                }


                if (cmd == "volumeUp") // Aumentar volume
                {
                    Console.WriteLine("Aumentar volume");
                    _spotify.SetSpotifyVolume(PostureVerify.getVol() + 25);
                }

                if (cmd == "volumeDown") // Diminuir volume
                {
                    Console.WriteLine("Dimiuir volume");
                    _spotify.SetSpotifyVolume(PostureVerify.getVol() - 25);
                }

                if (cmd == "close") // Fechar Spotify
                {
                    Console.WriteLine("Fechar");
                    SpotifyLocalAPI.StopSpotify();
                    t.Speak("Obrigado pela tua preferência. Até à próxima!");
                }

                if (cmd == "createList") // Criar lista de reprodução
                {
                    String name = obj;
                    Console.WriteLine("Criar lista de reprodução");
                    FullPlaylist playlist = _spotifyWeb.CreatePlaylist(id, name);
                    if (!playlist.HasError())
                    {
                        Console.WriteLine("Playlist-URI:" + playlist.Uri);
                    }

                    t.Speak("Lista de reprodução " + name + " criada com sucesso");
                }

                if (cmd == "addList") // Adicionar à lista de reprodução
                {
                    String name = obj;
                    Console.WriteLine("Adicionar à lista de reprodução");
                    String uri = _spotify.GetStatus().Track.TrackResource.Uri;
                    List <SimplePlaylist> playlist = _spotifyWeb.GetUserPlaylists(id).Items;
                    int index = playlist.FindIndex(x => x.Name == name);
                    _spotifyWeb.AddPlaylistTrack(id, _spotifyWeb.GetUserPlaylists(id).Items[index].Id, uri);
                    t.Speak("Música adicionada com sucesso!");
                }

                if (cmd == "removeList") // Remover música da lista de reprodução
                {
                    Console.WriteLine("Remover música da lista de reprodução");
                    String uri      = _spotify.GetStatus().Track.TrackResource.Uri;
                    String playlist = _spotifyWeb.GetUserPlaylists(id).Items[0].Id;
                    _spotifyWeb.RemovePlaylistTrack(id, playlist, new DeleteTrackUri(uri));
                    t.Speak("Música removida!");
                }

                if (cmd == "identify") // Reconhecer música actual
                {
                    Console.WriteLine("Não me lembro do nome desta música");
                    String name = _spotify.GetStatus().Track.TrackResource.Name;
                    t.Speak("A música que estás a ouvir é" + name);
                }


                if (cmd == "playMusic") // Ouvir música
                {
                    SearchType search_type = SearchType.Track;
                    SearchItem item;
                    String     musica;

                    musica = obj;
                    Console.WriteLine("Ouvir " + musica + "!");
                    item = _spotifyWeb.SearchItems(musica, search_type, 1, 0, "pt");
                    await _spotify.PlayURL(item.Tracks.Items[0].Uri, "");
                }

                if (cmd == "playAlbum") // Ouvir álbum
                {
                    SearchType search_type = SearchType.Album;
                    SearchItem item;
                    String     album;

                    album = obj;
                    Console.WriteLine("Ouvir " + album + "!");
                    item = _spotifyWeb.SearchItems(album, search_type, 1, 0, "pt");
                    await _spotify.PlayURL(item.Albums.Items[0].Uri, "");
                }

                if (cmd == "playArtist") // Ouvir artista
                {
                    SearchType search_type = SearchType.Track;
                    SearchItem item;
                    String     artist;

                    artist = obj;
                    Console.WriteLine("Ouvir " + artist + "!");
                    item = _spotifyWeb.SearchItems(artist, search_type, 1, 0, "pt");
                    await _spotify.PlayURL(item.Artists.Items[0].Uri, "");
                }
            }
            else
            {
                t.Speak("Spotify não está aberto.");
            }
        }
예제 #38
0
        protected virtual void AddFieldContainsCriteria(Field field, string containsText, long?id,
                                                        SearchType searchType, bool numericOnly, ref BaseCriteria criteria, ref bool orFalse)
        {
            if (numericOnly == true && (id == null))
            {
                orFalse = true;
                return;
            }

            switch (searchType)
            {
            case SearchType.Contains:
                criteria |= new Criteria(field).Contains(containsText);
                break;

            case SearchType.FullTextContains:
                criteria |= new Criteria("CONTAINS(" + field.Expression + ", " + containsText.ToSql() + ")");
                break;

            case SearchType.StartsWith:
                criteria |= new Criteria(field).StartsWith(containsText);
                break;

            case SearchType.Equals:
                if (field is Int32Field)
                {
                    if (id == null || id < Int32.MinValue || id > Int32.MaxValue)
                    {
                        orFalse = true;

                        return;
                    }

                    criteria |= new Criteria(field) == (int)id;
                }
                else if (field is Int16Field)
                {
                    if (id == null || id < Int16.MinValue || id > Int16.MaxValue)
                    {
                        orFalse = true;
                        return;
                    }

                    criteria |= new Criteria(field) == (Int16)id;
                }
                else if (field is Int64Field)
                {
                    if (id == null || id < Int64.MinValue || id > Int64.MaxValue)
                    {
                        orFalse = true;
                        return;
                    }

                    criteria |= new Criteria(field) == id.Value;
                }
                else
                {
                    criteria |= new Criteria(field) == containsText;
                }
                break;

            default:
                throw new ArgumentOutOfRangeException("searchType");
            }
        }
예제 #39
0
        /// <summary>
        /// Searches the specified query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="searchType">Type of the search.</param>
        /// <param name="entities">The entities.</param>
        /// <param name="fieldCriteria">The field criteria.</param>
        /// <param name="size">The size.</param>
        /// <param name="from">From.</param>
        /// <returns>Search results.</returns>
        public override List <IndexModelBase> Search(string query, SearchType searchType = SearchType.Wildcard, List <int> entities = null, SearchFieldCriteria fieldCriteria = null, int?size = null, int?from = null)
        {
            long totalResultsAvailable = 0;

            return(Search(query, searchType, entities, fieldCriteria, size, from, out totalResultsAvailable));
        }
예제 #40
0
        public List <Student> GetStudentList(string searchParam, SearchType sType, int startYear, int endYear)
        {
            List <Student> sList = new List <Student>();
            string         sql   = $"SELECT s.*, c.*, a.* FROM {basic_table} s INNER JOIN student_class c ON c.student_basic_id = s.id" +
                                   $" INNER JOIN admission a ON a.student_basic_id = s.id";
            string session_sql = $"  AND c.startYear = " + dv(startYear) + " AND c.endYear = " + dv(endYear);

            switch (sType)
            {
            case SearchType.Name:
                sql = sql + $" WHERE s.name LIKE '%{searchParam}%'" + session_sql;
                break;

            case SearchType.ID:
                sql = sql + $" WHERE a.admissionNo = " + dv(searchParam) + session_sql;
                break;

            case SearchType.Aadhaar:
                sql = sql + $" WHERE s.aadhar = " + dv(searchParam) + session_sql;
                break;

            case SearchType.Father:
                sql = sql + $" WHERE s.fatherName LIKE '%{searchParam}%'" + session_sql;
                break;

            case SearchType.Village:
                sql = sql + $" WHERE s.presentAddrLane2 LIKE '%{searchParam}%'" + session_sql;
                break;

            case SearchType.SocialCategory:
                sql = sql + $" WHERE s.socialCategory = " + dv(searchParam) + session_sql;
                break;

            case SearchType.Roll:
                sql = sql + $" WHERE c.roll = {dv(searchParam)} {session_sql}";
                break;

            default:
                break;
            }
            try
            {
                this.conn.Open();
                MySqlCommand    cmd = new MySqlCommand(sql, this.conn);
                MySqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Student s = BuildObject(rdr);
                    sList.Add(s);
                }
            }
            catch (Exception e1)
            {
                System.Windows.MessageBox.Show("Problem in getting student list by type : " + e1.Message);
            }
            finally
            {
                this.conn.Close();
            }
            return(sList);
        }
예제 #41
0
        public override Response <List <Topic> > SearchTopics(string searchTerm, List <int> hiddenForums, SearchType searchType, int startRow, int pageSize, out int topicCount)
        {
            var response = _elasticSearchClientWrapper.SearchTopicsWithIDs(searchTerm, hiddenForums, searchType, startRow, pageSize, out topicCount);
            Response <List <Topic> > result;

            if (!response.IsValid)
            {
                result = new Response <List <Topic> >(null, false, response.Exception, response.DebugInfo);
                return(result);
            }
            var topics = _topicRepository.Get(response.Data);

            result = new Response <List <Topic> >(topics);
            return(result);
        }
예제 #42
0
 public By(SearchType type, string value, IElement parent)
 {
     Type   = type;
     Value  = value;
     Parent = parent;
 }
        private async void ExecuteVoiceCommand(SpeechRecognitionResult result)
        {
            bool isConnected = await LoadAndConnnect();

            if (!isConnected)
            {
                return;
            }

            string voiceCommandName = result.RulePath[0];
            string textSpoken       = result.Text;

            switch (voiceCommandName)
            {
            case "PlayArtist":
                searchType = SearchType.Artist;
                string artistName = SemanticInterpretation("musicTopic", result);
                allArtists = await AudioLibrary.GetArtists();

                var filteredArtists = allArtists.Where(t => t.Label.ToLower().Contains(artistName.ToLower())).ToList();
                if (filteredArtists.Count > 1)
                {
                    searchHitState = SearchHitState.Multiple;
                    ReceivedCommandTextBlock.Text     = "We found multiple artists. Choose one...";
                    SearchedItemsListView.ItemsSource = filteredArtists;
                }
                else if (filteredArtists.Count > 0)
                {
                    searchHitState = SearchHitState.Single;
                    ReceivedCommandTextBlock.Text     = "This is the artist we found...";
                    SearchedItemsListView.ItemsSource = filteredArtists;
                    Player.PlayArtist(filteredArtists[0]);
                    QuestionNameTextBlock.Text = "Did we get the right one?";
                    QuestionWrapper.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                else
                {
                    searchHitState = SearchHitState.None;
                    ReceivedCommandTextBlock.Text = "Sorry, we couldn't find what you asked for.";
                    //SearchedItemsListView.ItemsSource = allArtists;
                    QuestionNameTextBlock.Text = "Would you like to see a list of all artists?";
                    QuestionWrapper.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                break;

            case "PlayMovie":
                searchType = SearchType.Movie;
                string movieName = SemanticInterpretation("movieTopic", result);
                allMovies = await VideoLibrary.GetMovies();

                var filteredMovies = allMovies.Where(t => t.Title.ToLower().Contains(movieName.ToLower())).ToList();
                if (filteredMovies.Count > 1)
                {
                    searchHitState = SearchHitState.Multiple;
                    ReceivedCommandTextBlock.Text     = "We found multiple movies. Choose one...";
                    SearchedItemsListView.ItemsSource = filteredMovies;
                }
                else if (filteredMovies.Count > 0)
                {
                    searchHitState = SearchHitState.Single;
                    ReceivedCommandTextBlock.Text     = "This is the movie we found...";
                    SearchedItemsListView.ItemsSource = filteredMovies;
                    Player.PlayMovie(filteredMovies[0]);
                    QuestionNameTextBlock.Text = "Did we find the right one?";
                    QuestionWrapper.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                else
                {
                    searchHitState = SearchHitState.None;
                    ReceivedCommandTextBlock.Text = "Sorry, we couldn't find what you asked for. Here is the list of all movies.";
                    //SearchedItemsListView.ItemsSource = allMovies;
                    QuestionNameTextBlock.Text = "Would you like to see a list of all movies?";
                    QuestionWrapper.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                break;

            case "PlayAlbum":
                searchType = SearchType.Album;
                string albumName = SemanticInterpretation("musicTopic", result);
                allAlbums = await AudioLibrary.GetAlbums();

                var filteredAlbums = allAlbums.Where(t => t.Title.ToLower().Contains(albumName.ToLower())).ToList();
                if (filteredAlbums.Count > 1)
                {
                    searchHitState = SearchHitState.Multiple;
                    ReceivedCommandTextBlock.Text     = "We found multiple albums. Choose one...";
                    SearchedItemsListView.ItemsSource = filteredAlbums;
                }
                else if (filteredAlbums.Count > 0)
                {
                    searchHitState = SearchHitState.Single;
                    ReceivedCommandTextBlock.Text     = "This is the album we found...";
                    SearchedItemsListView.ItemsSource = filteredAlbums;
                    Player.PlayAlbum(filteredAlbums[0]);
                    QuestionNameTextBlock.Text = "Did we get the right one?";
                    QuestionWrapper.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                else
                {
                    searchHitState = SearchHitState.None;
                    ReceivedCommandTextBlock.Text = "Sorry, we couldn't find what you asked for. Here is the list of all albums.";
                    //SearchedItemsListView.ItemsSource = allAlbums;
                    QuestionNameTextBlock.Text = "Would you like to see a list of all albums?";
                    QuestionWrapper.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                break;

            case "StartParty":
                await Player.PlayPartyMode();

                ReceivedCommandTextBlock.Text = "Started party mode!";
                await Task.Delay(1000);

                Frame.Navigate(typeof(CoverPage));
                break;

            default:
                break;
            }
            if (searchHitState == SearchHitState.Single)
            {
                GlobalVariables.CurrentTracker.SendEvent(EventCategories.VoiceCommand, EventActions.VoiceCommand, "Single" + voiceCommandName, 0);
            }
            else if (searchHitState == SearchHitState.None)
            {
                GlobalVariables.CurrentTracker.SendEvent(EventCategories.VoiceCommand, EventActions.VoiceCommand, "Zero" + voiceCommandName, 0);
            }
        }
예제 #44
0
        /// <summary>
        /// Use this call to search for transfers which match a specific criteria
        /// </summary>
        /// <param name="searchType">The type of search.</param>
        /// <param name="searchText">The search term.</param>
        /// <param name="locationID">The location ID to search.</param>
        /// <returns>A list of the relevant transfer ids.</returns>
        public List <Guid> SearchTransfersByLocation(SearchType searchType, String searchText, Guid locationID)
        {
            var response = GetResponse("WarehouseTransfer/SearchTransfersByLocation", "searchType=" + searchType.ToString() + "&searchText=" + System.Net.WebUtility.UrlEncode(searchText) + "&locationID=" + locationID + "");

            return(JsonFormatter.ConvertFromJson <List <Guid> >(response));
        }
예제 #45
0
 /// <summary>
 /// controls how the distributed search behaves. http://www.elasticsearch.org/guide/reference/api/search/search-type.html
 /// </summary>
 public SearchDescriptor <T> SearchType(SearchType searchType)
 {
     searchType.ThrowIfNull("searchType");
     this._SearchType = searchType;
     return(this);
 }
        public IEnumerable <Dragon> FilterHealthPoints(List <Dragon> dragons, int?HealthPoints, SearchType searchType, SearchParams searchParams)
        {
            if (HealthPoints == null)
            {
                return(dragons);
            }

            List <Dragon> filteredDragons = new List <Dragon>();

            switch (searchType)
            {
            case SearchType.Greater:
            {
                if (searchParams == SearchParams.CreatedHealthPoints)
                {
                    foreach (Dragon dragon in dragons)
                    {
                        if (dragon.CreatedHealthPoints > HealthPoints)
                        {
                            filteredDragons.Add(dragon);
                        }
                    }
                }
                else if (searchParams == SearchParams.CurrentHealthPoints)
                {
                    foreach (Dragon dragon in dragons)
                    {
                        if (dragon.CurrentHealthPoints > HealthPoints)
                        {
                            filteredDragons.Add(dragon);
                        }
                    }
                }
                else
                {
                    throw new SearchException();
                }

                break;
            }

            case SearchType.Lesser:
            {
                if (searchParams == SearchParams.CreatedHealthPoints)
                {
                    foreach (Dragon dragon in dragons)
                    {
                        if (dragon.CreatedHealthPoints < HealthPoints)
                        {
                            filteredDragons.Add(dragon);
                        }
                    }
                }
                else if (searchParams == SearchParams.CurrentHealthPoints)
                {
                    foreach (Dragon dragon in dragons)
                    {
                        if (dragon.CurrentHealthPoints < HealthPoints)
                        {
                            filteredDragons.Add(dragon);
                        }
                    }
                }
                else
                {
                    throw new SearchException();
                }

                break;
            }
            }

            return(filteredDragons);
        }
예제 #47
0
 public bool Replace(string sourceFile, string destinationFile, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
 {
     throw new Exception("The method or operation is not supported.");
 }
 private void TagsButtonTap(object sender, EventArgs e)
 {
     _searchType = SearchType.Tags;
     SwitchSearchType();
 }
예제 #49
0
        /// <summary>
        /// Build a 'contains' expression for a search term against a particular string property
        /// </summary>
        private static Expression Build <T>(Expression <Func <T, string> > propertyToSearch, string searchTerm, SearchType searchType)
        {
            Ensure.ArgumentNotNull(searchTerm, "searchTerm");
            if (searchType == SearchType.WholeWords)
            {
                searchTerm = " " + searchTerm + " ";
            }
            ConstantExpression searchTermExpression = Expression.Constant(searchTerm);

            return(Expression.Call(propertyToSearch.Body, ExpressionMethods.StringContainsMethod, searchTermExpression));
        }
예제 #50
0
        public ActionResult SearchProducts(HomeViewModel data)
        {
            CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
            var client = account.CreateCloudTableClient();
            var table  = client.GetTableReference("products");

            data.MatchedProducts.Clear();
            Stopwatch watch = new Stopwatch();

            SearchType searchType = SearchType.Name;

            double lowerRange  = 0;
            double higherRange = 0;
            int    top         = 5;

            if (data.SearchString.IndexOf('-') > 0)
            {
                string[] parts = data.SearchString.Split('-');
                if (parts.Length == 2 && double.TryParse(parts[0], out lowerRange) && double.TryParse(parts[1], out higherRange))
                {
                    searchType = SearchType.Range;
                }
            }
            else if (data.SearchString.StartsWith("top:"))
            {
                searchType = SearchType.Top;
                top        = int.Parse(data.SearchString.Substring(4));
            }
            if (data.UseTable)
            {
                watch.Start();
                IQueryable <Product> query = null;

                switch (searchType)
                {
                case SearchType.Range:
                    query = from c in table.CreateQuery <Product>()
                            where c.Price >= lowerRange && c.Price <= higherRange && c.PartitionKey == data.ProductCategory
                            select c;
                    break;

                case SearchType.Name:
                    query = from c in table.CreateQuery <Product>()
                            where c.Name == data.SearchString && c.PartitionKey == data.ProductCategory
                            select c;
                    break;

                case SearchType.Top:
                    query = from c in table.CreateQuery <Product>()
                            where c.PartitionKey == data.ProductCategory
                            select c;
                    break;
                }
                foreach (var c in query)
                {
                    c.Price = (int)(c.Price * 100) / 100.0;
                    data.TableProducts.Add(c);
                }
                switch (searchType)
                {
                case SearchType.Range:
                    data.TableProducts.Sort(new Comparison <Product>((p1, p2) => { return(p2.Price.CompareTo(p1.Price)); }));   //descending comparision
                    break;

                case SearchType.Top:
                    data.TableProducts.Sort(new Comparison <Product>((p1, p2) => { return(p2.Rate.CompareTo(p1.Rate)); }));   //descending comparision
                    data.TableProducts = data.TableProducts.Take(top).ToList <Product>();
                    break;
                }
                watch.Stop();
                data.TableResponseTime = watch.ElapsedMilliseconds;
            }

            var connection = ConnectionMultiplexer.Connect(new ConfigurationOptions
            {
                EndPoints = { { redisUrl2, redisPortSSL } },
                Password  = redisPassword2,
                Ssl       = true
            });
            var db = connection.GetDatabase();

            watch.Restart();

            switch (searchType)
            {
            case SearchType.Range:
                List <Product> products = getProducts(data.ProductCategory, lowerRange, higherRange);
                data.MatchedProducts = products;
                break;

            case SearchType.Top:
                List <string> keys = getTopKeys(data.ProductCategory, top);
                foreach (string key in keys)
                {
                    string[] parts = key.Split(':');
                    if (parts.Length == 5)
                    {
                        var quickQuery = from c in table.CreateQuery <Product>()
                                         where c.PartitionKey == parts[0] && c.RowKey == parts[1]
                                         select c;
                        foreach (var c in quickQuery)
                        {
                            c.Price = (int)(c.Price * 100) / 100.0;
                            data.MatchedProducts.Add(c);
                        }
                    }
                }
                break;

            case SearchType.Name:
                var record = db.StringGet("prod:" + data.ProductCategory + ":" + data.SearchString.Replace(' ', ':'));
                if (!record.IsNullOrEmpty)
                {
                    string[] parts = Encoding.ASCII.GetString(record).Split(':');
                    if (parts.Length == 5)
                    {
                        var quickQuery = from c in table.CreateQuery <Product>()
                                         where c.PartitionKey == parts[0] && c.RowKey == parts[1]
                                         select c;
                        foreach (var c in quickQuery)
                        {
                            c.Price = (int)(c.Price * 100) / 100.0;
                            data.MatchedProducts.Add(c);
                        }
                    }
                }
                break;
            }

            watch.Stop();
            data.CachedResponseTime = watch.ElapsedMilliseconds;
            connection.Close(false);
            return(View("Products", data));
        }
예제 #51
0
        private static Expression Build <T>(Expression <Func <T, string> > propertyToSearch, ICollection <string> searchTerms, SearchType searchType)
        {
            Expression result = null;

            foreach (var searchTerm in searchTerms)
            {
                Expression comparisonExpression = Build(propertyToSearch, searchTerm, searchType);
                result = ExpressionHelper.JoinOrExpression(result, comparisonExpression);
            }

            return(result);
        }
예제 #52
0
 public By(SearchType type, string value) : this(type, value, null)
 {
 }
예제 #53
0
        public List <GrepSearchResult> Search(Stream input, string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
        {
            List <GrepSearchResult> searchResults = new List <GrepSearchResult>();

            var filter = FileFilter.ToStandardFilter();

            var includeRegexPatterns = new List <Regex>();
            var excludeRegexPatterns = new List <Regex>();

            Utils.PrepareFilters(filter, includeRegexPatterns, excludeRegexPatterns);

            List <string> hiddenDirectories = new List <string>();

            try
            {
                using (SevenZipExtractor extractor = new SevenZipExtractor(input))
                {
                    foreach (var fileInfo in extractor.ArchiveFileData)
                    {
                        var    attr          = (FileAttributes)fileInfo.Attributes;
                        string innerFileName = fileInfo.FileName;

                        if (fileInfo.IsDirectory)
                        {
                            if (!filter.IncludeHidden && attr.HasFlag(FileAttributes.Hidden) && !hiddenDirectories.Contains(innerFileName))
                            {
                                hiddenDirectories.Add(innerFileName);
                            }

                            continue;
                        }

                        if (CheckHidden(filter, attr) &&
                            CheckHidden(filter, innerFileName, hiddenDirectories) &&
                            CheckSize(filter, fileInfo.Size) &&
                            CheckDate(filter, fileInfo) &&
                            IsPatternMatch(innerFileName, includeRegexPatterns) &&
                            !IsPatternMatch(innerFileName, excludeRegexPatterns))
                        {
                            using (Stream stream = new MemoryStream())
                            {
                                extractor.ExtractFile(innerFileName, stream);
                                stream.Seek(0, SeekOrigin.Begin);

                                if (CheckBinary(filter, stream))
                                {
                                    IGrepEngine engine           = GrepEngineFactory.GetSearchEngine(innerFileName, initParams, filter);
                                    var         innerFileResults = engine.Search(stream, innerFileName, searchPattern, searchType, searchOptions, encoding);

                                    if (innerFileResults.Count > 0)
                                    {
                                        using (Stream readStream = new MemoryStream())
                                        {
                                            extractor.ExtractFile(innerFileName, readStream);
                                            readStream.Seek(0, SeekOrigin.Begin);
                                            using (StreamReader streamReader = new StreamReader(readStream))
                                            {
                                                foreach (var result in innerFileResults)
                                                {
                                                    if (Utils.CancelSearch)
                                                    {
                                                        break;
                                                    }

                                                    if (!result.HasSearchResults)
                                                    {
                                                        result.SearchResults = Utils.GetLinesEx(streamReader, result.Matches, initParams.LinesBefore, initParams.LinesAfter);
                                                    }
                                                }
                                            }
                                            searchResults.AddRange(innerFileResults);
                                        }
                                    }

                                    GrepEngineFactory.ReturnToPool(innerFileName, engine);
                                }
                                if (Utils.CancelSearch)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }

                foreach (GrepSearchResult result in searchResults)
                {
                    result.FileNameDisplayed = file + "\\" + result.FileNameDisplayed;
                    result.FileNameReal      = file;
                    result.ReadOnly          = true;
                }
            }
            catch (Exception ex)
            {
                logger.Log <Exception>(LogLevel.Error, string.Format("Failed to search inside archive '{0}'", file), ex);
            }
            return(searchResults);
        }
예제 #54
0
 public By(SearchType type, string value, IElement parent)
 {
     this.Type   = type;
     this.Value  = value;
     this.Parent = parent;
 }
예제 #55
0
        /// <summary>
        /// Searches the specified query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="searchType">Type of the search.</param>
        /// <param name="entities">The entities.</param>
        /// <param name="fieldCriteria">The field criteria.</param>
        /// <param name="size">The size.</param>
        /// <param name="from">From.</param>
        /// <param name="totalResultsAvailable">The total results available.</param>
        /// <returns></returns>
        public override List <IndexModelBase> Search(string query, SearchType searchType, List <int> entities, SearchFieldCriteria fieldCriteria, int?size, int?from, out long totalResultsAvailable)
        {
            List <IndexModelBase> documents = new List <IndexModelBase>();

            totalResultsAvailable = 0;
            bool allEntities = false;

            BooleanQuery  queryContainer  = new BooleanQuery();
            List <string> combinedFields  = new List <string>();
            List <Type>   indexModelTypes = new List <Type>();
            Dictionary <string, Analyzer> combinedFieldAnalyzers = new Dictionary <string, Analyzer>();

            using (RockContext rockContext = new RockContext())
            {
                var entityTypeService = new EntityTypeService(rockContext);
                if (entities == null || entities.Count == 0)
                {
                    // add all entities
                    allEntities = true;
                    var selectedEntityTypes = EntityTypeCache.All().Where(e => e.IsIndexingSupported && e.IsIndexingEnabled && e.FriendlyName != "Site");

                    foreach (var entityTypeCache in selectedEntityTypes)
                    {
                        entities.Add(entityTypeCache.Id);
                    }
                }

                foreach (var entityId in entities)
                {
                    // get entities search model name
                    var entityType = entityTypeService.GetNoTracking(entityId);
                    indexModelTypes.Add(entityType.IndexModelType);

                    // check if this is a person model, if so we need to add two model types one for person and the other for businesses
                    // wish there was a cleaner way to do this
                    if (entityType.Guid == SystemGuid.EntityType.PERSON.AsGuid())
                    {
                        indexModelTypes.Add(typeof(BusinessIndex));
                    }
                }

                indexModelTypes = indexModelTypes.Distinct().ToList();
            }

            CombineIndexTypes(indexModelTypes, out combinedFields, out combinedFieldAnalyzers);

            var entityFieldFilter = new BooleanQuery();

            if (entities != null && entities.Count != 0 && !allEntities)
            {
                Occur occur = fieldCriteria.SearchType == CriteriaSearchType.And ? Occur.MUST : Occur.SHOULD;
                var   indexModelTypesQuery = new BooleanQuery();

                foreach (var modelType in indexModelTypes)
                {
                    var modelFilter = new BooleanQuery();
                    modelFilter.Add(new TermQuery(new Term("type", modelType.Name.ToLower())), Occur.MUST);

                    if (fieldCriteria != null && fieldCriteria.FieldValues?.Count > 0)
                    {
                        var fieldQuery = new BooleanQuery();
                        foreach (var field in fieldCriteria.FieldValues)
                        {
                            var fieldName = field.Field.Substring(0, 1).ToUpper() + field.Field.Substring(1);

                            if (modelType.GetProperty(fieldName) != null)
                            {
                                // Add field filter
                                var phraseQuery = new PhraseQuery();

                                foreach (var word in field.Value.Split(' '))
                                {
                                    phraseQuery.Add(new Term(fieldName, word.ToLower()));
                                }

                                BooleanClause booleanClause = new BooleanClause(phraseQuery, occur);
                                booleanClause.Query.Boost = field.Boost;
                                fieldQuery.Add(booleanClause);
                            }
                        }

                        if (fieldQuery.Clauses.Count() > 0)
                        {
                            modelFilter.Add(fieldQuery, Occur.MUST);
                        }
                    }

                    indexModelTypesQuery.Add(modelFilter, Occur.SHOULD);
                }

                entityFieldFilter.Add(indexModelTypesQuery, Occur.MUST);
            }

            queryContainer.Add(entityFieldFilter, Occur.MUST);

            switch (searchType)
            {
            case SearchType.ExactMatch:
            {
                var wordQuery = new BooleanQuery();

                if (!string.IsNullOrWhiteSpace(query))
                {
                    var words = query.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var word in words)
                    {
                        var innerQuery = new BooleanQuery();
                        combinedFields.ForEach(f => innerQuery.Add(new PrefixQuery(new Term(f, word.ToLower())), Occur.SHOULD));
                        wordQuery.Add(innerQuery, Occur.SHOULD);
                    }
                }

                if (wordQuery.Count() != 0)
                {
                    queryContainer.Add(wordQuery, Occur.MUST);
                }

                // special logic to support emails
                if (query.Contains("@"))
                {
                    queryContainer.Add(new BooleanClause(new TermQuery(new Term("Email", query)), Occur.SHOULD));
                }

                // special logic to support phone search
                if (query.IsDigitsOnly())
                {
                    queryContainer.Add(new BooleanClause(new WildcardQuery(new Term("PhoneNumbers", "*" + query + "*")), Occur.SHOULD));
                }

                // add a search for all the words as one single search term
                foreach (var field in combinedFields)
                {
                    var phraseQuery = new PhraseQuery();
                    phraseQuery.Add(new Term(field, query.ToLower()));
                    queryContainer.Add(phraseQuery, Occur.SHOULD);
                }

                break;
            }

            case SearchType.Fuzzy:
            {
                foreach (var field in combinedFields)
                {
                    queryContainer.Add(new FuzzyQuery(new Term(field, query.ToLower())), Occur.SHOULD);
                }

                break;
            }

            case SearchType.Wildcard:
            {
                bool enablePhraseSearch = true;

                if (!string.IsNullOrWhiteSpace(query))
                {
                    BooleanQuery wildcardQuery = new BooleanQuery();

                    // break each search term into a separate query and add the * to the end of each
                    var queryTerms = query.Split(' ').Select(p => p.Trim()).ToList();

                    // special logic to support emails
                    if (queryTerms.Count == 1 && query.Contains("@"))
                    {
                        wildcardQuery.Add(new WildcardQuery(new Term("Email", "*" + query.ToLower() + "*")), Occur.SHOULD);
                        enablePhraseSearch = false;
                    }
                    else
                    {
                        foreach (var queryTerm in queryTerms)
                        {
                            if (!string.IsNullOrWhiteSpace(queryTerm))
                            {
                                var innerQuery = new BooleanQuery();
                                combinedFields.ForEach(f => innerQuery.Add(new PrefixQuery(new Term(f, queryTerm.ToLower())), Occur.SHOULD));
                                wildcardQuery.Add(innerQuery, Occur.MUST);
                            }
                        }

                        // add special logic to help boost last names
                        if (queryTerms.Count() > 1 && (indexModelTypes.Contains(typeof(PersonIndex)) || indexModelTypes.Contains(typeof(BusinessIndex))))
                        {
                            BooleanQuery nameQuery = new BooleanQuery
                            {
                                { new PrefixQuery(new Term("FirstName", queryTerms.First().ToLower())), Occur.MUST },
                                { new PrefixQuery(new Term("LastName", queryTerms.Last().ToLower()))
                                  {
                                      Boost = 30
                                  }, Occur.MUST }
                            };
                            wildcardQuery.Add(nameQuery, Occur.SHOULD);

                            nameQuery = new BooleanQuery
                            {
                                { new PrefixQuery(new Term("NickName", queryTerms.First().ToLower())), Occur.MUST },
                                { new PrefixQuery(new Term("LastName", queryTerms.Last().ToLower()))
                                  {
                                      Boost = 30
                                  }, Occur.MUST }
                            };
                            wildcardQuery.Add(nameQuery, Occur.SHOULD);
                        }

                        // special logic to support phone search
                        if (query.IsDigitsOnly())
                        {
                            wildcardQuery.Add(new PrefixQuery(new Term("PhoneNumbers", queryTerms.First().ToLower())), Occur.SHOULD);
                        }
                    }

                    queryContainer.Add(wildcardQuery, Occur.MUST);
                }

                // add a search for all the words as one single search term
                if (enablePhraseSearch)
                {
                    // add a search for all the words as one single search term
                    foreach (var field in combinedFields)
                    {
                        var phraseQuery = new PhraseQuery();
                        phraseQuery.Add(new Term(field, query.ToLower()));
                        queryContainer.Add(phraseQuery, Occur.SHOULD);
                    }
                }

                break;
            }
            }

            int returnSize = 10;

            if (size.HasValue)
            {
                returnSize = size.Value;
            }

            try
            {
                OpenReader();
            }
            catch (IndexNotFoundException)
            {
                // Issue opening index. Most likely cause is the index is empty so return an empty results set.
                return(new List <IndexModelBase>());
            }

            TopDocs topDocs = null;

            if (from.HasValue)
            {
                TopScoreDocCollector collector = TopScoreDocCollector.Create(returnSize * 10, true);   // Search for 10 pages with returnSize entries in each page
                _indexSearcher.Search(queryContainer, collector);
                topDocs = collector.GetTopDocs(from.Value, returnSize);
            }
            else
            {
                topDocs = _indexSearcher.Search(queryContainer, returnSize);
            }

            totalResultsAvailable = topDocs.TotalHits;

            if (topDocs != null)
            {
                foreach (var hit in topDocs.ScoreDocs)
                {
                    var document = LuceneDocToIndexModel(queryContainer, hit);
                    if (document != null)
                    {
                        documents.Add(document);
                    }
                }
            }

            return(documents);
        }
예제 #56
0
    /// <summary>
    /// Plays the given clip on the given audio source.
    /// </summary>
    /// <param name="id">Music/sound player name or tag</param>
    /// <param name="sClip">Sound Clip</param>
    /// <param name="shouldRepeat">Should audio be in a loop, false by default</param>
    /// <param name="st">Search type for the player. Search by name or tag</param>
    public static void PlaySound(string id, AudioClip sClip, bool shouldRepeat = false, SearchType st = SearchType.Name)
    {
        AudioSource source = GetSoundPlayer(id, st);

        if (!source)
        {
            Debug.Log("No music player has been found!"); return;
        }

        source.loop = shouldRepeat;

        source.clip = sClip;
        source.Play();
    }
예제 #57
0
 public DialogResult EditSearch(SearchType type)
 {
     return(EditSearch(type, this.Location, this.Size));
 }
예제 #58
0
        private void OnGUI()
        {
            EditorGUILayout.Space();
            EditorGUILayout.Space();

            targetScriptable = (LocalizationScriptableObject)EditorGUILayout.ObjectField(targetScriptable, typeof(LocalizationScriptableObject), false);

            EditorGUILayout.BeginHorizontal(GUILayout.Height(25));
            {
                EditorGUI.BeginDisabledGroup(targetScriptable == null);
                if (GUILayout.Button(loaded ? "Reload" : "Load", GUILayout.Height(25)))
                {
                    LoadDictionary(targetScriptable);
                }
                EditorGUI.EndDisabledGroup();

                EditorGUI.BeginDisabledGroup(!loaded);
                if (GUILayout.Button("Save", GUILayout.Height(25)))
                {
                    tempDictionary.Clear();
                    tempDictionary.LoadEntries(tempEntries);
                    targetScriptable.dictionary = tempDictionary;
                    if (AssetDatabase.Contains(targetScriptable))
                    {
                        EditorUtility.SetDirty(targetScriptable);
                        AssetDatabase.SaveAssets();
                    }
                }

                if (GUILayout.Button("Languages", GUILayout.Height(25)))
                {
                }
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Separator();
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Search by", GUILayout.Width(75));
            searchMask  = (SearchType)EditorGUILayout.EnumPopup(searchMask, GUILayout.Width(100));
            searchValue = EditorGUILayout.TextField(searchValue);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Separator();
            EditorGUI.EndDisabledGroup();

            EditorGUILayout.Space();
            if (loaded)
            {
                DisplayValues();

                EditorGUILayout.Separator();
                EditorGUILayout.BeginHorizontal();
                {
                    //if (GUILayout.Button("Add Language"))
                    //{
                    //    if (!tempEntries.Exists(e => e.languageKey == newLanguage))
                    //    {
                    //        foreach (var w in wordKeys)
                    //        {
                    //            var temp = new LocalizationEntry();
                    //            temp.wordKey = w;
                    //            temp.languageKey = newLanguage;
                    //            tempEntries.Add(temp);
                    //        }

                    //        languageKeys.Add(newLanguage);
                    //    }
                    //}

                    if (GUILayout.Button("Add", GUILayout.Height(30)))
                    {
                        ShowAddPopup();
                    }
                }
                EditorGUILayout.EndHorizontal();

                //EditorGUILayout.BeginHorizontal();
                //{
                //    if (GUILayout.Button("Remove Language"))
                //    {
                //        tempEntries.RemoveAll(e => e.languageKey == newLanguage);
                //        languageKeys.Remove(newLanguage);
                //    }

                //    if (GUILayout.Button("Remove Word Key"))
                //    {
                //        tempEntries.RemoveAll(e => e.wordKey == newWordKey);
                //        wordKeys.Remove(newWordKey);
                //    }
                //}
                //EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.Space();
        }
        private static Expression Build <T>(Expression <Func <T, string> > propertyToSearch, IEnumerable <string> searchTerms, ConstantExpression stringComparisonExpression, SearchType searchType)
        {
            Expression completeExpression = null;
            bool       isWholeWordSearch  = searchType == SearchType.WholeWords;

            foreach (var searchTerm in searchTerms)
            {
                var searchTermExpression = Expression.Constant(isWholeWordSearch ? " " + searchTerm + " " : searchTerm);
                var containsExpression   = Build(propertyToSearch, searchTermExpression, stringComparisonExpression);
                completeExpression = ExpressionHelper.JoinOrExpression(completeExpression, containsExpression);
            }

            return(completeExpression);
        }
예제 #60
0
 public static ISearchCriteria SearchType(this ISearchCriteria criteria, SearchType searchType)
 {
     return(criteria.Component("SearchType", searchType));
 }