Пример #1
0
 public bool Match(SearchItem item, Type type)
 {
     var realType = TypeUtil.GetUnNullableType(type);
     return realType == typeof(DateTime)
            && !(item.Value is DateTime)
            && (item.Method == SearchMethod.LessThan || item.Method == SearchMethod.LessThanOrEqual);
 }
        public SearchItemEditWindow(ref SearchItem searchItem)
        {
            _searchItem = searchItem;

            InitializeComponent();

            {
                var icon = new BitmapImage();

                icon.BeginInit();
                icon.StreamSource = new FileStream(Path.Combine(App.DirectoryPaths["Icons"], "Amoeba.ico"), FileMode.Open, FileAccess.Read, FileShare.Read);
                icon.EndInit();
                if (icon.CanFreeze) icon.Freeze();

                this.Icon = icon;
            }

            lock (_searchItem.ThisLock)
            {
                _searchTreeViewItemNameTextBox.Text = _searchItem.Name;

                _nameCollection = new ObservableCollectionEx<SearchContains<string>>(_searchItem.SearchNameCollection);
                _nameRegexCollection = new ObservableCollectionEx<SearchContains<SearchRegex>>(_searchItem.SearchNameRegexCollection);
                _signatureCollection = new ObservableCollectionEx<SearchContains<SearchRegex>>(_searchItem.SearchSignatureCollection);
                _keywordCollection = new ObservableCollectionEx<SearchContains<string>>(_searchItem.SearchKeywordCollection);
                _creationTimeRangeCollection = new ObservableCollectionEx<SearchContains<SearchRange<DateTime>>>(_searchItem.SearchCreationTimeRangeCollection);
                _lengthRangeCollection = new ObservableCollectionEx<SearchContains<SearchRange<long>>>(_searchItem.SearchLengthRangeCollection);
                _seedCollection = new ObservableCollectionEx<SearchContains<Seed>>(_searchItem.SearchSeedCollection);
                _stateCollection = new ObservableCollectionEx<SearchContains<SearchState>>(_searchItem.SearchStateCollection);
            }

            _searchTreeViewItemNameTextBox_TextChanged(null, null);

            _nameListView.ItemsSource = _nameCollection;
            _nameRegexListView.ItemsSource = _nameRegexCollection;
            _signatureListView.ItemsSource = _signatureCollection;
            _keywordListView.ItemsSource = _keywordCollection;
            _creationTimeRangeListView.ItemsSource = _creationTimeRangeCollection;
            _lengthRangeListView.ItemsSource = _lengthRangeCollection;
            _seedListView.ItemsSource = _seedCollection;
            _stateListView.ItemsSource = _stateCollection;

            _nameListViewUpdate();
            _nameRegexListViewUpdate();
            _signatureListViewUpdate();
            _keywordListViewUpdate();
            _creationTimeRangeListViewUpdate();
            _lengthRangeListViewUpdate();
            _seedListViewUpdate();
            _stateListViewUpdate();

            foreach (var item in Enum.GetValues(typeof(SearchState)).Cast<SearchState>())
            {
                _stateComboBox.Items.Add(item);
            }

            _stateComboBox.SelectedIndex = 0;
        }
Пример #3
0
 public IEnumerable<SearchItem> Transform(SearchItem item, Type type)
 {
     DateTime willTime;
     DateTime.TryParse(item.Value.ToString(), out willTime);
     if (willTime.Hour == 0 && willTime.Minute == 0 && willTime.Second == 0)
     {
         willTime = willTime.AddDays(1).AddMilliseconds(-1);
     }
     return new[] { new SearchItem(item.Field, SearchMethod.LessThanOrEqual, willTime) };
 }
Пример #4
0
 public void LogImage(SearchItem item)
 {
     try
     {
         if (item.Status == SearchItem.Statuses.Failed)
             LogError(item);
         else
             LogSuccess(item);
     }
     catch (Exception ex)
     {
         throw new LoggingException(string.Format("Error logging result: {0},{1}", item.FilePath, item.ImageUrl), ex);
     }
 }
Пример #5
0
        public SearchItem ResolveImageShortUrl(SearchItem item)
        {
            try
            {
                if (item.Status != SearchItem.Statuses.Ok)
                    return item;

                if (!IsShortUrl(item.ImageUrl))
                    return item;

                item.ShortUrl = item.ImageUrl;

                if (CachedUrls.ContainsKey(item.ImageUrl))
                {
                    item.ImageUrl = CachedUrls[item.ImageUrl];
                    return item;
                }

                var request = WebRequest.CreateHttp(item.ImageUrl);
                request.MaximumAutomaticRedirections = 1;
                request.AllowAutoRedirect = false;
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    if (response == null)
                        return item;
                    if (!IsRedirectResponse(response.StatusCode))
                        return item;

                    var responseLocation = response.GetResponseHeader("Location");

                    if (!string.IsNullOrEmpty(responseLocation))
                    {
                        CachedUrls.TryAdd(item.ImageUrl, responseLocation);
                        item.ImageUrl = responseLocation;
                    }
                    else
                        CachedUrls.TryAdd(item.ImageUrl, item.ImageUrl);

                    return item;
                }
            }
            catch (Exception ex)
            {
                item.Status = SearchItem.Statuses.Failed;
                item.Error = new ShortUrlResolverExceptoin(String.Format("Error resolving short item: {0}", item), ex);
                return item;
            }
        }
Пример #6
0
        public SearchItem GetFile(SearchItem item)
        {
            try
            {
                if (item.Status != SearchItem.Statuses.Ok)
                    return item;

                item.FileContents = File.ReadAllText(item.FilePath);
                return item;
            }
            catch (Exception ex)
            {
                item.Status = SearchItem.Statuses.Failed;
                item.Error = new FileProviderException("Error getting file", ex);
                return item;
            }
        }
Пример #7
0
 public override SearchItem[] ExtractSearchItems(string content)
 {
     List<SearchItem> items = new List<SearchItem>();
     string pattern = "<p class=\"second_name\"><a href=\"(.+?)\" title=\"(.+?)\">[^<]+</a></p>(<p class=\"cost2\">([^<]+)<|)";
     MatchCollection matches = Regex.Matches(content, pattern);
     foreach (Match m in matches)
     {
         SearchItem item = new SearchItem()
         {
             EngineId = this.Id,
             Name = m.Groups[2].Value,
             Price = m.Groups[4].Value,
             Url = GetAbsoluteUri(m.Groups[1].Value)
         };
         items.Add(item);
     }
     return items.ToArray();
 }
Пример #8
0
        /// <summary>
        /// Busca la primer entrada con el nombre completo dentro de una funcion, store, vista, trigger o rule.
        /// Ignora los comentarios.
        /// </summary>
        private static SearchItem FindCreate(string ObjectType, ISchemaBase item, string prevText)
        {
            SearchItem sitem = new SearchItem();
            Regex regex = new Regex(@"((/\*)(\w|\s|\d|\[|\]|\.)*(\*/))|((\-\-)(.)*)", RegexOptions.IgnoreCase);
            Regex reg2 = new Regex(@"CREATE( )+" + ObjectType + @"(\s|\r|\n|\t|\w|\/|\*|-|@|_|&|#)*((\[)?" + item.Owner + @"(\])?((\s)*)?\.)?((\s)*)?(\[)?" + item.Name + @"(\])?", (RegexOptions)((int)RegexOptions.IgnoreCase + (int)RegexOptions.Multiline));
            //Regex reg2_1 = new Regex(@"CREATE( )+" + ObjectType + @"(\s|\r|\n|\t|\w|\/|\*|-|@|_|&|#)*((\[)?" + item.Name + @"(\])?", (RegexOptions)((int)RegexOptions.IgnoreCase + (int)RegexOptions.Multiline));
            
            Regex reg3 = new Regex(@"((\[)?" + item.Owner + @"(\])?\.)?((\s)+\.)?(\s)*(\[)?" + item.Name + @"(\])?", RegexOptions.IgnoreCase);
            Regex reg4 = new Regex(@"( )*\[");

            MatchCollection abiertas = regex.Matches(prevText);
            Boolean finish = false;
            int indexStart = 0;
            int indexBegin = 0;
            int iAux = -1;

            while (!finish)
            {
                Match match = reg2.Match(prevText, indexBegin);
                if (match.Success)
                    iAux = match.Index;

                    else iAux = -1;                   

                if ((abiertas.Count == indexStart) || (!match.Success))
                    finish = true;
                else
                {
                    if ((iAux < abiertas[indexStart].Index) || (iAux > abiertas[indexStart].Index + abiertas[indexStart].Length))
                        finish = true;
                    else
                    {
                        indexBegin = iAux + 1;
                        indexStart++;
                    }
                }
            }
            string result = reg3.Replace(prevText, " " + item.FullName, 1, iAux + 1);
            if (iAux != -1)
                sitem.Body = reg4.Replace(result, " [", 1, iAux);
            sitem.FindPosition = iAux;
            return sitem;
        }
        public async Task <List <String> > GetSpotifyGenreData(string searchTerm)
        {
            CredentialsAuth auth  = new CredentialsAuth("078c7392711e4b978d6a3bd21984c93c", "8b7f7c3b96454fcd8b42193a179ca19b");
            Token           token = await auth.GetToken();

            SpotifyWebAPI api = new SpotifyWebAPI()
            {
                TokenType = token.TokenType, AccessToken = token.AccessToken
            };
            SearchItem        item      = api.SearchItems(searchTerm, SearchType.All, 10, 0, "US");
            List <FullArtist> artists   = item.Artists.Items.ToList();
            List <String>     genreList = new List <String>();

            foreach (FullArtist artist in artists)
            {
                foreach (string genre in artist.Genres)
                {
                    genreList.Add(genre);
                }
            }
            return(genreList);
        }
        public async Task <JsonResult> GetSpotifyData(string searchTerm)
        {
            CredentialsAuth auth  = new CredentialsAuth("078c7392711e4b978d6a3bd21984c93c", "8b7f7c3b96454fcd8b42193a179ca19b");
            Token           token = await auth.GetToken();

            SpotifyWebAPI api = new SpotifyWebAPI()
            {
                TokenType = token.TokenType, AccessToken = token.AccessToken
            };
            SearchItem        item        = api.SearchItems(searchTerm, SearchType.All, 10, 0, "US");
            List <FullArtist> artists     = item.Artists.Items.ToList();
            List <AjaxArtist> ajaxArtists = new List <AjaxArtist>();

            foreach (FullArtist artist in artists)
            {
                AjaxArtist artistajax = new AjaxArtist();
                artistajax.Id   = artist.Id;
                artistajax.Name = artist.Name;
                ajaxArtists.Add(artistajax);
            }
            return(Json(ajaxArtists, JsonRequestBehavior.AllowGet));
        }
        // Generate further information
        //
        //

        public static string GetIrdiForUnitSearchItem(SearchItem si)
        {
            if (si == null || si.ContentNode == null || si.Entity != "unit")
            {
                return(null);
            }

            string res = null;

            foreach (var x in GetChildNodesByName(si.ContentNode, "unitsml:CodeListValue"))
            {
                var cln = GetAttributeByName(x, "codeListName");
                var ucv = GetAttributeByName(x, "unitCodeValue");
                if (cln == "IRDI")
                {
                    res = ucv;
                    break;
                }
            }

            return(res);
        }
Пример #12
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            var response = string.Empty;

            try
            {
                var mode = ((string)req.Query["mode"]) ?? string.Empty;

                if (mode.Contains("-l"))
                {
                    response = httpHelper.GetStringResponse($"https://www.newegg.com/product/api/ProductRealtime?ItemNumber=68-110-292&RecommendItem=&BestSellerItemList=&IsVATPrice=true");
                }
                else
                {
                    response = File.ReadAllText(Path.Combine(context.FunctionAppDirectory, "requests/newegg/newegg-ps5-response.json"));
                }

                var ps5 = JsonConvert.DeserializeObject <JObject>(response);

                var item = new SearchItem
                {
                    Url     = "https://www.newegg.com/p/N82E16868110292?Description=ps5&cm_re=ps5-_-68-110-292-_-Product&quicklink=true",
                    Instock = (bool)ps5["MainItem"]["Instock"],
                    Title   = ps5["MainItem"]["Description"]["Title"]?.ToString()
                };
                Console.WriteLine($"Newegg Response: {JsonConvert.SerializeObject(item)}");
                Console.WriteLine();

                return(new OkObjectResult(new[] { item }));
            }
            catch (Exception ex)
            {
                var detailEx = new Exception($"Newegg Server Response: {response}", ex);
                return(new ExceptionResult(detailEx, true));
            }
        }
Пример #13
0
 public static IEnumerable<Models.SearchResult> MapSearchItemsToSearchResults(SearchItem[] items, IConditionResolver resolver, int productId)
 {
     return items.Select(i => new Models.SearchResult()
     {
         DateOfMatch = DateTime.Now,
         Link = i.viewItemURL,
         Title = i.title,
         Price = i.sellingStatus.currentPrice.Value,
         ItemNumber = i.itemId,
         StartTime = i.listingInfo.startTime,
         EndTime = i.listingInfo.endTime,
         NumberOfBidders = i.listingInfo.listingType.ToLowerInvariant() == "auction" ? i.sellingStatus.bidCount : 0,
         ImageURL = i.galleryURL,
         Currency = i.sellingStatus.currentPrice.currencyId,
         Location = i.location,
         SiteID = i.globalId,
         Type = i.listingInfo.listingType,
         ShippingCost = (i.shippingInfo.shippingServiceCost != null) ? i.shippingInfo.shippingServiceCost.Value : 0.0f,
         ConditionId = resolver.ConditionIdFromEBayConditionId((i.condition == null)? 0 : i.condition.conditionId),
         ProductId = productId
     });
 }
Пример #14
0
        public async Task <SearchItem> SearchTrack(string query, string tk)
        {
            RoclappData data = DataAccess.GetRocolappData();

            RocolappUser user = GetUserbyRocolappId(tk);

            var spotify = new SpotifyWebAPI()
            {
                TokenType   = "Bearer",
                AccessToken = user.Token,
                UseAuth     = true
            };

            SearchItem searchItem = spotify.SearchItems(query, SearchType.Track);

            if (searchItem.Error != null && searchItem.Error.Status == 401)
            {
                AutorizationCodeAuth auth = new AutorizationCodeAuth();
                //Datos de mi aplicacion Rocolapp
                auth.ClientId    = DataAccess.GetRocolappData().ClientId;
                auth.RedirectUri = DataAccess.GetRocolappData().RedirectUri;
                string clientSecret = DataAccess.GetRocolappData().ClientSecret;

                Token token = auth.RefreshToken(user.RefreshToken, DataAccess.GetRocolappData().ClientSecret);

                UpdateToken(user.Id.ToString(), token.AccessToken);

                var withRefreshedToken = new SpotifyWebAPI()
                {
                    TokenType   = "Bearer",
                    AccessToken = token.AccessToken,
                    UseAuth     = true
                };

                searchItem = withRefreshedToken.SearchItems(query, SearchType.Track);
            }

            return(searchItem);
        }
Пример #15
0
        private void dataView_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
        {
            try
            {
                SearchItem tmp;
                if (e.RowIndex < SearchList.Count)
                {
                    tmp        = SearchList.Get(e.RowIndex);
                    currentRow = e.RowIndex;
                    if (curEdit == null)
                    {
                        curEdit = new SearchItem(tmp.Name, tmp.Keyword, tmp.SearchPath);
                    }
                    tmp        = curEdit;
                    currentRow = e.RowIndex;
                }
                else
                {
                    tmp = curEdit;
                }
                string val = e.Value as string;
                switch (e.ColumnIndex)
                {
                case 0:
                    tmp.Name = val;
                    break;

                case 1:
                    tmp.Keyword = val;
                    break;

                case 2:
                    tmp.SearchPath = val;
                    break;
                }
            }
            catch { }
        }
Пример #16
0
        public static List <SearchItem> GetSearchResults(string searchKey)
        {
            List <SearchItem> results = new List <SearchItem>();

            #region Products
            var products = ProductManager.GetProductsBySearchKey(searchKey);
            foreach (var product in products)
            {
                SearchItem ps = new SearchItem();
                ps.Title        = product.ProductName;
                ps.Description  = product.Description;
                ps.ShortDetails = product.ShortDetails;
                ps.ImageUrl     = product.ImageUrl;
                ps.Link         = "/Home/ProductDetails?id=" + product.Id;

                results.Add(ps);
            }
            #endregion

            #region News

            var news = NewsEventsManager.GetNewsBySearchkey(searchKey);

            foreach (var nw in news)
            {
                SearchItem ps = new SearchItem();
                ps.Title        = nw.Title;
                ps.Description  = nw.Description;
                ps.ShortDetails = nw.ShortDescription;
                ps.ImageUrl     = nw.ImagePath;
                ps.Link         = "/Home/News?newsId=" + nw.Id;

                results.Add(ps);
            }
            return(results);

            #endregion
        }
        private IQ SetVCardSearch(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            var answer = new IQ(IqType.result);

            answer.Id   = iq.Id;
            answer.To   = iq.From;
            answer.From = iq.To;

            var search = (Search)iq.Query;

            var pattern = new Vcard();

            pattern.Nickname = search.Nickname;
            pattern.Name     = new Name(search.Lastname, search.Firstname, null);
            //pattern.AddEmailAddress(new Email() { UserId = search.Email });

            search = new Search();
            foreach (var vcard in context.StorageManager.VCardStorage.Search(pattern))
            {
                var item = new SearchItem();
                item.Jid      = vcard.JabberId;
                item.Nickname = vcard.Nickname;
                if (vcard.Name != null)
                {
                    item.Firstname = vcard.Name.Given;
                    item.Lastname  = vcard.Name.Family;
                }
                var email = vcard.GetPreferedEmailAddress();
                if (email != null)
                {
                    item.Email = email.UserId;
                }
                search.AddChild(item);
            }

            answer.Query = search;
            return(answer);
        }
Пример #18
0
        public async Task fmspotifysearchAsync(params string[] searchterms)
        {
            try
            {
                string querystring = null;

                if (searchterms.Length > 0)
                {
                    querystring = string.Join(" ", searchterms);

                    SearchItem item = await _spotifyService.GetSearchResultAsync(querystring).ConfigureAwait(false);

                    if (item.Tracks.Items.Count > 0)
                    {
                        FullTrack    track       = item.Tracks.Items.FirstOrDefault();
                        SimpleArtist trackArtist = track.Artists.FirstOrDefault();

                        await ReplyAsync("https://open.spotify.com/track/" + track.Id).ConfigureAwait(false);

                        this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
                    }
                    else
                    {
                        await ReplyAsync("No results have been found for this track.").ConfigureAwait(false);
                    }
                }
                else
                {
                    await ReplyAsync("Please specify what you want to search for.").ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                _logger.LogException(Context.Message.Content, e);

                await ReplyAsync("Unable to search for music via Spotify due to an internal error.").ConfigureAwait(false);
            }
        }
Пример #19
0
        public ActionResult Index(string q)
        {
            _search  = q;
            _trackId = "";

            SearchResult searchResult = new SearchResult();

            if (!_search.NullCheck())
            {
                _search = _search.Decode();

                ViewBag.Title = string.Format("{0} - {1}", _search, Settings.SingleTitle);

                CustomToken token      = ViewBag.Token;
                SearchItem  searchItem = null;
                if (!token.IsTokenEmpty())
                {
                    searchItem = Search(_search, token);

                    if (searchItem != null && searchItem.Tracks != null &&
                        searchItem.Tracks.Items != null && searchItem.Tracks.Items.Count == 0)
                    {
                        var tempSearch = Regex.Replace(_search, "\\([^\\]]*\\)", "");
                        searchItem = Search(tempSearch, token);
                    }
                }
                else
                {
                    searchResult.IsTokenEmpty = true;
                }

                searchResult.SearchItem = searchItem;
                searchResult.query      = _search;
                searchResult.track      = _trackId;
            }

            return(View("Index", searchResult));
        }
Пример #20
0
        public SearchItem GetFile(SearchItem item)
        {
            try
            {
                if (item.Status != SearchItem.Statuses.Ok)
                    return item;

                using (var client = new WebClient())
                {
                    var fileContents = client.DownloadString(item.FilePath);

                    item.FileContents = (ContentsIsTextHtml(client)) ? fileContents : string.Empty;

                    return item;
                }
            }
            catch (Exception ex)
            {
                item.Status = SearchItem.Statuses.Failed;
                item.Error = new FileProviderException("Error getting url", ex);
                return item;
            }
        }
Пример #21
0
        public async Task <List <SpotifySong> > FetchAsync()
        {
            if (_apiNeedsReseting)
            {
                _searchItem = await _api.Api.SearchItemsAsync(Query, SearchType.Track);

                CheckForPageError(_searchItem);
                _page = _searchItem.Tracks;
            }
            else
            {
                _page = await _api.Api.GetNextPageAsync <FullTrack>(_searchItem.Tracks);
            }

            var result = new List <SpotifySong>();

            foreach (var track in _page.Items)
            {
                result.Add(ToSong(track));
            }

            return(result);
        }
Пример #22
0
        private void SetSearchChoice(SearchItem searchItem)
        {
            TripOptions.SetAsAddress(new Address(searchItem.Name, searchItem.Name, searchItem.Location));

            switch (this.Type)
            {
            case SearchType.Location:
                // Change text to the search item name.
                TextLocation = searchItem.Name;

                ClearButtonVisibilityLocation = Visibility.Visible;
                break;

            case SearchType.Destination:
                // Change text to the search item name.
                TextDestination = searchItem.Name;

                ClearButtonVisibilityDestination = Visibility.Visible;;
                break;
            }

            OnChanged(EventArgs.Empty);
        }
        public override void OnBindElements(View view)
        {
            AddItemFloatActionButton = view.FindViewById <FloatingActionButton>(Resource.Id.AddItemFloatActionButton);
            SearchItem              = view.FindViewById <AutoCompleteTextView>(Resource.Id.SearchItem);
            ItemList                = view.FindViewById <RecyclerView>(Resource.Id.ItemList);
            EmptyItemsView          = view.FindViewById <TextView>(Resource.Id.EmptyItemsView);
            LoadingItemsProgressBar = view.FindViewById <ProgressBar>(Resource.Id.LoadingItemsProgressBar);
            EmptyItemsView.Text     = Resources.GetString(_emptyItemsResourceStringId);
            SearchItem.Hint         = Resources.GetString(_searchItemsResourceStringId);
            AddItemFloatActionButton.SetOnClickListener(this);
            SearchItem.AddTextChangedListener(this);

            var layoutManager = new LinearLayoutManager(Context);

            layoutManager.Orientation = LinearLayoutManager.Vertical;
            ItemList.SetLayoutManager(layoutManager);
            var animationController = AnimationUtils.LoadLayoutAnimation(Context, Resource.Animation.layout_animation_fall_down);

            ItemList.LayoutAnimation = animationController;
            ItemList.ScheduleLayoutAnimation();

            SetLoadingContent();
        }
Пример #24
0
        /// <summary>
        /// 商户预收款余额明细查询
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public DataGridResult GetMerchantAccountDetail(SearchItem item)
        {
            string sql = @"SELECT M.*,A.NAME MERCHANTNAME,F.NAME FEE_ACCOUNTNAME,B.NAME BRANCHNAME,B.ID BRANCHID,D.CHANGE_TIME,D.REFERTYPE,D.REFERID, 
                D.BALANCE ACCOUNT,D.SAVE_MONEY,D.USE_MONEY  
	            from MERCHANT_ACCOUNT M ,MERCHANT_ACCOUNT_RECORD D, MERCHANT A,FEE_ACCOUNT F,BRANCH B,CONTRACT C 
                WHERE M.MERCHANTID=A.MERCHANTID AND M.FEE_ACCOUNT_ID=F.ID AND M.MERCHANTID=C.MERCHANTID 
                AND C.BRANCHID=B.ID AND D.MERCHANTID=M.MERCHANTID AND M.FEE_ACCOUNT_ID=D.FEE_ACCOUNT_ID ";

            item.HasKey("BRANCHID", a => sql       += $" and B.ID = {a}");
            item.HasKey("MERCHANTID", a => sql     += $" and A.MERCHANTID LIKE '%{a}%'");
            item.HasKey("MERCHANTNAME", a => sql   += $" and A.NAME  LIKE '%{a}%'");
            item.HasKey("FEE_ACCOUNT_ID", a => sql += $" and F.ID  = {a}");
            item.HasKey("REFERTYPE", a => sql      += $" and D.REFERTYPE  = {a}");
            item.HasKey("REFERID", a => sql        += $" and D.REFERID  = {a}");
            item.HasDateKey("STARTTIME", a => sql  += $" and trunc(D.CHANGE_TIME) >= {a}");
            item.HasDateKey("ENDTIME", a => sql    += $" and trunc(D.CHANGE_TIME) <= {a}");
            sql += " ORDER BY D.MERCHANTID,D.FEE_ACCOUNT_ID,D.CHANGE_TIME DESC ";
            int       count;
            DataTable dt = DbHelper.ExecuteTable(sql, item.PageInfo, out count);

            dt.NewEnumColumns <收款类型>("REFERTYPE", "REFERTYPENAME");
            return(new DataGridResult(dt, count));
        }
Пример #25
0
        /*************************************/
        /**** Public Methods              ****/
        /*************************************/

        public static Caller InstantiateCaller(SearchItem item)
        {
            try
            {
                Type type = item.CallerType;

                if (!m_ItemInstances.ContainsKey(type))
                {
                    m_ItemInstances[type] = Activator.CreateInstance(type as Type) as Caller;
                }


                Caller caller = m_ItemInstances[type].DeepClone();
                caller.SetItem(item.Item);

                return(caller);
            }
            catch (Exception e)
            {
                Engine.Reflection.Compute.RecordError($"Failed to instantiate {item.Text}.\nError: {e.Message}");
                return(null);
            }
        }
Пример #26
0
        public DataGridResult GetRateAdjustList(SearchItem item)
        {
            string sql = @"SELECT A.*,B.NAME BRANCHNAME FROM RATE_ADJUST A,BRANCH B
                    WHERE A.BRANCHID=B.ID ";

            item.HasKey("ADID", a => sql                    += $" and A.ID = {a}");
            item.HasKey("BRANCHID", a => sql                += $" and A.BRANCHID={a}");
            item.HasDateKey("DATE_START", a => sql          += $" and A.STARTTIME>={a}");
            item.HasDateKey("DATE_END", a => sql            += $" and A.ENDTIME<={a}");
            item.HasKey("STATUS", a => sql                  += $" and A.STATUS={a}");
            item.HasKey("REPORTER", a => sql                += $" and A.REPORTER={a}");
            item.HasDateKey("REPORTER_TIME_START", a => sql += $" and A.REPORTER_TIME>={a}");
            item.HasDateKey("REPORTER_TIME_END", a => sql   += $" and A.REPORTER_TIME<={a}");
            item.HasKey("VERIFY", a => sql                  += $" and L.VERIFY={a}");
            item.HasDateKey("VERIFY_TIME_START", a => sql   += $" and A.VERIFY_TIME>={a}");
            item.HasDateKey("VERIFY_TIME_END", a => sql     += $" and A.VERIFY_TIME<={a}");
            sql += " ORDER BY A.ID DESC";
            int       count;
            DataTable dt = DbHelper.ExecuteTable(sql, item.PageInfo, out count);

            dt.NewEnumColumns <普通单据状态>("STATUS", "STATUSMC");
            return(new DataGridResult(dt, count));
        }
Пример #27
0
        public async Task <IList <SearchItem> > convertToSearchItemList(IList <SearchItem> resultList, string pType, IList <Product> pList, IList <Bundle> bList)
        {
            if (!pType.Equals("bundle"))
            {
                foreach (Product p in pList)
                {
                    SearchItem temp = await convertToSearchItem(p, null, false, pType, 1);

                    resultList.Add(temp);
                }
            }
            else
            {
                foreach (Bundle b in bList)
                {
                    SearchItem temp = await convertToSearchItem(null, b, true, pType, 1);

                    resultList.Add(temp);
                }
            }

            return(resultList);
        }
Пример #28
0
        public DataGridResult GetBillReturnList(SearchItem item)
        {
            string sql = $@"SELECT L.*,B.NAME BRANCHNAME,D.MERCHANTID,D.NAME MERCHANTNAME " +
                         " FROM BILL_RETURN L,BRANCH B ,CONTRACT C,MERCHANT D " +
                         "  WHERE L.BRANCHID = B.ID and L.CONTRACTID=C.CONTRACTID(+) and C.MERCHANTID = D.MERCHANTID(+) ";

            item.HasKey("BILLID", a => sql   += $" and L.BILLID = {a}");
            item.HasKey("STATUS", a => sql   += $" and L.STATUS={a}");
            item.HasKey("REPORTER", a => sql += $" and L.REPORTER={a}");
            item.HasDateKey("REPORTER_TIME_START", a => sql += $" and L.REPORTER_TIME>={a}");
            item.HasDateKey("REPORTER_TIME_END", a => sql   += $" and L.REPORTER_TIME<={a}");
            item.HasKey("VERIFY", a => sql += $" and L.VERIFY={a}");
            item.HasDateKey("VERIFY_TIME_START", a => sql += $" and L.VERIFY_TIME>={a}");
            item.HasDateKey("VERIFY_TIME_END", a => sql   += $" and L.VERIFY_TIME<={a}");
            item.HasKey("CONTRACTID", a => sql            += $" and C.CONTRACTID={a}");
            item.HasKey("MERCHANTID", a => sql            += $" and C.MERCHANTID={a}");
            sql += " ORDER BY  L.BILLID DESC";
            int       count;
            DataTable dt = DbHelper.ExecuteTable(sql, item.PageInfo, out count);

            dt.NewEnumColumns <普通单据状态>("STATUS", "STATUSMC");
            return(new DataGridResult(dt, count));
        }
Пример #29
0
        public DetailView(SearchItem item)
        {
            InitializeComponent();

            currentItem = item;

            Title = item.Name;

            FC5Html htmlFc5 = null;

            switch (item.Type)
            {
            case SearchItem.ItemType.Spell:
                htmlFc5 = DataStorage.GetSpell(item.Name);
                break;

            case SearchItem.ItemType.Monster:
                htmlFc5 = DataStorage.GetMonster(item.Name);
                break;
            }

            webBrowser.NavigateToString(htmlFc5.ToHtml());
        }
Пример #30
0
        /// <summary>
        /// 弹窗选择账单
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public DataGridResult GetContract(SearchItem item)
        {
            string sql = " SELECT  A.* "
                         + " ,B.NAME MERCHANTNAME,C.NAME BRANCHNAME "
                         + " FROM CONTRACT A,MERCHANT B,BRANCH C " +
                         "  WHERE  A.MERCHANTID=B.MERCHANTID AND A.BRANCHID=C.ID";

            item.HasKey("MERCHANTID", a => sql += $" and A.MERCHANTID like '%{a}%'");
            item.HasKey("CONTRACTID", a => sql += $" and A.CONTRACTID = '{a}'");
            item.HasKey("STATUS", a => sql     += $" and A.STATUS = '{a}'");
            item.HasKey("BRANCHID", a => sql   += $" and A.BRANCHID = '{a}'");
            item.HasKey("REPORTER", a => sql   += $" and A.REPORTER = '{a}'");
            item.HasDateKey("REPORTER_TIME_START", a => sql += $" and A.REPORTER_TIME >= '{a}'");
            item.HasDateKey("REPORTER_TIME_END", a => sql   += $" and A.REPORTER_TIME <= '{a}'");
            item.HasKey("YXHTBJ", a => sql     += $" and A.STATUS in (2,3,4)");
            item.HasKey("FREESHOPBJ", a => sql += $" and not exists (select 1 from FREESHOP P where P.CONTRACTID = A.CONTRACTID)");

            int       count;
            DataTable dt = DbHelper.ExecuteTable(sql, item.PageInfo, out count);

            dt.NewEnumColumns <合同状态>("STATUS", "STATUSMC");
            return(new DataGridResult(dt, count));
        }
Пример #31
0
        public DataGridResult GetVoucherList(SearchItem item)
        {
            string sql = $@"SELECT L.* " +
                         " FROM VOUCHER L" +
                         "  WHERE 1=1  ";

            item.HasKey("VOUCHERID", a => sql               += $" and L.VOUCHERID = {a}");
            item.HasKey("VOUCHERNAME", a => sql             += $" and L.VOUCHERNAME like '%{a}%'");
            item.HasKey("STATUS", a => sql                  += $" and L.STATUS={a}");
            item.HasKey("REPORTER", a => sql                += $" and L.REPORTER={a}");
            item.HasDateKey("REPORTER_TIME_START", a => sql += $" and L.REPORTER_TIME>={a}");
            item.HasDateKey("REPORTER_TIME_END", a => sql   += $" and L.REPORTER_TIME<={a}");
            item.HasKey("VERIFY", a => sql                  += $" and L.VERIFY={a}");
            item.HasDateKey("VERIFY_TIME_START", a => sql   += $" and L.VERIFY_TIME>={a}");
            item.HasDateKey("VERIFY_TIME_END", a => sql     += $" and L.VERIFY_TIME<={a}");
            sql += " ORDER BY  L.VOUCHERID DESC";
            int       count;
            DataTable dt = DbHelper.ExecuteTable(sql, item.PageInfo, out count);

            dt.NewEnumColumns <账单类型>("VOUCHERTYPE", "VOUCHERTYPEMC");
            dt.NewEnumColumns <普通单据状态>("STATUS", "STATUSMC");
            return(new DataGridResult(dt, count));
        }
Пример #32
0
        /*****************************************************************/

        /**
         * @brief Solicita datos de una cancion en especifico. Retorna el identificador de la cancion.
         * @param partist El nombre del artista.
         * @param psong Nombre de la cancion que se quiere.
         * @return identificador de la canción.
         */
        public string searchTracks(string partist, string psong)
        {
            SearchItem item = _spotify.SearchItems(psong, SearchType.Track);
            string     id   = null;

            try
            {
                for (int i = 0; i < item.Tracks.Items.Count; i++)
                {
                    if (item.Tracks.Items[i].Artists[0].Name == partist)
                    {
                        id = item.Tracks.Items[i].Id;
                        break;
                    }
                }
            }
            catch (Exception)
            {
                id = "No_ID";
            }

            return((id == null) ? "No_ID" : id);
        }
Пример #33
0
            public bool Add(SearchItem item)
            {
                bool added    = true;
                var  itemHash = item.GetHashCode();

                if (m_IdHashes.Contains(itemHash))
                {
                    var startIndex = m_Items.BinarySearch(item, sortByScoreComparer);
                    if (startIndex < 0)
                    {
                        startIndex = ~startIndex;
                    }
                    var itemIndex = m_Items.IndexOf(item, Math.Max(startIndex - 1, 0));
                    if (itemIndex >= 0 && item.score < m_Items[itemIndex].score)
                    {
                        m_Items.RemoveAt(itemIndex);
                        m_IdHashes.Remove(itemHash);
                        added = false;
                    }
                    else
                    {
                        return(false);
                    }
                }

                var insertAt = m_Items.BinarySearch(item, sortByScoreComparer);

                if (insertAt < 0)
                {
                    insertAt = ~insertAt;
                    m_Items.Insert(insertAt, item);
                    m_IdHashes.Add(itemHash);
                    return(added);
                }

                return(false);
            }
Пример #34
0
        public HttpResponseMessage PerformSearch(PerformActiomSettingsViewModel settings)
        {
            var operationResults = new List <OperationResult>();

            if (settings.SearchTargets.Any() && !string.IsNullOrEmpty(settings.SearchText))
            {
                if (settings.HtmlEncode)
                {
                    settings.SearchText = HttpUtility.HtmlEncode(settings.SearchText);
                }

                foreach (var item in settings.SearchTargets)
                {
                    var tableName  = SearchItem.GetTableNameFromId(item.Id);
                    var columnName = SearchItem.GetColumnNameFromId(item.Id);
                    var pkColumns  = SqlDataProvider.GetPkColumns(tableName);

                    var searchResults = SqlDataProvider.GetSearchResults(tableName, pkColumns, columnName, settings.SearchText);

                    if (searchResults.Count > 0)
                    {
                        if (settings.DoReplace)
                        {
                            _ = SqlDataProvider.PerformReplace(tableName, columnName, settings.SearchText, settings.ReplaceText);
                        }

                        operationResults.Add(new OperationResult(tableName, columnName, BuildColumnsList(columnName, pkColumns), searchResults.Data, searchResults.Count));
                    }
                }
            }

            var jsonResults = JsonConvert.SerializeObject(operationResults);
            var res         = Request.CreateResponse(HttpStatusCode.OK);

            res.Content = new StringContent(jsonResults, Encoding.UTF8, "application/json");
            return(res);
        }
Пример #35
0
        /// <summary>
        /// Searches the spotify API for an track
        /// </summary>
        /// <returns>A task string with the id of the first found track.</returns>
        public async Task <String> SearchSpotifyTrackAsync()
        {
            try
            {
                String[] stringPairs = Msg.Content.Split(' ');
                if (stringPairs.Length > 1)
                {
                    CredentialsAuth auth  = new CredentialsAuth(Properties.Settings.Default.SpotifyClientID, Properties.Settings.Default.SpotifyClientSecret);
                    Token           token = await auth.GetToken();

                    SpotifyWebAPI _spotify = new SpotifyWebAPI()
                    {
                        AccessToken = token.AccessToken,
                        TokenType   = token.TokenType
                    };

                    //Search for the first track on Spotify
                    String     message = Msg.Content;
                    String     search  = message.Substring(message.IndexOf(" "));
                    SearchItem item    = _spotify.SearchItemsEscaped(search, SearchType.Track, 1);

                    return(item.Tracks.Items[0].Id);
                }

                return(rm.GetString("SearchSpotifyTrackAsyncMissingSearchTerm"));
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Logger logger = new Logger(ex.ToString());
                return(rm.GetString("SearchSpotifyTrackAsyncTrackNotFound") + "\r\n\r\n" + ex.ToString());
            }
            catch (Exception ex)
            {
                Logger logger = new Logger(ex.ToString());
                return(rm.GetString("SearchSpotifyTrackAsyncError") + "\r\n\r\n" + ex.ToString());
            }
        }
        public async Task <Stream> GetInfo(string adeId, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(adeId))
            {
                throw new ArgumentNullException("adeId");
            }

            var cachePath = Path.Combine(_appPaths.CachePath, "ade", _fileSystem.GetValidFilename(adeId), "item.html");

            var fileInfo = new FileInfo(cachePath);

            // Check cache first
            if (!fileInfo.Exists || (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 7)
            {
                var searchItem = new SearchItem {
                    Id = adeId
                };

                // Download and cache
                using (var stream = await _httpClient.Get(new HttpRequestOptions
                {
                    Url = searchItem.Url,
                    CancellationToken = cancellationToken,
                    ResourcePool = ResourcePool
                }))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(cachePath));

                    using (var fileStream = _fileSystem.GetFileStream(cachePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
                    {
                        await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                    }
                }
            }

            return(_fileSystem.GetFileStream(cachePath, FileMode.Open, FileAccess.Read, FileShare.Read));
        }
Пример #37
0
        public async Task <IActionResult> GetSpotify(string title)
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)
                );
            var spotifyID = await keyVaultClient.GetSecretAsync("https://wakeyvault.vault.azure.net/secrets/appSettings--connectionSettings--spotifyId/69cdf003254f4b2e81a5ce90dffe80ab").ConfigureAwait(false);

            var spotifySecret = await keyVaultClient.GetSecretAsync("https://wakeyvault.vault.azure.net/secrets/appSettings--connectionStrings--spotifySecret/49de24c1d0a44edcb4c7e9379b49d1a4").ConfigureAwait(false);

            CredentialsAuth auth  = new CredentialsAuth(spotifyID.Value, spotifySecret.Value);
            Token           token = await auth.GetToken();

            SpotifyWebAPI api = new SpotifyWebAPI()
            {
                TokenType   = token.TokenType,
                AccessToken = token.AccessToken
            };

            SearchItem searchItem = api.SearchItems(title, SearchType.Track);


            return(Ok(searchItem.Tracks.Items[0]));
        }
Пример #38
0
 private void dataView_RowValidated(object sender, DataGridViewCellEventArgs e)
 {
     try
     {
         if (e.RowIndex >= SearchList.Count && e.RowIndex != dataView.Rows.Count)
         {
             SearchList.Add(curEdit);
             curEdit    = null;
             currentRow = -1;
         }
         else if (curEdit != null && e.RowIndex < SearchList.Count)
         {
             SearchList.Set(e.RowIndex, curEdit);
             curEdit    = null;
             currentRow = -1;
         }
         else if (dataView.ContainsFocus)
         {
             curEdit    = null;
             currentRow = -1;
         }
     }
     catch { }
 }
Пример #39
0
        public async Task <ActionResult> SpotifyArtistSearch(string Keyword, string Genre)
        {
            string ArtistString = "";

            if (ModelState.IsValid)
            {
                SearchItem ArtistSearch = await SpotifyHelper.GrabArtists(Keyword);

                List <FullArtist> searchedArtists = ArtistSearch.Artists.Items; // this list acts like an array?
                int      arraySize   = searchedArtists.Count();
                string[] ArtistArray = new string[arraySize];


                for (int i = 0; i <= arraySize - 1; i++)
                {
                    if (Genre == "") //leave genre blank to grab 50 artists
                    {
                        ArtistArray[i] = searchedArtists[i].Name;
                    }
                    else if (searchedArtists[i].Genres.Contains(Genre))

                    {
                        ArtistString  += searchedArtists[i].Name + ", ";
                        ArtistArray[i] = searchedArtists[i].Name;
                    }
                }
                TempData["ArtistsByGenre"] = ArtistArray;
            }
            else
            {
                TempData["ArtistsByGenre"] = "Whoops something went wrong!";
            }


            return(View());
        }
Пример #40
0
        private void AddSearchItems(CompositeCollection cc)
        {
            SearchItem b = new SearchItem();

            b.SearchObject   = new RMSDataAccessLayer.Transactionlist();
            b.SearchCriteria = "Transaction History";
            b.DisplayName    = "Transaction History";
            cc.Add(b);

            if (ApplicationMode == SalesRegion.ApplicationMode.Pharmacy)
            {
                SearchItem p = new SearchItem();
                p.SearchObject   = null;
                p.SearchCriteria = "Add Patient";
                p.DisplayName    = "Add Patient";
                cc.Add(p);

                SearchItem d = new SearchItem();
                d.SearchObject   = null;
                d.SearchCriteria = "Add Doctor";
                d.DisplayName    = "Add Doctor";
                cc.Add(d);
            }
        }
Пример #41
0
 private void LogSuccess(SearchItem item)
 {
     _logWriter.WriteLine("\"{0}\",\"{1}\",\"{2}\"", item.FilePath, item.ImageUrl, item.ShortUrl);
 }
Пример #42
0
        //not a really good search engine
        public List<SearchItem> Search(string searchString, IUser user)
        {
            #region new filesearch
            try{

            DataTable dt = _db.Select("SELECT filename,md5 " +
                                      "FROM files");

            FileSearcher fs = new FileSearcher();

            foreach(DataRow dr in dt.Rows)
            {
                DBFile dbfile = new DBFile();
                dbfile.Name = dr.ItemArray[0].ToString();
                dbfile.MD5 = dr.ItemArray[1].ToString();
                fs.Search(dbfile, searchString);
            }

            }catch(Exception e)
            {
                Debug.WriteLine("Server: New Search. "+e.Message);
            }
            #endregion

            #region thestandard be replaced soon
            if(!CheckUserIntegrity(user))
                return null;

            if(searchString.Length < 3 || searchString.Length > 50)
                return null;

            // search algo gone easy: one hit gets 100%

            List<SearchItem> si = new List<SearchItem>();

            try{

            DataTable dt = _db.Select("SELECT user " +
                                      "FROM interests " +
                                      "WHERE content = '"+searchString+"'");

            foreach(DataRow dr in dt.Rows)
            {
                SearchItem s = new SearchItem();
                s.PercentageHit = 100;
                s.User = int.Parse(dr.ItemArray[0].ToString());
                s.UserLastSeen = DateTime.Now.Ticks;
                si.Add(s);
            }

            }catch(Exception e)
            {
                Console.Write(e);
            }

            return si;
            #endregion
        }
 private string GetKBName(SearchItem results)
 {
     string kbName = string.Empty;
     if (results.SourceType == "Articles")
     {
         KnowledgeBase KB = _portal.Knowledgebases.FirstOrDefault(Q => Q.Id == results.KbId);
         if (KB != null)
         {
             kbName = KB.Name;
         }
     }
     return kbName;
 }
 private void GetFileFormatCounts(Dictionary<string, string> fileFormatCounts, SearchItem results, string FileExtn)
 {
     if (!fileFormatCounts.ContainsKey(FileExtn))
     {
         string extension = GetOfficeExtensions(FileExtn);
         if (extension != string.Empty)
         {
             fileFormatCounts.Add(FileExtn, extension);
         }
         else
         {
             fileFormatCounts.Add(FileExtn, results.FileExtn);
         }
     }
 }
 private string GetAutoSummarizationEnabled(SearchModule searchModule, SearchItem results, string searchString)
 {
     string autoSummEnabled = string.Empty;
     if (searchModule.AutoSummarizationEnabled)
     {
         if (_portal.ArticleTemplateBodySecurity)
         {
             if (results.ArtTemplateId > 0)
             {
                 string groups = string.Join(",", _portal.ArticleGroups.Select(arr => arr.Id.ToString()));
                 autoSummEnabled = _searchesManager.GetArticleSecuredSummary(results.Id, results.KbId, groups, results.FileExtn, searchModule.AutoSummarization.MaxLength, searchString, searchModule.ResultsDisplay.HighlightTerm);
             }
             else
             {
                 autoSummEnabled = results.Summary;
             }
         }
         else
         {
             autoSummEnabled = results.Summary;
         }
     }
     return autoSummEnabled;
 }
        private string GetArticleNames(SearchItem results)
        {
            string AttributeNames = string.Empty;

            // Get article names from DB
            if (!string.IsNullOrEmpty(results.ArtAttributeIds))
            {
                if (results.ArtAttributeIds != "0")
                {
                    var Attributes = _searchesManager.GetAttributesByIds(results.ArtAttributeIds.ToString());
                    if (Attributes.Count > 0)
                    {
                        AttributeNames = String.Join(",", Attributes);
                    }
                }
            }
            return AttributeNames;
        }
 private void MoveLeftRun(SearchItem item)
 {
     if (UsedItems.Remove(item))
       {
     UnusedItems.Add(item);
       }
 }
 private void MoveRightRun(SearchItem item)
 {
     if (UnusedItems.Remove(item))
       {
     UsedItems.Insert(SelectedUsedIndex+1,item);
     SelectedUsedIndex = UsedItems.IndexOf(item);
       }
 }
Пример #49
0
        /// <summary>
        /// Gets called from the background thread whenever the background search finishes
        /// </summary>
        /// <param name="si">Search item</param>
        private void BackgroundSearchFinished(SearchItem si)
        {
            if (searchIdentifier == si.SearchIdentifier &&
                String.IsNullOrEmpty(si.Hits.ErrorMessages))
            {
                loadingResults = true;

                hitsBox.DataSource = si.Hits;
                hitsBox.SelectedItem = null;

                loadingResults = false;

                searchStatusLabel.Text = si.Hits.HadMoreHits ? String.Format(Properties.Resources.ShowingXTopResults, Indexer.MAX_SEARCH_HITS.ToString()) : String.Empty;
            }
            else
            {
                searchStatusLabel.Text = String.Empty;
            }
        }
Пример #50
0
        /// <summary>
        /// Populates the main form filters the images in the database using the string specified in the search field.
        /// </summary>
        private void PerformSearch()
        {
            if (string.IsNullOrEmpty(tSICB_search.Text)) return;
            string keyword = tSICB_search.Text.ToLowerInvariant();
            SearchItem item = new SearchItem(keyword, _searchCriterion);
            if (!_searchKeywords.Contains(item))
            {
                _searchKeywords.Add(item);
                ImageComboBoxItem displayItem = new ImageComboBoxItem(keyword);
                string imageKey = "";
                switch (_searchCriterion)
                {
                    case SearchCriterion.Product: imageKey = "product"; break;
                    case SearchCriterion.ProductWithLicense: imageKey = "productwithlicense"; break;
                    case SearchCriterion.UserWithLicense: imageKey = "userwithlicense"; break;
                    case SearchCriterion.LicenseByProduct: imageKey = "licensebyuser"; break;
                    case SearchCriterion.LicenseByUser: imageKey = "licensebyproduct"; break;
                    default: imageKey = "product"; break;
                }
                displayItem.ImageKey = imageKey;
                tSICB_search.Items.Add(displayItem);
            }

            SelectControls(item.SearchCriterion);

            switch (_searchCriterion)
            {
                case SearchCriterion.Product:
                    SearchProduct();
                    break;
                case SearchCriterion.UserWithLicense:
                    SearchUserWithLicense();
                    break;
                case SearchCriterion.ProductWithLicense:
                    SearchProductWithLicense();
                    break;

                case SearchCriterion.LicenseByUser:
                    SearchLicenseByUser();
                    break;

                case SearchCriterion.LicenseByProduct:
                    SearchLicenseByProduct();
                    break;

                default:
                    SearchProduct();
                    break;
            }
        }
Пример #51
0
        /// <summary>
        /// Searches for the specified term in the index.
        /// </summary>
        /// <param name="term">The term.</param>
        public static HitCollection Search(string term, IEnumerable<Indexer> indexers, int maxResults)
        {
            foreach (Indexer ixr in indexers)
            {
                if (!ixr.indexExists ||
                    ixr.searcher == null)
                {
                    throw new Exception("The index does not exist for " + ixr.filePath);
                }
            }

            string searchRequest = String.Format("title:{0} AND -\"Image:\"", term);

            HitCollection ret = new HitCollection();

            SearchItem si = new SearchItem();

            si.Hits = ret;
            si.SearchRequest = searchRequest;
            si.MaxResults = maxResults;

            // I can't really be sure about the thread safety of Lucene

            lock (typeof(Indexer))
            {
                foreach (Indexer ixr in indexers)
                {
                    int i = 0;

                    while (ixr.searchRunning &&
                        i < 30)
                    {
                        Thread.Sleep(100);

                        i++;
                    }

                    if (i >= 30)
                    {
                        throw new Exception("Failed starting the search work item due to timeout");
                    }

                    ixr.searchRunning = true;
                }

                foreach (Indexer ixr in indexers)
                {
                    ThreadPool.QueueUserWorkItem(ixr.Search, si);
                }

                foreach (Indexer ixr in indexers)
                {
                    int i = 0;

                    while (ixr.searchRunning &&
                        i < 100)
                    {
                        Thread.Sleep(100);

                        i++;
                    }

                    if (i >= 30)
                    {
                        throw new Exception("Failed finishing the search work item due to timeout");
                    }
                }
            }

            return ret;
        }
 private bool LeftRightCanRun(SearchItem item)
 {
     return item != null;
 }
 private void MoveUpRun(SearchItem item)
 {
     int index = _usedItems.IndexOf(item);
       _usedItems.RemoveAt(index);
       _usedItems.Insert(index - 1, item);
       SelectedUsedIndex = index - 1;
 }
 private bool MoveUpCanRun(SearchItem item)
 {
     if (item == null) return false;
       if (_usedItems.IndexOf(item) == 0) return false;
       return true;
 }
Пример #55
0
 private void LogError(SearchItem item)
 {
     _errorWriter.WriteLine("File: {0}", item.FilePath);
     _errorWriter.WriteLine("Image: {0}", item.ImageUrl);
     _errorWriter.WriteLine("ShortUrl: {0}", item.ShortUrl);
     _errorWriter.WriteLine("Error: {0}", item.Error.BuildLog());
     _errorWriter.WriteLine();
 }
        private static void GetArticleCounts(Dictionary<int, int> categoryCounts, Dictionary<int, int> attributeCounts, Dictionary<int, int> KBCounts, SearchItem results)
        {
            // Get article KB counts
            string[] articleKBs = results.KbId.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (articleKBs.Length == 0)
            {
                if (KBCounts.ContainsKey(0)) KBCounts[0]++;
                else KBCounts[0] = 1;
            }
            for (int j = 0; j < articleKBs.Length; j++)
            {
                if (KBCounts.ContainsKey(Convert.ToInt32(articleKBs[j]))) KBCounts[Convert.ToInt32(articleKBs[j])]++;
                else KBCounts[Convert.ToInt32(articleKBs[j])] = 1;
            }

            // Get article category counts
            string[] articleCats = null;
            if (!string.IsNullOrEmpty(results.ArtCategoryIds))
            {
                articleCats = results.ArtCategoryIds.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                if (articleCats.Length == 0)
                {
                    if (categoryCounts.ContainsKey(0)) categoryCounts[0]++;
                    else categoryCounts[0] = 1;
                }
                for (int j = 0; j < articleCats.Length; j++)
                {
                    if (categoryCounts.ContainsKey(Convert.ToInt32(articleCats[j]))) categoryCounts[Convert.ToInt32(articleCats[j])]++;
                    else categoryCounts[Convert.ToInt32(articleCats[j])] = 1;
                }
            }
            // Get article attribute counts
            if (!string.IsNullOrEmpty(results.ArtAttributeIds))
            {
                string[] articleAttributes = results.ArtAttributeIds.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                if (articleAttributes.Length == 0)
                {
                    if (attributeCounts.ContainsKey(0)) attributeCounts[0]++;
                    else attributeCounts[0] = 1;
                }
                for (int j = 0; j < articleAttributes.Length; j++)
                {
                    if (attributeCounts.ContainsKey(Convert.ToInt32(articleAttributes[j]))) attributeCounts[Convert.ToInt32(articleAttributes[j])]++;
                    else attributeCounts[Convert.ToInt32(articleAttributes[j])] = 1;
                }
            }
        }
Пример #57
0
        /// <summary>
        /// Executes the search using the currently entered text
        /// </summary>
        private void LaunchSearch(bool interactive)
        {
            if (indexes.Count == 0)
            {
                return;
            }

            searchStatusLabel.Text = String.Format(Properties.Resources.SearchingForTerm, searchBox.Text);

            searchLaunched = true;

            searchIdentifier++;

            if (!interactive)
            {
                SearchItem si = new SearchItem();

                si.SearchIdentifier = searchIdentifier;
                si.SearchText = searchBox.Text;

                ThreadPool.QueueUserWorkItem(BackgroundSearch, si);

                return;
            }

            HitCollection hits = Indexer.Search(searchBox.Text, indexes.Values, Indexer.MAX_SEARCH_HITS);

            searchStatusLabel.Text = String.Empty;

            if (String.IsNullOrEmpty(hits.ErrorMessages))
            {
                loadingResults = true;

                hitsBox.DataSource = hits;
                hitsBox.SelectedItem = null;

                loadingResults = false;

                if (hits.HadMoreHits)
                {
                    searchStatusLabel.Text = String.Format(Properties.Resources.ShowingXTopResults, Indexer.MAX_SEARCH_HITS.ToString());
                }

                if (hits.Count > 0)
                {
                    hitsBox.SetSelected(0, true);

                    PageInfo page = hitsBox.SelectedItem as PageInfo;

                    webBrowser.Navigate(WebServer.Instance.GenerateUrl(page));
                }
            }
            else
            {
                MessageBox.Show(this, hits.ErrorMessages, Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void AddSearchResultsViewModel(string AttributeNames, string summary, SearchItem results, string FileExtn, string kbName)
        {
            SearchResultsViewModel searchResultsModel = new SearchResultsViewModel()
            {
                Id = results.Id, //Artilce Id
                SFId = results.SFId,  // Solution FInder Id
                SFCId = results.SFCId, // Solution Finder Choice Id
                Title = results.Title,
                Summary = summary,
                Modified = results.ModifiedDate.ToShortDateString(),
                KBName = kbName,
                SourceName = results.SourceName,
                SourceType = results.SourceType,
                Size = results.FileSize,
                Attributes = AttributeNames,
                FileType = FileExtn
            };

            searchMainViewModel.SearchResultsViewModel.Add(searchResultsModel);
        }
Пример #59
0
 private void button1_Click(object sender, EventArgs e)
 {
     SearchItem item = new SearchItem()
     {
         Provider="aa",
         StoryName= "aaa",
         StoryUrl = "url"
     };
     lvLastestUpdates.AddObject(item);
     lvLastestUpdates.EnsureModelVisible(item);
 }
 private bool MoveDownCanRun(SearchItem item)
 {
     if (item == null) return false;
       if (_usedItems.IndexOf(item) == (_usedItems.Count - 1)) return false;
       return true;
 }